Conditionals and Loops¶
if, elif and else and Indentation¶
# 1. if, elif, else and Indentation
x = 15
if x < 10:
print("Less than 10")
elif x == 10:
print("Equal to 10")
else:
print("Greater than 10")
Greater than 10
if x < 10:
print('x less than 10')
print('x less than 10')
x less than 10
Conditional statement using logical operator (and, or, not)¶
# 2. Logical Operators: and, or, not
a = 5
b = 10
if a < 10 and b > 5:
print("Both conditions are True")
if a > 10 or b > 5:
print("At least one condition is True")
if not a > 10:
print("a is not greater than 10")
Both conditions are True At least one condition is True a is not greater than 10
Identity(is) vs Equality(==)¶
# 3. is vs. == (Identity vs. Equality)
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x == y) # True: Same content
print(x is y) # False: Different objects
print(x is z) # True: Same object
True False True
id(x), id(y), id(z)
(136234817650112, 136234817650496, 136234817650112)
Ternary Operator¶
- The ternary operator in Python allows us to perform conditional checks and assign values or perform operations on a single line.
x = a if condition else b
n = 5
res = "Even" if n % 2 == 0 else "Odd"
print(res)
Odd
1. Check Even or Odd¶
Write a program that takes an integer input from the user and checks if it is even or odd.
2. Check Age Category¶
Write a program that asks for a person's age and prints:
- "Child" if age < 13
- "Teenager" if 13 <= age < 20
- "Adult" if age >= 20
3. Write a one-liner using a ternary operator to assign a grade based on a student's score.¶
Given a variable score (an integer from 0 to 100), write a one-liner to assign:
"Pass" if the score is 40 or above
"Fail" if the score is below 40
Loops¶
cities_list = ('Kathmandu', 'Lalitpur', 'Bhaktapur', 'asdf')
for city in cities_list:
print(city.lower())
print(city.upper())
kathmandu KATHMANDU lalitpur LALITPUR bhaktapur BHAKTAPUR asdf ASDF
word = 'Kathmandu'
for char in word:
print(char)
K a t h m a n d u
# 4. Introduction to Loops: for and while
# for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple banana cherry
# while loop
count = 0
while count < 3:
print("Count:", count)
count += 1
Count: 0 Count: 1 Count: 2
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
for i in range(2, 10):
print(i)
2 3 4 5 6 7 8 9
for i in range(2, 10, 2):
print(i)
2 4 6 8
for i in range(10, 1, -2):
print(i)
10 8 6 4 2
numbers_list = []
for i in range(1, 101):
numbers_list.append(i)
nums_list = list(range(1, 101))
numbers_list = [1, 2, 3, 4, 5, 6, 7,]
# 5. Loop control: break, continue, pass
# break example
for i in range(5):
if i == 3:
break
print(f"Break example: {i}")
Break example: 0 Break example: 1 Break example: 2
# continue example
for i in range(5):
if i == 2:
continue
print("Continue example:", i)
Continue example: 0 Continue example: 1 Continue example: 3 Continue example: 4
Range¶
range(start, stop, step)
# range()
for i in range(1, 6):
print(i)
1 2 3 4 5
for i in range(1, 10, 2):
print(i)
1 3 5 7 9
for i in range(10, 1, -1):
print(i)
10 9 8 7 6 5 4 3 2
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index} : {color}")
0 : red 1 : green 2 : blue
colors = ["red", "green", "blue"]
for index, color in enumerate(colors, start=2):
print(f"{index} : {color}")
2 : red 3 : green 4 : blue
# enumerate()
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Index {index} has color {color}")
Index 0 has color red Index 1 has color green Index 2 has color blue
Exercise¶
3. Print Multiplication Table (for loop)¶
Print the multiplication table of a number entered by the user (from 1 to 10). Print in the following format. Use f-string in this case
Input = 2
Output:
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
....
...
2 * 10 = 20
4. Sum of First N Numbers (while loop)¶
Ask the user for a number n and compute the sum of the first n natural numbers using a while loop.
Input : 5
Output : 15
5. Write a program that takes a string input from the user and uses a dictionary to count how many times each character appears in the string. Use a loop to iterate over the string.¶
Example:
Input: "banana"
Output:
{'b': 1, 'a': 3, 'n': 2}
6. Filter out All Even Numbers in a List¶
Write a program that takes a list of integers and uses a loop to create a new list containing only the even numbers from the original list. Then print the new list.
Example:
Input: [1, 4, 7, 8, 10, 3, 6]
Output:
[4, 8, 10, 6]
input_list = [1, 23, 983, 2923, 83, 85, 98, 20, 1]
output_list = []
for num in input_list:
if num % 2 == 0:
output_list.append(num)
print(output_list)
[98, 20]
word = 'banana'
counter_dictionary = {}
for char in word:
if char not in counter_dictionary:
counter_dictionary[char] = 1
elif char in counter_dictionary:
counter_dictionary[char] += 1
print(counter_dictionary)
{'b': 1, 'a': 3, 'n': 2}
'cocot' in ['apple', 'fruites', 'coco', 'mike']
False
List Comprehension¶
numbers = [3, 6, 8, 9, 2]
output_list = []
for number in numbers:
output_list.append(number ** 2)
numbers = [3, 6, 8, 9, 2]
output_list = [number**2 for number in numbers]
print(output_list)
[9, 36, 64, 81, 4]
print(output_list)
[9, 36, 64, 81, 4]
Exercise¶
1. Given a list of words, create a list with each word capitalized. Use List Comprehension.¶
Note: Use string.title() function to capitalize
input_word_list = ['apple', 'banana', 'coco']
output_word_list = ['Apple', 'Banana', 'Coco]
2. Generate pairs of numbers (i, j) where i and j are from 1 to 10, but only where i < j. Use List Comprehension¶
Input: [(2, 5), (5, 2), (3, 7), (8, 2)]
Output : [(2, 5), (3, 7)]
input_list = [(2, 5), (5, 2), (3, 7), (8, 2)]
output_list = []
for pair in input_list:
if pair[0] < pair[1]:
output_list.append(pair)
print(output_list)
[(2, 5), (3, 7)]
input_list = [(2, 5), (5, 2), (3, 7), (8, 2)]
[pair for pair in input_list if pair[0] < pair[1]]
[(2, 5), (3, 7)]