Introduction to Python Programming
Introduction to Python Programming
• Example
• if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
• Five is greater than two!
Five is greater than two!
Python Indentation
⚫ You have to use the same number of spaces in the same block of
code, otherwise Python will give you an error.
⚫ if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
⚫ Syntax Error
Python Variables
In Python, variables are created when you
assign a value to it.
x= 5
y = "Hello, Python!“
#This is a comment.
print("Hello, World!")
Exercise
⚫ Insert the missing part of the code below to output "Hello
World".
⚫ if 5 > 2:
if 5 > 2:
print("Five is greater than two!")
This is a comment
written in more that
just one line
Output:
<class 'int'>
<class 'str'>
Case-Sensitive
Variable names are case-sensitive.
a=4
A= “Abdi“
NOTE:Awill not overwrite a.
Output:
4
Abdi
Python - Variable Names
⚫ Avariable can have ashort name (like x and y) or amore
descriptive name (age, carname, total_volume).
Rules for Python variables:
1. Avariable name must start with a letter or the underscore
character.
2. Avariable name cannot start with a number.
3. Avariable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ ).
4. Variable names are case-sensitive (age, Age and AGEare three
different variables).
Multi Words Variable Names
⚫ Variable names with more than one word can be difficult to read.
⚫ There are several techniques you can use to make them more
readable:
Camel Case:
⚫ Each word, except the first, starts with a capital.e.g.:
myVariableName = “Abdi" letter
Pascal Case:
⚫ Each word starts with a capital letter.
⚫ E.g.: MyVariableName = “Abdi“
Snake Case:
⚫ Each word is separated by an underscore character: e.g.:
my_variable_name = “Abdi"
Python Variables - Assign Multiple Values
Python allows you to assign values to multiple
variables in one line.
x, y, z = "Orange", "Banana", "Cherry“
print(x)
print(y)
print(z)
Output:
Orange
Banana
Cherry
One Value to Multiple Variables
you can assign the samevalue to multiple
variables in one line.
x = y = z = "Orange«
print(x)
print(y)
print(z)
Unpack a Collection
If you have a collection of values in a list. Python
allows you extract the values into
variables. This is called unpacking.
Output:
Apple
Banana
cherry
Python - Output Variables
⚫ The Python ’print’statement is often used to output
variables.
⚫ To combine both text and a variable, Python uses
the + character.
⚫ x = "easy"
print("Python is " + x)
⚫ Output:
⚫ Python is easy
•
Python - Output Variables
Youcan also use the + character to add a variable to another variable.
• x = "Python is "
y = “easy"
z= x+ y
print(z)
• Output:
• Python is easy
Output:
TypeError: unsupported operand type(s) for + :
'int' and 'str'
PYTHON DATATYPES
Built-in DataTypes
⚫ In programming, data type is an important concept.
⚫ Variables can store data of different types, and different types can
do different things.
⚫ Python has the following data types built-in by default, in these
categories.
⚫ TextType:str
⚫ NumericTypes:int, float, complex
⚫ SequenceTypes:list, tuple, range
⚫ MappingType: dictionary
⚫ SetTypes:set
⚫ BooleanType:bool
Setting the Data Type
In Python, the data type is set when you assign
a value to a variable.
Example DataType
x = "HelloWorld" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = {"name" : “Abdi", "age" : 36} Dict
x = {"apple", "banana", "cherry"} Set
x =True bool
Setting the Specific Data Type
If you want to specify the data type, you can
use the following constructor functions.
x = str("HelloWorld") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = dict(name="Abdi", age=36) dict
x = set(("apple", "banana", "cherry")) set
Python Numbers
There are three numeric types in Python:
⚫ int
⚫ float
⚫ complex
Variables of numeric types are created when you assign
a value to them.
import random
print([Link](1, 10))
Python-Strings
⚫ Strings in python are surrounded by either single quotation
marks, or double quotation marks.
⚫ 'hello' is the same as "hello".
⚫ a = "Hello,World!"
print(a[1])
⚫ Output:
⚫e
String Length
⚫ To get the length of a string, use the len() function.
⚫ The len() function returns the length of a string.
⚫ a = "Hello,World!"
print(len(a))
⚫ Output:
⚫ 13
Python - Slicing Strings
⚫ You can return a range of characters by using the slice syntax.
⚫ Specify the start index and the end index, separated by a colon, to
return a part of the string.
⚫ Output:
⚫ llo
Slice From the Start
Get the characters from the start to position 5 (not
included).
b = "Hello, World!"
print(b[:5])
Output: Hello
+ Addition x+y 8
- Subtraction x-y 2
* Multiply x*y 15
/ Divide x/y 1.67
% Modulus x%y 2
** Exponential X**y 125
// Floor division x//y 1
Python Assignment Operators
Consider X=5
Reverse the result, returns not(x < 5 and x < 10) False
not
False if the result is true
PYTHON-CONDITIONAL STATEMENTS
If Condition: Python supports the usual logical conditions.
⚫ 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
These conditions can be used in several ways, most commonly
in "if statements" and loops.
An"if statement" is written byusing the if keyword.
Example:
a= 3
b = 20
if b > a:
print("b is greater than a")
Example
⚫If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:print("b is greater than a") # you will get an error
Elif:
The elif keyword says "if the previous conditions were not true,
then try this condition“
Example:
a= 3
b= 3
if b > a:
print("b is greater than a")
elif a = = b:
print("a and b are equal")
Else: The else keyword catches anything which isn't caught by
the preceding conditions.
Example:
a = 40
b = 33
if b > a:
print("b is greater than a")
elif a = = b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
⚫ You can also have an else without the elif.
Example:
a = 40
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
List Length:
⚫ To determine how many items a list has, use the len() function.
list = ["apple", "banana", "cherry"]
print(len(list))
List Items - Data Types
⚫ List items can be of any data type.
Example: String, int and boolean data types
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• Alist can contain different data types.
Example: Alist with strings, integers and boolean values.
list1 = ["abc", 34,True, 40, "male"]
Python Collections (Arrays)
⚫ There are four collection data types in the Python
programming language:
⚫ List is acollection which is ordered and changeable. Allows
duplicate members.
⚫ Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
⚫ Set is a collection which is unordered and unindexed. No
duplicate members.
⚫ Dictionary is acollection which is unordered and
changeable. No duplicate members.
Python - Access List Items
⚫ List items are indexed and you can access them by referring
to the index number.
Example: Print the second item of the list:
list = ["apple", "banana", "cherry"]
print(list[1])
❑ Negative Indexing
❑ Range of Indexes
Check if Item Exists: To determine if a specified item is
present in a list use the in keyword.
Example: Check if "apple" is present in the list:
list = ["apple", "banana", "cherry"]
if "apple" in list:
print("Yes, 'apple' is in the list")
Python - Change List Items
⚫ To change the value of a specific item, refer to the index
number.
Example: Change the second item:
list = ["apple", "banana", "cherry"]
list[1] = "blackcurrant“
print(list)
Change a Range of Item Values
⚫ Tochange the value of items within aspecific range, define a
list with the new values, and refer to the range of index
numbers where you want to insert the new values:
Example: Change the values "banana" and "cherry" with
the values "blackcurrant" and "watermelon":
list =
["apple", "banana", "cherry", "orange", "kiwi", "mango"]
list[1:3] = ["blackcurrant", "watermelon"]
print(list)
Output:
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
⚫ If you insert moreitems than you replace, the new items will
be inserted where you specified, and the remaining items
will move accordingly:
Example: Change the second value by replacing it
with twonew values:
list = ["apple", "banana", "cherry"]
list[1:2] = ["blackcurrant", "watermelon"]
print(list)
Output:
['apple', 'blackcurrant', 'watermelon', 'cherry']
⚫ If you insert less items than you replace, the new items will
be inserted where you specified, and the remaining items
will move accordingly:
Example: Change the second and third value by replacing
it with onevalue:
list = ["apple", "banana", "cherry"]
list[1:3] = ["watermelon"]
print(list)
Output:
['apple', 'watermelon']
Insert Items
⚫ To insert a new list item, without replacing any of the
existing values, we can use the insert() method.
⚫ The insert() method inserts an item at the specified index:
Example: Insert "watermelon" as the third item:
list = ["apple", "banana", "cherry"]
[Link](2, "watermelon")
print(list)
OutPut:
['apple', 'banana', 'watermelon', 'cherry']
Append Items
⚫ To add an item to the end of the list, use
the append() method:
Example: Using the append() method to append an item:
list = ["apple", "banana", "cherry"]
[Link]("orange")
print(list)
OutPut: ['apple', 'banana', 'cherry', 'orange']
Extend List
⚫ To append elements from another list to the current list, use
the extend() method.
Example: Add the elements of tropical to thislist:
list1 = ["apple", "banana", "cherry"]
list2 = ["mango", "pineapple", "papaya"]
[Link](list2)
print(list1)
Output:
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
Add Any Iterable
⚫ The extend() method does not haveto append lists, you can
add any iterable object (tuples, sets, dictionaries etc.).
Example: Add elements of a tuple to a list:
list = ["apple", "banana", "cherry"]
tuple = ("kiwi", "orange")
[Link](tuple)
print(list)
OutPut:
['apple', 'banana', 'cherry', 'kiwi', 'orange']
Python - Remove List Items
Remove Specified Item
⚫The remove() method removes the specified item.
Example: Remove "banana":
list = ["apple", "banana", "cherry"]
[Link]("banana")
print(list)
Output: ['apple', 'cherry']
Remove Specified Index
The pop() method removes the specified index.
Example: Remove the second item:
list = ["apple", "banana", "cherry"]
[Link](1)
print(list)
Output: ["apple", "cherry"]
⚫ If you do not specify the index, the pop() method removes
the last item.
Example: Remove the last item:
list = ["apple", "banana", "cherry"]
[Link]()
print(list)
Output: ["apple", "banana""]
⚫The del keyword also removes the specified index:
Example: Remove the first item:
list = ["apple", "banana", "cherry"]
del list[0]
print(list)
Output: ["banana", "cherry"]
⚫ The del keyword can also delete the list completely.
Example: Delete the entire list:
list = ["apple", "banana", "cherry"]
del list
Output: NameError: name 'list' is not defined.
Clear the List
⚫ The clear() method empties the list.
⚫ The list still remains, but it has no content.
Example: Clear the list content:
list = ["apple", "banana", "cherry"]
[Link]()
print(list)
Output: []
Loop Through a List
⚫Youcan loop through the list items by using a for loop:
Example: Print all items in the list, one by one:
list = ["apple", "banana", "cherry"]
for x in list:
print(x)
Output:
Apple
Banana
Cherry
Loop Through the Index Numbers
⚫ Youcan also loop through the list items by referring to their
index number.
⚫ Use the range() and len() functions to create a suitable
iterable.
Example
⚫ Print all items by referring to their index number:
list = ["apple", "banana", "cherry"]
for i in range(len(list)):
print(list[i]
Using a While Loop
⚫ You can loop through the list items by using a while loop.
⚫ Use the len() function to determine the length of the list,
then start at 0 and loop your way through the list items by
refering to their indexes.
⚫ Remember to increase the index by 1 after each iteration.
Example: Print all items, using a while loop to go through all
the index numbers
list = ["apple", "banana", "cherry"]
i= 0
while i < len(list):
print(list[i])
i= i+ 1
List Comprehension
⚫ List comprehension offers a shorter syntax when you want to
create a new list based on the values of an existing list.
Example: Based on alist of fruits, you want anew list,
containing only the fruits with the letter "a" in the name.
Example:
⚫ fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
[Link](x)
print(newlist)
Output: ['apple', 'banana', 'mango']
⚫ With list comprehension you can do all that with only one
line of code:
Example:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output: ['apple', 'banana', 'mango']
Example: Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
[Link](list1)
print(list2)
List Methods
⚫ Python has a set of built-in methods that you can use on lists.
Method Description
Tuple Items
⚫ Tuple items are ordered, unchangeable, and allow duplicate
values.
⚫ Tuple items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered
⚫ When we say that tuples are ordered, it means that the items
have a defined order, and that order will not change.
Unchangeable
⚫ Tuples are unchangeable, meaning that we cannot change,
add or remove items after the tuple has been created.
Allow Duplicates
⚫ Since tuple are indexed, tuples can haveitems with the same
value.
Tuple Length
⚫ To determine how many items a tuple has, use
the len() function
CreateTupleWith One Item
⚫ Tocreate a tuple with only one item, you have to add a
comma after the item, otherwise Python will not recognize it
as a tuple.
Example: One item tuple, remember the commma:
⚫ tuple = ("apple",)
print(type(tuple))
#NOT a tuple
tuple = ("apple")
print(type(stuple))
Output:
<class 'tuple'>
<class 'str'>
Tuple Items - Data Types
⚫ Tuple items can be of any data type.
Example: String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
⚫ Atuple can contain different data types:
Example
⚫ Atuple with strings, integers and boolean values:
tuple1 = ("abc", 34,True, 40, "male")
AccessTuple Items
⚫ Youcan access tuple items by referring to the index number,
inside square brackets.
Example: Print the second item in the tuple:
tuple = ("apple", "banana", "cherry")
print(tuple[1])
Negative Indexing
⚫ Negative indexing means start from the end.
⚫ -1 refers to the last item, -2 refers to the second last item
etc.
Example: Print the last item of the tuple:
⚫ tuple = ("apple", "banana", "cherry")
print(tuple[-1])
Output: cherry
Range of Indexes
⚫ Youcan 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
tuple with the specified items.
Example: Return the third, fourth, and fifth item:
tuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(tuple[2:5])
Output: ("cherry", "orange", "kiwi")
Example: This example returns the items from the beginning.
tuple = ("apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango")
print(tuple[:4])
Output: ("apple", "banana", "cherry", "orange“)
Range of Negative Indexes
⚫ Specify negative indexes if you want to start the search from the
end of the tuple
Example: This example returns the items from index -4 (included)
to index -1 (excluded)
tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(tuple[-4:-1])
Output: ("orange", "kiwi", "melon“)
Check if Item Exists
⚫ To determine if a specified item is present in a tuple use
the in keyword:
Example: Check if "apple" is present in the tuple:
tuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
ChangeTupleValues
⚫ Once atuple is created, you cannot change its [Link]
are unchangeable, or immutable.
⚫ But you can convert the tuple into alist, change the list, and
convert the list back into a tuple.
Example: Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi“
x = tuple(y)
print(x)
Output: ("apple", "kiwi", "cherry")
Add Items
⚫ Once a tuple is created, you cannot add items to it.
Example: Youcannot add items to a tuple:
tuple = ("apple", "banana", "cherry")
[Link]("orange") # This will raise an error
print(tuple)
But you can convert the tuple into a list, add "orange", and
convert it back into a tuple.
Example:
tuple = ("apple", "banana", "cherry")
y = list(tuple)
[Link]("orange")
tuple = tuple(y)
Output: ('apple', 'banana', 'cherry', 'orange')
Unpacking aTuple
⚫ When we create a tuple, we normally assign values to [Link] is
called "packing" a tuple
Packing a tuple:
⚫ fruits = ("apple", "banana", "cherry")
⚫ But, in Python, we are also allowed to extract the values back into
variables. This is called "unpacking“.
Example: Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(a,b,c) = fruits
print(a)
print(b)
print(c)
Output:
apple
banana
cherry
Example: Assign the rest of the values as a list called "red“.
⚫fruits = ("apple", "banana", "cherry", "strawberry",
"raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Output:
apple
banana
['cherry', 'strawberry', 'raspberry']
If the * is added to another variable name than the last, Python
will assign values to the variable until the number of values left
matches the number of variables left.
LoopThrough aTuple:
Looping can be done same as list. Byfor/range/while loop.
⚫ Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times aspecified value
occurs in a tuple
index() Searches the tuple for a specified value and
returns the position of where it was
found