0% found this document useful (0 votes)
55 views16 pages

Introduction To Python (Notes)

Uploaded by

Ifrah Diane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
55 views16 pages

Introduction To Python (Notes)

Uploaded by

Ifrah Diane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

Created by Turbolearn AI

Getting Started with Python

What is Python?
Python is a multi-purpose programming language that can be used for various tasks
such as machine learning, web development, and automation.

Uses of Python
Some popular uses of Python include:

Machine Learning and AI: Python is the number one language for machine
learning and data science projects.
Web Development: Python can be used to build amazing websites using
frameworks like Django.
Automation: Python can be used to automate repetitive tasks and increase
productivity.

Installing Python
To get started with Python, you need to download and install the latest version from
the official Python website: python.org.

Setting up a Code Editor


A code editor is a program that allows you to write and execute code. The most
popular code editor for Python is PyCharm. You can download the community edition
for free from jetbrains.com/pycharm.

Writing Your First Python Code

Printing to the Terminal


To print a message to the terminal, you can use the print() function.

Page 1
Created by Turbolearn AI

print("Hello, World!")

Variables
A variable is a name given to a value. You can use variables to store data in a
computer's memory.

A variable is a name given to a value. It's a way to store data in a


computer's memory.

Declaring Variables
To declare a variable, you need to give it a name and assign it a value.

age = 20

Printing Variables
You can print the value of a variable using the print() function.

print(age)

Changing Variable Values


You can change the value of a variable by assigning it a new value.

age = 30
print(age)

Page 2
Created by Turbolearn AI

Data Types
Python has several data types, including:

Data Type Description

Integer A whole number, e.g. 1, 2, 3, etc.


Float A number with a decimal point, e.g. 3.14, -0.5, etc.
String A sequence of characters, e.g. "hello", 'hello', etc.
Boolean A true or false value, e.g. True, False

String Concatenation
You can combine strings using the + operator.

name = "John"
print("Hello, " + name)

Receiving Input from the User


You can use the input() function to read a value from the terminal window.

Page 3
Created by Turbolearn AI

name = input("What is your name? ")


print("Hello, " + name)
```## Type Conversion in Python

Python has three main types of data: **numbers**, **strings**, and **boole

### Converting Types

Python has several built-in functions for converting the types of variable

| Function | Description |
| --- | --- |
| `int()` | Converts a value to an integer |
| `float()` | Converts a value to a floating-point number |
| `bool()` | Converts a value to a boolean |
| `str()` | Converts a value to a string |

### Example: Converting a String to an Integer

When using the `input()` function, the returned value is a string. To conv

```python
birth_year = input("Enter your birth year: ")
age = 2020 - int(birth_year)
print(age)

Example: Creating a Basic Calculator Program


To create a basic calculator program, you need to convert the input values to
numbers.

first = float(input("Enter the first number: "))


second = float(input("Enter the second number: "))
sum = first + second
print("Sum is " + str(sum))

String Methods
In Python, a string is an object that has several methods. These methods are
functions that are specific to strings.

Page 4
Created by Turbolearn AI

Methods of a String Object


upper(): Converts a string to uppercase
lower(): Converts a string to lowercase
find(): Returns the index of the first occurrence of a character or sequence of
characters
replace(): Replaces a character or sequence of characters with another string

Example: Using String Methods

course = "Python for Beginners"


print(course.upper()) # Output: PYTHON FOR BEGINNERS
print(course.lower()) # Output: python for beginners
print(course.find("y")) # Output: 1
print(course.replace("4", "Four")) # Output: Python for Beginners

"In Python, a string is an object that has several methods. These methods
are functions that are specific to strings."## String Methods

The replace() Method


The replace() method is used to replace a character or a sequence of characters in a
string with another character or sequence of characters.

"The replace() method returns a new string with the replaced characters,
it does not modify the original string."

For example, if we try to replace 'x' with '4' in a string that does not contain 'x',
nothing will happen.

The find() Method and the in Operator


The find() method is used to find the index of the first occurrence of a character or a
sequence of characters in a string. The in operator is used to check if a character or a
sequence of characters is present in a string.

Page 5
Created by Turbolearn AI

"The in operator returns a boolean value, which is more desirable in many


cases."

For example, we can use the in operator to check if the word 'python' is present in a
string.

course = "I'm learning python"


print('python' in course) # Output: True

Arithmetic Operations

Arithmetic Operators
Python has the following arithmetic operators:

Operator Description

+ Addition
- Subtraction
* Multiplication
/ Division (returns a floating point number)
// Division (returns an integer)
% Modulus (returns the remainder of the division)
** Exponentiation

Augmented Assignment Operators


Python has augmented assignment operators that can be used to perform arithmetic
operations and assign the result to a variable.

Page 6
Created by Turbolearn AI

Operator Description

+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
//= Integer division assignment
%= Modulus assignment
**= Exponentiation assignment

For example, we can use the += operator to increment the value of a variable.

x = 10
x += 3
print(x) # Output: 13

Operator Precedence
Python has a set of rules that determine the order in which operators are applied.
These rules are similar to the rules of operator precedence in mathematics.

"Operator precedence determines the order in which operators are applied


in an expression."

For example, in the expression 10 + 3 * 2, the multiplication operator has higher


precedence than the addition operator, so the expression is evaluated as 10 + (3 *
2).

Comparison Operators

Comparison Operators
Python has the following comparison operators:

Page 7
Created by Turbolearn AI

Operator Description

> Greater than


>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to

For example, we can use the > operator to compare two values.

x = 3
y = 2
print(x > y) # Output: True

Logical Operators

Logical Operators
Python has the following logical operators:

Operator Description

and Logical and


or Logical or
not Logical not

For example, we can use the and operator to combine two boolean expressions.

price = 25
print(price > 10 and price < 30) # Output: True

If Statements

Page 8
Created by Turbolearn AI

If Statements
If statements are used to make decisions in Python programs. They consist of a
condition and a block of code that is executed if the condition is true.

"If statements are used to control the flow of a program."

For example, we can use an if statement to print a message based on the value of a
variable.

temperature = 35
if temperature > 30:
print("It's a hot day")
print("Drink plenty of water")
```## Conditional Statements

Conditional statements are used to make decisions in a program based on ce

### If Statements

An **if statement** is used to execute a block of code if a certain condit

* The condition is specified after the `if` keyword and is followed by a c


* The block of code to be executed is indented under the `if` statement.
* The block of code is only executed if the condition is true.

> "A block of code is a group of statements that are executed together."

### Example of an If Statement

```python
if temperature > 30:
print("It's hot!")
print("Stay cool!")

Else If Statements
An else if statement is used to check another condition if the initial condition is false.

The else if statement is used to specify an additional condition to check.


The block of code to be executed is indented under the else if statement.
The block of code is only executed if the condition is true.

Page 9
Created by Turbolearn AI

Example of an Else If Statement

if temperature > 30:


print("It's hot!")
print("Stay cool!")
elif temperature > 20:
print("It's nice!")

Else Statements
An else statement is used to specify a block of code to execute if none of the
previous conditions are true.

The else statement is used to specify the block of code to execute.


The block of code is only executed if none of the previous conditions are true.

Example of an Else Statement

if temperature > 30:


print("It's hot!")
print("Stay cool!")
elif temperature > 20:
print("It's nice!")
else:
print("It's cold!")

Weight Converter Program


The weight converter program is an example of how to use if statements to make
decisions in a program.

Input Output

Weight in pounds Weight in kilograms


Weight in kilograms Weight in pounds

Page 10
Created by Turbolearn AI

Code for the Weight Converter Program

weight = int(input("Enter your weight: "))


unit = input("Is your weight in kilograms or pounds? (k/p): ")

if unit.upper() == "K":
converted_weight = weight / 0.45
print("Weight in pounds is", str(converted_weight))
else:
converted_weight = weight * 0.45
print("Weight in kilograms is", str(converted_weight))

While Loops
A while loop is used to repeat a block of code multiple times.

The condition is specified after the while keyword and is followed by a colon (:).
The block of code to be executed is indented under the while statement.
The block of code is executed as long as the condition is true.

Example of a While Loop

i = 1
while i <= 5:
print(i)
i += 1

Table of While Loop Iterations

Iteration Value of i Output

1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

Page 11
Created by Turbolearn AI

What are Lists?


A list is a collection of items that can be of any data type, including
strings, integers, floats, and other lists.

Creating a List
To create a list, we use square brackets [] and add items inside them, separated by
commas.

names = ["John", "Bob", "Marsh", "Sam", "Mary"]

Accessing List Elements


We can access individual elements in a list using their index. The index of the first
element is 0.

print(names[0]) # Output: John

We can also use negative indices to access elements from the end of the list.

print(names[-1]) # Output: Mary

Modifying List Elements


We can modify an element at a given index by assigning a new value to it.

names[0] = "Jon"
print(names) # Output: ["Jon", "Bob", "Marsh", "Sam", "Mary"]

Page 12
Created by Turbolearn AI

Slicing a List
We can select a range of values from a list using slicing.

print(names[0:3]) # Output: ["Jon", "Bob", "Marsh"]

List Methods

Method Description

append() Adds an element to the end of the list


insert() Inserts an element at a given index
remove() Removes the first occurrence of an element
clear() Removes all elements from the list
in Checks if an element is in the list
len() Returns the number of elements in the list

Using List Methods

numbers = [1, 2, 3, 4, 5]

numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]

numbers.insert(0, -1)
print(numbers) # Output: [-1, 1, 2, 3, 4, 5, 6]

numbers.remove(3)
print(numbers) # Output: [-1, 1, 2, 4, 5, 6]

numbers.clear()
print(numbers) # Output: []

print(1 in numbers) # Output: False

print(len(numbers)) # Output: 0

Page 13
Created by Turbolearn AI

Iterating Over a List


We can iterate over a list using a for loop.

numbers = [1, 2, 3, 4, 5]

for item in numbers:


print(item)

We can also use a while loop to iterate over a list, but it's less efficient.

numbers = [1, 2, 3, 4, 5]
i = 0

while i < len(numbers):


print(numbers[i])
i += 1
```## The Range Function in Python

The **range function** is a built-in function in Python that generates a s

> A **range object** is an object that can store a sequence of numbers.

The range function can take one, two, or three arguments.

| Argument | Description |
| --- | --- |
| One argument | The ending value (exclusive) |
| Two arguments | The starting value and the ending value (exclusive) |
| Three arguments | The starting value, the ending value (exclusive), and

### One Argument

When one argument is passed to the range function, it generates a sequence

```python
numbers = range(5)
for number in numbers:
print(number)

Two Arguments

Page 14
Created by Turbolearn AI

When two arguments are passed to the range function, the first argument is
considered the starting value and the second argument is considered the ending
value (exclusive).

numbers = range(5, 10)


for number in numbers:
print(number)

Three Arguments
When three arguments are passed to the range function, the third argument is used
as the step.

numbers = range(5, 10, 2)


for number in numbers:
print(number)

Tuples in Python
Tuples are a type of data structure in Python that are similar to lists, but are
immutable.

A tuple is a sequence of objects that cannot be changed once created.

Tuples are defined using parentheses () instead of square brackets [] like lists.

Characteristics of Tuples
Immutable: Tuples cannot be changed once created.
No append, insert, or remove methods.
Only have count and index methods.
Method Description

count() Returns the number of occurrences of an element


index() Returns the index of the first occurrence of an element

Page 15
Created by Turbolearn AI

Example

numbers = (1, 2, 3)
print(numbers.count(3)) # Output: 1
print(numbers.index(2)) # Output: 1
```<script type="text/javascript">
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']]
}
};
</script>
<script type="text/javascript" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>

Page 16

You might also like