Python Programming
Python Variables
In Python, variables are used to store data that can be referenced and manipulated
during program execution. A variable is essentially a name that is assigned to a
value. Unlike many other programming languages, Python variables do not require
explicit declaration of type. The type of the variable is inferred based on the value
assigned.
Variables act as placeholders for data. They allow us to store and reuse values in
our program.
Example:
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
● A variable name must start with a letter or the underscore character
● A variable name cannot start with a number
● A variable name can only contain alphanumeric characters and underscores
(A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different
variables)
● A variable name cannot be any of the Python keywords.
Variable Names
myvar = "John" 2myvar = "John"
my_var = "John" my-var = "John"
_my_var = "John"
my var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Variable Names
LEGAL:
ILLEGAL:
myvar = "John"
my_var = "John"
2myvar = "John"
_my_var = "John" my-var = "John"
myVar = "John"
my var = "John"
MYVAR = "John"
myvar2 = "John"
Multi Words Variable Names
Pascal Case
Camel Case
Each word starts with a capital letter:
Each word, except the first, starts with a capital letter:
MyVariableName = "John"
myVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Assign Multiple Values
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Assign Multiple Values
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in
one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Assign Multiple Values
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Assign Multiple Values
Many Values to Multiple Variables
And you can assign the same value to multiple variables in
one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Assign Multiple Values
Many Values to Multiple Variables
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Assign Multiple Values
Many Values to Multiple Variables
If you have a collection of values in a list, tuple etc. Python allows
you to extract the values into variables. This is called unpacking.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
EXERCISE
Swapping Variables
# Assign the value 5 to 'var1' and 10 to 'var2'.
# Swap the values of 'var1' and 'var2' without using a temporary variable.
# Print the new values of 'var1' and 'var2'.
EXERCISE
Swapping Variables
# Assign the value 5 to 'var1' and 10 to 'var2'.
# Swap the values of 'var1' and 'var2' without using a temporary variable.
# Print the new values of 'var1' and 'var2'.
EXERCISE
Variable Type Conversion
# Assign the string "123" to a variable named 'num_str'.
# Convert 'num_str' to an integer and store the result in a variable named 'num_int'.
# Print the value of 'num_int' and its type.
EXERCISE
Variable Type Conversion
# Assign the string "123" to a variable named 'num_str'.
# Convert 'num_str' to an integer and store the result in a variable named 'num_int'.
# Print the value of 'num_int' and its type.
DATA TYPES
Numeric Data Types in Python
Int, or integer, is a whole number, positive or
negative, without decimals, of unlimited length.
z = -3255522
There are three numeric types in
Python: Float, or "floating point number" is a number,
positive or negative, containing one or more decimals.
● int
● float z = -35.59
● complex
Complex numbers are written with a "j" as the
imaginary part
z = -5j
Python Strings
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
Example:
a = "Hello, World!"
print(a[1])
String Length
To get the length of a string, use the len() function.
Python Lists
Lists are used to store multiple items in a single variable.
Lists are created using square brackets:
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Python - Access List Items
List items are indexed and you can access them by referring to the index number:
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Python - Access List Items - Range of Indexes
You can specify a range of indexes by specifying where to start and where to end
the range.
When specifying a range, the return value will be a new list with the specified items.
Note: The search will start at index 2 (included) and end at index 5 (not included).
Python - Access List Items - Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the list:
Python - Add List Items
Append Items
To add an item to the end of the list, use the append() method:
Python - Add List Items
Extend List
To append elements from another list to the current list, use the extend()
method.
Python - Remove List Items
Remove Specific Item
The remove() method removes the specified item.
Python - Remove List Items
Remove Specific Index
The pop() method removes the specified index.
Python - Loop Lists
You can loop through the list items by using a for loop:
Python - Loop Lists
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Tuples
❏ Tuples are used to store multiple items in a single variable.
❏ Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary, all with
different qualities and usage.
❏ A tuple is a collection which is ordered and unchangeable.
❏ Tuples are written with round brackets.
Python Sets
❏ Sets are used to store multiple items in a single variable.
❏ A set is a collection which is unordered, unchangeable*, and unindexed.
❏ Unordered means that the items in a set do not have a defined order.
❏ Sets cannot have two items with the same value.
❏ Unindexed means you cannot access items in a set by referring to an
index or a key.
Python Sets
Python Dictionaries
❏ Dictionaries are used to store data values in key:value pairs.
❏ Dictionary items are ordered, changeable, and do not allow duplicates.
❏ Dictionary items are presented in key:value pairs, and can be referred to
by using the key name.
Python Dictionaries
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Python Dictionaries
Change Values
You can change the value of a specific item by referring to its key name:
Python Dictionaries
Loop Through a Dictionary
Python Dictionaries
Loop Through a Dictionary
Key:
Values:
Python - Nested Dictionaries
A dictionary can contain dictionaries,
this is called nested dictionaries.
Python - Nested Dictionaries
A dictionary can contain dictionaries,
this is called nested dictionaries.
PYTHON
CONDITIONS
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
If statements
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope
in the code. Other programming languages often use curly-brackets for this
purpose.
If statements
An "if statement" is written by using the if keyword.
The elif keyword is Python's way of saying "if the
previous conditions were not true, then try this
condition".
The else keyword catches anything which isn't
caught by the preceding conditions.
If statements
An "if statement" is written by using the if keyword.
The elif keyword is Python's way of saying "if the
previous conditions were not true, then try this
condition".
The else keyword catches anything which isn't
caught by the preceding conditions.
If statements
If statements
If statements
Nested If
You can have if statements inside if statements, this is called nested if statements.
If statements
Nested If
You can have if statements inside if statements, this is called nested if statements.
WHAT IS THE OUTPUT?
WHAT IS THE OUTPUT?
PYTHON LOOPS
Python While Loops
With the while loop we can execute a set of statements as long as a
condition is true.
Python While Loops
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Python While Loops
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Python While Loops
The continue Statement
With the continue statement we can stop the current iteration, and continue with
the next:
Python While Loops
The continue Statement
With the continue statement we can stop the current iteration, and continue with
the next:
Python While Loops
The else Statement
With the else statement we can run a block of code once when the condition no
longer is true:
Python While Loops
The else Statement
With the else statement we can run a block of code once when the condition no
longer is true:
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Python For Loops
The break Statement
With the break statement we can stop the loop before it has looped through
all the items:
Python For Loops
The break Statement
With the break statement we can stop the loop before it has looped through
all the items:
Python For Loops
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue
with the next:
Python For Loops
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue
with the next:
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Note that range(7) is not the values
of 0 to 7, but the values 0 to 6.
The range() Function
The range() Function
Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one
time for each iteration of the "outer loop":
Nested Loops
Nested Loops
Nested Loops