Basic if Statement
A basic if statement executes a block of code only if a condition is true.
# Example 1: Checking a number
age = 20
if age >= 18:
print("You are an adult.")
# Example 2: Checking a string
name = "Alice"
if name == "Alice":
print("Hello, Alice!")
# Example 3: Checking a boolean value
is_sunny = True
if is_sunny:
print("It's a good day for a walk.")
if-else Statement
An if-else statement provides an alternative block of code to execute if the initial if
condition is false.
# Example 4: Even or odd number
number = 7
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
# Example 5: Checking user input
user_input = "yes"
if user_input == "yes":
print("You confirmed.")
else:
print("You did not confirm.")
if-elif-else Statement
The if-elif-else (short for "else if") statement allows you to check multiple conditions
sequentially. Once a condition is true, its corresponding block is executed, and the rest
are skipped.
# Example 6: Grading system
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: Fail")
# Example 7: Time of day
hour = 14
if hour < 12:
print("Good morning!")
elif hour < 18:
print("Good afternoon!")
else:
print("Good evening!")
Nested if Statements
You can place if statements inside other if statements to check more complex conditions.
# Example 8: Eligibility for a discount
is_member = True
purchase_amount = 120
if is_member:
if purchase_amount > 100:
print("You qualify for a 15% member discount on large purchases!")
else:
print("You qualify for a 5% member discount.")
else:
print("No member discount available.")
Combining Conditions with and and or
You can use logical operators and and or to combine multiple conditions within a single
if statement.
# Example 9: Checking multiple criteria (and)
temperature = 25
is_raining = False
if temperature > 20 and not is_raining:
print("It's a perfect day for outdoor activities.")
else:
print("Might need to adjust plans.")
# Example 10: Checking alternative criteria (or)
day_of_week = "Saturday"
is_holiday = False
if day_of_week == "Saturday" or day_of_week == "Sunday" or is_holiday:
print("It's the weekend or a holiday!")
else:
print("It's a weekday.")
if with in operator (for membership)
You can use the in operator to check if an item exists within a sequence (like a string,
list, or tuple).
# Example 11: Checking if a character is in a string
message = "Hello World"
if "World" in message:
print("The word 'World' is in the message.")
# Example 12: Checking if an item is in a list
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("We have bananas!")
These examples cover the fundamental ways to use if conditions in Python. Remember
that indentation is crucial in Python to define the blocks of code associated with each if,
elif, and else statement.
Understanding Lists
A list in Python is an ordered, mutable (changeable) collection of items. Items can be of
different data types. Lists are defined using square brackets [].
List Examples with Operations
Here are more than 10 examples, categorized by the type of operation:
1. Creating and Accessing Lists
# Example 1: Creating a simple list
fruits = ["apple", "banana", "cherry", "date"]
print(f"Original fruits list: {fruits}")
# Example 2: Accessing elements by index (0-based)
print(f"First fruit: {fruits[0]}")
print(f"Last fruit: {fruits[-1]}") # Negative index accesses from the end
print(f"Second to last fruit: {fruits[-2]}")
2. Modifying List Elements
# Example 3: Changing an element
numbers = [10, 20, 30, 40]
numbers[1] = 25 # Change the second element
print(f"Numbers after modification: {numbers}")
3. Adding Elements
# Example 4: Appending an element to the end
colors = ["red", "green", "blue"]
[Link]("yellow")
print(f"Colors after append: {colors}")
# Example 5: Inserting an element at a specific position
items = ["chair", "table", "lamp"]
[Link](1, "sofa") # Insert "sofa" at index 1
print(f"Items after insert: {items}")
# Example 6: Extending a list with another list (concatenation)
list1 = [1, 2, 3]
list2 = [4, 5]
[Link](list2)
print(f"List1 after extend: {list1}")
4. Removing Elements
# Example 7: Removing a specific value
animals = ["dog", "cat", "bird", "dog"]
[Link]("dog") # Removes the first occurrence of "dog"
print(f"Animals after removing first 'dog': {animals}")
# Example 8: Removing an element by index (and getting its value)
cities = ["London", "Paris", "Rome", "Berlin"]
removed_city = [Link](2) # Removes and returns the element at index 2 ("Rome")
print(f"Cities after pop: {cities}")
print(f"Removed city: {removed_city}")
# Example 9: Deleting elements using 'del'
my_list = ["a", "b", "c", "d", "e"]
del my_list[1] # Deletes element at index 1 ("b")
print(f"My_list after del index: {my_list}")
del my_list[0:2] # Deletes a slice of elements
print(f"My_list after del slice: {my_list}")
# Example 10: Clearing all elements from a list
empty_me = [1, 2, 3, 4, 5]
empty_me.clear()
print(f"Empty_me after clear: {empty_me}")
5. List Slicing
# Example 11: Getting sub-lists (slicing)
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(f"Alphabets: {alphabets}")
print(f"First three alphabets: {alphabets[0:3]}") # or alphabets[:3]
print(f"Alphabets from index 2 to 5: {alphabets[2:6]}")
print(f"Alphabets from index 4 to end: {alphabets[4:]}")
print(f"All alphabets (copy): {alphabets[:]}")
print(f"Alphabets with step of 2: {alphabets[::2]}")
6. Checking Membership
# Example 12: Checking if an item exists in a list
cars = ["Ford", "BMW", "Audi"]
if "BMW" in cars:
print("BMW is in the cars list.")
if "Toyota" not in cars:
print("Toyota is not in the cars list.")
7. List Length and Other Utilities
# Example 13: Getting the length of a list
data = [10, 20, 30, 40, 50, 60]
print(f"Length of data list: {len(data)}")
# Example 14: Sorting a list
unsorted_numbers = [5, 2, 8, 1, 9]
unsorted_numbers.sort() # Sorts the list in-place (modifies the original list)
print(f"Sorted numbers: {unsorted_numbers}")
# Example 15: Reversing a list
original_list = [1, 2, 3, 4, 5]
original_list.reverse() # Reverses the list in-place
print(f"Reversed list: {original_list}")
# Example 16: Counting occurrences of an item
items_count = [1, 2, 2, 3, 2, 4]
count_of_2 = items_count.count(2)
print(f"Number of '2's in items_count: {count_of_2}")