Introduction to Python
LECTURE 3
Outlines
➢Sequences
➢Selection statements
➢Loop statements
➢List operations :
Multiplication
Accessing (indexing – slicing)
Update
Append and extend
Remove
Pop
Clear
Copy
Index
Count
Sort
reverse
Python literals (sequences) (Collections)
#string literal
fruit = “apple” # dictionary literal
print(fruit) alphabets = {'a':'apple', 'b':'ball', 'c':'cat'}
print(alphabets)
# list literal
fruits = ["apple", "mango", "orange"]
# set literal
print(fruits)
vowels = {'a', 'e', 'i' , 'o', 'u'}
print(vowels)
# tuple literal
numbers = (1, 2, 3)
print(numbers)
Python literals (sequences) (Collections)
Python if Statement
Here, condition is a boolean expression, such as number > 5, that evaluates to either True or False.
If condition evaluates to True, the body of the if statement is executed.
If condition evaluates to False, the body of the if statement will be skipped from execution.
If else
Here, if the condition inside the if statement evaluates to
True - the body of if executes, and the body of else is skipped.
False - the body of else executes, and the body of if is skipped
If elif else
The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, we use the
if...elif...else statement.
Python Nested if Statements
example
example
Program to test If a number even or odd
Match-Case (Python 3.10+)
Logical operators
for Loop with Python range()
In Python, the range() function returns a sequence of numbers. For example,
Here, range(4) returns a sequence of 0, 1, 2 ,and 3.
For loop
Range function
Python for Loop
In Python, we use a for loop to iterate over sequences such as lists, strings, dictionaries, etc.
for loop Syntax
Indentation in Loop
Example: Loop Through a String
Nested loop
Names = [“Eman”, “Ahmed” , “Mohamed” , “Momen” , “Eslam” , “Youmna”]
For name in Names:
◦ Print(name)
What if we want to print all characters ?
while Loop Syntax
Example: Python while Loop
Python while Loop
Write a python program to sum all the
prices in a price list
Printing Multiplication Table
While loop
How can we write it with for loop?
Loop on strings (for loop)
Loop on strings (while loop)
Iterating Over a List
Iterating Over a String
Iterating Over a Set
Iterating Over a Tuple
Iterating Over a Dictionary
Using enumerate() with Any Sequence
list
multiplication
Access List Items (indexing )
Access List Items (indexing )
Access List Items (slicing)
Access List Items (slicing)
String Slicing
Update - Change List Items
Python - Add List Items (append , extend)
insert
Remove
Remove the first 5 only
Clear()
Pop()
Index
The first occurrence of 5, so it will return 0
In operator
count
2
Sort
Reverse
copy
assignment