Simple If Statement
x = 10
if x > 5:
print("x is greater than 5")
::::::::::::::::::::::::::::::::::::::::
If-Else Statement
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
::::::::::::::::::::::::::::::::::::::::::::::
If-Elif-Else Statement
x = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
:::::::::::::::::::::::::::::::::::::::::::
Nested If Statements
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
:::::::::::::::::::::::::::::::::::::::::::
Using Logical Operators
x = 10
if x > 5 and x < 15:
print("x is between 5 and 15")
:::::::::::::::::::::::::::::::::::::::::::::::
Conditions with Lists
Check if an Item is in a List
fruits = ['apple', 'banana', 'cherry']
if 'banana' in fruits:
print("Banana is in the list")
:::::::::::::::::::::::::::::::::::::::::::::::
Check if an Item is not in a List
fruits = ['apple', 'banana', 'cherry']
if 'orange' not in fruits:
print("Orange is not in the list")
::::::::::::::::::::::::::::::::::::::::::::::::
Using a Loop with Conditions
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
::::::::::::::::::::::::::::::::::::::::::::::::::
Conditions with Functions
Function with Conditional Return
def check_even_odd(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
print(check_even_odd(4))
::::::::::::::::::::::::::::::::::::::::::::::::::::
Function with Multiple Conditions
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
print(grade(85))
::::::::::::::::::::::::::::::::::::::::::::::::::::::
Conditions with Dictionaries
Check Key in Dictionary
student = {'name': 'John', 'age': 20}
if 'age' in student:
print("Age is present in the dictionary")
::::::::::::::::::::::::::::::::::::::::::::::::::::
Using get() Method with Default Value
student = {'name': 'John'}
age = student.get('age', 'Not specified')
print(age)
:::::::::::::::::::::::::::::::::::::::::::::::::::
Ternary Operator
Ternary Conditional Operator
x = 10
result = "Greater than 5" if x > 5 else "Not greater than 5"
print(result)
:::::::::::::::::::::::::::::::::::::::::::::::
Conditions with Exception Handling
Try-Except with Conditions
try:
x = int(input("Enter a number: "))
if x < 0:
raise ValueError("Negative number")
except ValueError as e:
print(e)
::::::::::::::::::::::::::::::::::::::::
Conditions with String Methods
Check if String is Uppercase
text = "HELLO"
if text.isupper():
print("The string is uppercase")
:::::::::::::::::::::::::::::::::::::::::::::::::::
Check if String is Lowercase
text = "hello"
if text.islower():
print("The string is lowercase")
:::::::::::::::::::::::::::::::::::::::::::::::::::::
Conditions with Date and Time
Check if Today is Weekend
import datetime
today = datetime.datetime.now()
if today.weekday() >= 5:
print("It's the weekend!")
:::::::::::::::::::::::::::::::::::::::::::::::::::::
Conditions with User Input
User Input Condition
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
:::::::::::::::::::::::::::::::::::::::::::::::::::
19. List Comprehension with Condition
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
:::::::::::::::::::::::::::::::::::::::::::::::::::::
20. Using any() with Conditions
numbers = [1, 3, 5, 7, 8]
if any(num % 2 == 0 for num in numbers):
print("There is at least one even number.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
21. Using all() with Conditions
numbers = [2, 4, 6, 8]
if all(num % 2 == 0 for num in numbers):
print("All numbers are even.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
22. Conditional Statements with Tuples
coordinates = (0, 0)
if coordinates == (0, 0):
print("At the origin")
elif coordinates[0] == 0:
print("On the Y-axis")
elif coordinates[1] == 0:
print("On the X-axis")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
23. Using switch-like Behavior with Dictionaries
def switch_case(value):
switcher = {
1: "One",
2: "Two",
3: "Three"
}
return switcher.get(value, "Invalid")
print(switch_case(2)) # Output: Two
:::::::::::::::::::::::::::::::::::::::::::
def switch_case(value):
if value == 1:
return "Case 1: Value is 1"
elif value == 2:
return "Case 2: Value is 2"
elif value == 3:
return "Case 3: Value is 3"
else:
return "Default case: Value is not 1, 2, or 3"
result = switch_case(2)
print(result)
def case_1():
return "Case 1: Value is 1"
def case_2():
return "Case 2: Value is 2"
def case_3():
return "Case 3: Value is 3"
def default_case():
return "Default case: Value is not 1, 2, or 3"
def switch_case(value):
switch_dict = {
1: case_1,
2: case_2,
3: case_3
}
return switch_dict.get(value, default_case)()
result = switch_case(3)
print(result)
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
24. Checking Multiple Conditions with in
color = "red"
if color in ["red", "green", "blue"]:
print("Color is primary.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
25. Using isinstance() for Type Checking
value = 10
if isinstance(value, int):
print("Value is an integer.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
26. Checking for Empty Structures
my_list = []
if not my_list:
print("The list is empty.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
27. Using len() for Conditions
my_string = "Hello"
if len(my_string) > 5:
print("String is longer than 5 characters.")
else:
print("String is 5 characters or shorter.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
28. Using startswith() Method
filename = "example.txt"
if filename.startswith("example"):
print("Filename starts with 'example'.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
29. Using endswith() Method
filename = "example.txt"
if filename.endswith(".txt"):
print("It's a text file.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
30. Checking for Palindrome
word = "radar"
if word == word[::-1]:
print("It's a palindrome.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::
31. Using isdigit() Method
user_input = "12345"
if user_input.isdigit():
print("Input is a number.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::
32. Using isalpha() Method
user_input = "Hello"
if user_input.isalpha():
print("Input contains only letters.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
33. Using islower() and isupper()
text = "Hello"
if text.islower():
print("All characters are lowercase.")
elif text.isupper():
print("All characters are uppercase.")
else:
print("Mixed case.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
34. Using strip() to Check for Whitespace
user_input = " "
if not user_input.strip():
print("Input is empty or whitespace.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::
35. Using find() Method
text = "Hello, world!"
if text.find("world") != -1:
print("Found 'world' in the text.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::
36. Using replace() Method
text = "Hello, world!"
if "world" in text:
new_text = text.replace("world", "Python")
print(new_text) # Output: Hello, Python!
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
37. Using count() Method
text = "banana"
if text.count("a") > 1:
print("There are multiple 'a's in the word.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
38. Using zip() with Conditions
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
if age > 30:
print(f"{name} is older than 30.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
39. Using filter() with Conditions
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
40. Using map() with Conditions
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2 if x % 2 == 0 else x, numbers))
print(squared_numbers) # Output: [1, 4, 3, 16, 5]
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
41. Using reduce() with Conditions
from functools import reduce
numbers = [1, 2, 3, 4]
sum_of_evens = reduce(lambda x, y: x + y if y % 2 == 0 else x, numbers)
print(sum_of_evens) # Output: 6 (2 + 4)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
42. Using set() to Remove Duplicates
numbers = [1, 2, 2, 3, 4, 4]
unique_numbers = set(numbers)
if len(unique_numbers) < len(numbers):
print("Duplicates were removed.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
43. Using enumerate() with Conditions
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
if fruit == "banana":
print(f"Banana is at index {index}.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
44. Using sorted() with Conditions
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
if sorted_numbers == [1, 2, 5, 9]:
print("Numbers are sorted correctly.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
45. Using join() with Conditions
words = ["Hello", "world"]
if len(words) > 1:
sentence = " ".join(words)
print(sentence) # Output: Hello world
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::
46. Using any() with List Comprehension
numbers = [1, 3, 5, 7, 8]
if any(num % 2 == 0 for num in numbers):
print("There is at least one even number.")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
47. Using all() with List Comprehension
numbers = [2, 4, 6, 8]
if all(num % 2 == 0 for num in numbers):
print("All numbers are even.")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
48. Using max() with Conditions
numbers = [1, 2, 3, 4, 5]
max_number = max(numbers)
if max_number > 3:
print(f"The maximum number is greater than 3: {max_number}")
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
49. Using min() with Conditions
numbers = [1, 2, 3, 4, 5]
min_number = min(numbers)
if min_number < 3:
print(f"The minimum number is less than 3: {min_number}")
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
50. Using random Module with Conditions
import random
number = random.randint(1, 10)
if number > 5:
print(f"The random number {number} is greater than 5.")
else:
print(f"The random number {number} is 5 or less.")