SlideShare a Scribd company logo
Prof Dr. Iqbal Ahmed
Dept. of Computer Science and Engineering
Python: If Statement
a = 33
b = 200
if b > a:
print("b is greater than
a")
If statement, without indentation (will raise an error)
Python: elif Statement
a = 33
b = 33
if b > a:
print("b is greater than
a")
elif a == b:
print("a and b are equal")
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
a = 200
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")
If you have only one statement to execute,
you can put it on the same line as the if
statement: Short Hand of If
if a > b: print("a is greater than
b")
a = 2
b = 330
print("A") if a >
Python: if Statement
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are
True")
AND operation
OR operation
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the
conditions is True")
NOT operation
a = 33
b = 200
if not a > b:
print("a is NOT greater than
b")
Python: Nested If Statement
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above
20!")
else:
print("but not above
20.")
if statements cannot be empty, but if you for
some reason have an if statement with no
content, put in the pass statement to avoid
getting an error
a = 33
b = 200
if b > a:
pass
You can have if statements inside if statements,
this is called nested if statements.
Python: Match Statement
day = 4
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
This is how it works:
•The match expression is evaluated once.
•The value of the expression is compared with
the values of each case.
•If there is a match, the associated block of code
is executed.
Instead of writing many if..else statements, you
can use the match statement.
The match statement selects one of many code
blocks to be executed.
match expression:
case x:
code block
case y:
code block
case z:
code block
Python: Match Statement
day = 4
match day:
case 6:
print("Today is
Saturday")
case 7:
print("Today is Sunday")
case _:
print("Looking forward to
the Weekend")
Use the pipe character | as an or operator in
the case evaluation to check for more than one
value match in one case
Use the underscore character _ as the last case
value if you want a code block to execute when
there are not other matches
day = 4
match day:
case 1 | 2 | 3 | 4 | 5:
print("Today is a
weekday")
case 6 | 7:
print("I love weekends!")
Python: Match Statement
month = 5
day = 4
match day:
case 1 | 2 | 3 | 4 | 5 if month == 4:
print("A weekday in April")
case 1 | 2 | 3 | 4 | 5 if month == 5:
print("A weekday in May")
case _:
print("No match")
You can add if statements in the case evaluation
as an extra condition-check:
The value _ will always match, so it is important to place it as the last case to make
it behave as a default case.
Python Loops
i = 1
while i < 6:
print(i)
i += 1
With the while loop we can execute a
set of statements as long as a condition
is true.
Python has two primitive loop
commands:
•while loops
•for loops
Note: remember to increment i, or else the loop will continue forever.
Break Statement
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the continue statement we can
stop the current iteration, and
continue with the next:
With the break statement we can
stop the loop even if the while
condition is true:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the else statement we can run
a block of code once when the
condition no longer is true:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than
Python For loops
fruits =
["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
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
fruits =
["apple", "banana", "cherry"]
for x in fruits:
print(x)
With the break statement we can stop
the loop before it has looped through
all the items:
fruits =
["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
Python For loops
for x in range(6):
print(x)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3):
print(x)
With the continue statement we can
stop the current iteration of the loop,
and continue with the next:
fruits =
["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
To loop through a set of code a specified
number of times, we can use
the range() function.
Note that range(6) is not the values of 0
to 6, but the values 0 to 5.
it is possible to specify the starting value
by adding a parameter: range(2, 6),
which means values from 2 to 6 (but not
including 6):
it is possible to specify the increment value by
adding a third parameter: range(2, 30, 3)
Python For loops
The else keyword in a for loop specifies
a block of code to be executed when
the loop is finished.
for x in range(6):
print(x)
else:
print("Finally finished!")
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
A nested loop is a loop inside a loop.
The "inner loop" will be executed one
time for each iteration of the "outer
loop”.
adj = ["red", "big", "tasty"]
fruits =
["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Python For loops
for loops cannot be empty, but if you
for some reason have a for loop with
no content, put in the pass statement
to avoid getting an error.
for x in [0, 1, 2]:
pass
1. Grading System (if, elif, nested if)
Write a program that:
•Asks the user for a marks input (0 to 100).
•Based on the marks, print the grade:
• 90-100 → A+
• 80-89 → A
• 70-79 → B
• 60-69 → C
• 50-59 → D
• Below 50 → Fail
•Tricky part: If marks are exactly 100, print "Perfect Score!" in addition to
grade.
Solve some real problem!
2. Food Menu Selection (match)
Write a program that:
•Displays a menu:
1. Pizza
2. Burger
3. Pasta
4. Salad
•Takes user's choice (1-4).
•Use a match-case to print a different message for each food item.
•Tricky part: If they input something else, print "Invalid choice. Try again!"
Solve some real problem!
3. Guess the Secret Number (while loop with break/continue)
Write a program that:
•A secret number (say 7) is fixed.
•The user is asked to guess the number.
•If guess is correct, print "Congratulations!" and break the loop.
•If guess is wrong:
• If the guess is negative, continue without any message.
• Else print "Wrong! Try again."
Solve some real problem!
4. Multiplication Table (for loop)
Write a program that:
•Asks the user for a number.
•Print its multiplication table from 1 to 10 using a for loop.
•Tricky part: If the number is negative, print "Tables not available for negative
numbers." and stop.
5. Number Triangle (nested for loop)
Write a program that:
•Asks the user for a number (e.g., 5).
•Print a number triangle like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Use nested for loops: Outer loop for rows, inner loop for numbers in
the row.
Solve some real problem!
6. Odd or Even Game (nested if with while loop)
Write a program that:
•Keeps asking the user for a number until they enter 0.
•For each number:
• Check if it is even or odd.
• Then check:
• If even and greater than 50, print "Big even number!"
• If odd and less than 10, print "Tiny odd number!"
• Otherwise, just print "Even" or "Odd" normally.
Solve some real problem!
7. Match a Month (match-case + nested if)
Write a program that:
•Asks the user for a month number (1-12).
•Use a match-case to:
• Print the month's name (e.g., 1 → January).
•Then inside the matched case, using nested if, check:
• If the month is January, print "Happy New Year!"
• If the month is December, print "Merry Christmas!"
Solve some real problem!
marks = int(input("Enter your marks (0-100): "))
if marks < 0 or marks > 100:
print("Invalid marks entered.")
else:
if marks == 100:
print("Perfect Score!")
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: Fail")
1. Solutions!!
choice = int(input("Choose an item (1-4):n1. Pizzan2. Burgern3. Pastan4. Saladn"))
match choice:
case 1:
print("You selected Pizza! Yummy!")
case 2:
print("Burger selected. Enjoy your meal!")
case 3:
print("Pasta it is! Bon appétit!")
case 4:
print("Healthy choice! Salad selected.")
case _:
print("Invalid choice. Try again!")
2. Solutions!!
secret_number = 7
while True:
guess = int(input("Guess the secret number: "))
if guess < 0:
continue # Skip negative guesses silently
if guess == secret_number:
print("Congratulations! You guessed it right!")
break
else:
print("Wrong! Try again.")
3 & 4. Solutions!!
num = int(input("Enter a number for multiplication table: "))
if num < 0:
print("Tables not available for negative numbers.")
else:
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
rows = int(input("Enter number of rows for the
triangle: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=" ")
print() # Newline after each row
while True:
number = int(input("Enter a number (0 to quit): "))
if number == 0:
print("Goodbye!")
break
if number % 2 == 0:
if number > 50:
print("Big even number!")
else:
print("Even")
else:
if number < 10:
print("Tiny odd number!")
else:
print("Odd")
5 & 6.
Solutions!!
month = int(input("Enter month number (1-12): "))
match month:
case 1:
print("January")
if month == 1:
print("Happy New Year!")
case 2:
print("February")
case 3:
print("March")
case 4:
print("April")
case 5:
print("May")
case 6:
print("June")
7. Solutions
case 7:
print("July")
case 8:
print("August")
case 9:
print("September")
case 10:
print("October")
case 11:
print("November")
case 12:
print("December")
if month == 12:
print("Merry Christmas!")
case _:
print("Invalid month number.")

More Related Content

PDF
Pythonintro
PPTX
Python Flow Control & use of functions.pptx
PPTX
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
PDF
Python unit 2 M.sc cs
PDF
2 Python Basics II meeting 2 tunghai university pdf
PPTX
Python_Loops.pptxpython loopspython loopspython loopspython loopspython loops...
PDF
Control of flow of the phyton programming
PPTX
industry coding practice unit-2 ppt.pptx
Pythonintro
Python Flow Control & use of functions.pptx
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
Python unit 2 M.sc cs
2 Python Basics II meeting 2 tunghai university pdf
Python_Loops.pptxpython loopspython loopspython loopspython loopspython loops...
Control of flow of the phyton programming
industry coding practice unit-2 ppt.pptx

Similar to Lecture on Fundamentals of Python Programming-2 (20)

PPTX
Conditional Statements.pptx
PPTX
Looping statement in python
PPTX
1. control structures in the python.pptx
PDF
Class 3: if/else
PDF
Class 4: For and while
PPTX
week2.pptx program program program problems
PPTX
module 2.pptx
PPTX
Python introduction
PDF
Recitation2IntroductionToPython.pptx.pdf
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
PPTX
Pythonlearn-03-Conditional.pptx
PDF
basic of desicion control statement in python
PPTX
Python
PPT
Control structures pyhton
PPTX
TN 12 computer Science - ppt CHAPTER-6.pptx
PPTX
Python notes for students to learn and develop
PPTX
Python for Beginners(v2)
DOCX
Python Math Concepts Book
PPTX
PPTX
Decision control units by Python.pptx includes loop, If else, list, tuple and...
Conditional Statements.pptx
Looping statement in python
1. control structures in the python.pptx
Class 3: if/else
Class 4: For and while
week2.pptx program program program problems
module 2.pptx
Python introduction
Recitation2IntroductionToPython.pptx.pdf
Python 101: Python for Absolute Beginners (PyTexas 2014)
Pythonlearn-03-Conditional.pptx
basic of desicion control statement in python
Python
Control structures pyhton
TN 12 computer Science - ppt CHAPTER-6.pptx
Python notes for students to learn and develop
Python for Beginners(v2)
Python Math Concepts Book
Decision control units by Python.pptx includes loop, If else, list, tuple and...
Ad

Recently uploaded (20)

PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
Sunset Boulevard Student Revision Booklet
PDF
High Ground Student Revision Booklet Preview
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
Landforms and landscapes data surprise preview
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Software Engineering BSC DS UNIT 1 .pptx
PDF
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
Open Quiz Monsoon Mind Game Prelims.pptx
Module 3: Health Systems Tutorial Slides S2 2025
human mycosis Human fungal infections are called human mycosis..pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
Sunset Boulevard Student Revision Booklet
High Ground Student Revision Booklet Preview
Open Quiz Monsoon Mind Game Final Set.pptx
UPPER GASTRO INTESTINAL DISORDER.docx
Cardiovascular Pharmacology for pharmacy students.pptx
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Abdominal Access Techniques with Prof. Dr. R K Mishra
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Landforms and landscapes data surprise preview
Week 4 Term 3 Study Techniques revisited.pptx
Software Engineering BSC DS UNIT 1 .pptx
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
Ad

Lecture on Fundamentals of Python Programming-2

  • 1. Prof Dr. Iqbal Ahmed Dept. of Computer Science and Engineering
  • 2. Python: If Statement a = 33 b = 200 if b > a: print("b is greater than a") If statement, without indentation (will raise an error)
  • 3. Python: elif Statement a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") 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 a = 200 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") If you have only one statement to execute, you can put it on the same line as the if statement: Short Hand of If if a > b: print("a is greater than b") a = 2 b = 330 print("A") if a >
  • 4. Python: if Statement a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") AND operation OR operation a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") NOT operation a = 33 b = 200 if not a > b: print("a is NOT greater than b")
  • 5. Python: Nested If Statement x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error a = 33 b = 200 if b > a: pass You can have if statements inside if statements, this is called nested if statements.
  • 6. Python: Match Statement day = 4 match day: case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") case 4: print("Thursday") case 5: print("Friday") case 6: print("Saturday") case 7: print("Sunday") This is how it works: •The match expression is evaluated once. •The value of the expression is compared with the values of each case. •If there is a match, the associated block of code is executed. Instead of writing many if..else statements, you can use the match statement. The match statement selects one of many code blocks to be executed. match expression: case x: code block case y: code block case z: code block
  • 7. Python: Match Statement day = 4 match day: case 6: print("Today is Saturday") case 7: print("Today is Sunday") case _: print("Looking forward to the Weekend") Use the pipe character | as an or operator in the case evaluation to check for more than one value match in one case Use the underscore character _ as the last case value if you want a code block to execute when there are not other matches day = 4 match day: case 1 | 2 | 3 | 4 | 5: print("Today is a weekday") case 6 | 7: print("I love weekends!")
  • 8. Python: Match Statement month = 5 day = 4 match day: case 1 | 2 | 3 | 4 | 5 if month == 4: print("A weekday in April") case 1 | 2 | 3 | 4 | 5 if month == 5: print("A weekday in May") case _: print("No match") You can add if statements in the case evaluation as an extra condition-check: The value _ will always match, so it is important to place it as the last case to make it behave as a default case.
  • 9. Python Loops i = 1 while i < 6: print(i) i += 1 With the while loop we can execute a set of statements as long as a condition is true. Python has two primitive loop commands: •while loops •for loops Note: remember to increment i, or else the loop will continue forever.
  • 10. Break Statement i = 0 while i < 6: i += 1 if i == 3: continue print(i) With the continue statement we can stop the current iteration, and continue with the next: With the break statement we can stop the loop even if the while condition is true: i = 1 while i < 6: print(i) if i == 3: break i += 1 With the else statement we can run a block of code once when the condition no longer is true: i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than
  • 11. Python For loops fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break 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 fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) With the break statement we can stop the loop before it has looped through all the items: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break
  • 12. Python For loops for x in range(6): print(x) for x in range(2, 6): print(x) for x in range(2, 30, 3): print(x) With the continue statement we can stop the current iteration of the loop, and continue with the next: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) To loop through a set of code a specified number of times, we can use the range() function. Note that range(6) is not the values of 0 to 6, but the values 0 to 5. it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6): it is possible to specify the increment value by adding a third parameter: range(2, 30, 3)
  • 13. Python For loops The else keyword in a for loop specifies a block of code to be executed when the loop is finished. for x in range(6): print(x) else: print("Finally finished!") for x in range(6): if x == 3: break print(x) else: print("Finally finished!") A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop”. adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)
  • 14. Python For loops for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. for x in [0, 1, 2]: pass
  • 15. 1. Grading System (if, elif, nested if) Write a program that: •Asks the user for a marks input (0 to 100). •Based on the marks, print the grade: • 90-100 → A+ • 80-89 → A • 70-79 → B • 60-69 → C • 50-59 → D • Below 50 → Fail •Tricky part: If marks are exactly 100, print "Perfect Score!" in addition to grade. Solve some real problem!
  • 16. 2. Food Menu Selection (match) Write a program that: •Displays a menu: 1. Pizza 2. Burger 3. Pasta 4. Salad •Takes user's choice (1-4). •Use a match-case to print a different message for each food item. •Tricky part: If they input something else, print "Invalid choice. Try again!" Solve some real problem!
  • 17. 3. Guess the Secret Number (while loop with break/continue) Write a program that: •A secret number (say 7) is fixed. •The user is asked to guess the number. •If guess is correct, print "Congratulations!" and break the loop. •If guess is wrong: • If the guess is negative, continue without any message. • Else print "Wrong! Try again." Solve some real problem! 4. Multiplication Table (for loop) Write a program that: •Asks the user for a number. •Print its multiplication table from 1 to 10 using a for loop. •Tricky part: If the number is negative, print "Tables not available for negative numbers." and stop.
  • 18. 5. Number Triangle (nested for loop) Write a program that: •Asks the user for a number (e.g., 5). •Print a number triangle like this: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Use nested for loops: Outer loop for rows, inner loop for numbers in the row. Solve some real problem!
  • 19. 6. Odd or Even Game (nested if with while loop) Write a program that: •Keeps asking the user for a number until they enter 0. •For each number: • Check if it is even or odd. • Then check: • If even and greater than 50, print "Big even number!" • If odd and less than 10, print "Tiny odd number!" • Otherwise, just print "Even" or "Odd" normally. Solve some real problem!
  • 20. 7. Match a Month (match-case + nested if) Write a program that: •Asks the user for a month number (1-12). •Use a match-case to: • Print the month's name (e.g., 1 → January). •Then inside the matched case, using nested if, check: • If the month is January, print "Happy New Year!" • If the month is December, print "Merry Christmas!" Solve some real problem!
  • 21. marks = int(input("Enter your marks (0-100): ")) if marks < 0 or marks > 100: print("Invalid marks entered.") else: if marks == 100: print("Perfect Score!") if marks >= 90: print("Grade: A+") elif marks >= 80: print("Grade: A") elif marks >= 70: print("Grade: B") elif marks >= 60: print("Grade: C") elif marks >= 50: print("Grade: D") else: print("Grade: Fail") 1. Solutions!!
  • 22. choice = int(input("Choose an item (1-4):n1. Pizzan2. Burgern3. Pastan4. Saladn")) match choice: case 1: print("You selected Pizza! Yummy!") case 2: print("Burger selected. Enjoy your meal!") case 3: print("Pasta it is! Bon appétit!") case 4: print("Healthy choice! Salad selected.") case _: print("Invalid choice. Try again!") 2. Solutions!!
  • 23. secret_number = 7 while True: guess = int(input("Guess the secret number: ")) if guess < 0: continue # Skip negative guesses silently if guess == secret_number: print("Congratulations! You guessed it right!") break else: print("Wrong! Try again.") 3 & 4. Solutions!! num = int(input("Enter a number for multiplication table: ")) if num < 0: print("Tables not available for negative numbers.") else: for i in range(1, 11): print(f"{num} x {i} = {num * i}")
  • 24. rows = int(input("Enter number of rows for the triangle: ")) for i in range(1, rows + 1): for j in range(1, i + 1): print(j, end=" ") print() # Newline after each row while True: number = int(input("Enter a number (0 to quit): ")) if number == 0: print("Goodbye!") break if number % 2 == 0: if number > 50: print("Big even number!") else: print("Even") else: if number < 10: print("Tiny odd number!") else: print("Odd") 5 & 6. Solutions!!
  • 25. month = int(input("Enter month number (1-12): ")) match month: case 1: print("January") if month == 1: print("Happy New Year!") case 2: print("February") case 3: print("March") case 4: print("April") case 5: print("May") case 6: print("June") 7. Solutions case 7: print("July") case 8: print("August") case 9: print("September") case 10: print("October") case 11: print("November") case 12: print("December") if month == 12: print("Merry Christmas!") case _: print("Invalid month number.")