Python Essentials Part 2

Python Conditions

In Python, conditions are used to perform different actions based on whether a specific condition is true or false. Python uses conditional statements like if, elif, and else to control the flow of the program.

if Statement

The if statement is used to test a condition. If the condition evaluates to True, the block of code under the if statement is executed. If it's False, the block is skipped.

x = 10
if x > 5:
    print("x is greater than 5")  # Output: x is greater than 5

2. elif Statement

The elif statement stands for "else if." It allows you to check multiple conditions sequentially. If the if condition is False, Python checks the next elif condition.

x = 5
if x > 10:
    print("x is greater than 10")
elif x == 5:
    print("x is equal to 5")  # Output: x is equal to 5

3. else Statement

The else statement is used to execute a block of code if none of the previous if or elif conditions are True.

x = 3
if x > 10:
    print("x is greater than 10")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")  # Output: x is less than 5

4. Comparison Operators

Conditions typically use comparison operators to evaluate the relationship between values:

  • ==: Equal to

  • !=: Not equal to

  • >: Greater than

  • <: Less than

  • >=: Greater than or equal to

  • <=: Less than or equal to

      x = 7
      if x == 7:
          print("x is equal to 7")  # Output: x is equal to 7
    

    5. Logical Operators

    You can use logical operators to combine multiple conditions:

    • and: Returns True if both conditions are true.

    • or: Returns True if at least one condition is true.

not: Returns True if the condition is false (negates the condition).

x = 8
if x > 5 and x < 10:
    print("x is between 5 and 10")  # Output: x is between 5 and 10

if x == 8 or x == 10:
    print("x is either 8 or 10")  # Output: x is either 8 or 10

if not x == 5:
    print("x is not 5")  # Output: x is n

6. Nested Conditions

You can nest one if statement inside another to create more complex condition checks.

x = 10
y = 20
if x > 5:
    if y > 15:
        print("x is greater than 5 and y is greater than 15")  # Output: x is greater than 5 and y is greater than 15

Python Loops

Loops in Python are used to repeatedly execute a block of code as long as a condition is true. Python primarily provides two types of loops: for loops and while loops.

1. for Loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range). It repeats the block of code for each element in the sequence.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

2. while Loop

The while loop keeps executing as long as the condition is True. Once the condition becomes False, the loop stops.

x = 1
while x <= 5:
    print(x)
    x += 1  # Increment x by 1

3. Looping through a range()

The range() function generates a sequence of numbers, which can be used with loops.

for i in range(1, 6):
    print(i)

4. break Statement

The break statement is used to exit a loop prematurely, regardless of the loop's condition.

for num in range(1, 10):
    if num == 5:
        break  # Exit the loop when num is 5
    print(num)

5. continue Statement

The continue statement skips the current iteration of the loop and moves to the next one.

for num in range(1, 6):
    if num == 3:
        continue  # Skip the iteration when num is 3
    print(num)

6. else with Loops

Python allows using the else clause with loops. The else block is executed when the loop terminates naturally, meaning it did not terminate using break.

Example with for Loop:

for num in range(1, 4):
    print(num)
else:
    print("Loop finished")

Python User Input

In Python, you can prompt the user for input during the execution of a program using the built-in input() function. This allows interaction between the user and the program, enabling the user to provide data that the program can process.

Getting User Input

The input() function allows the user to type data at runtime. By default, the input is always returned as a string, so if numeric input is required, you’ll need to convert it.

name = input("Enter your name: ")
print("Hello, " + name)

Handling Numeric Input

If the user is expected to input numbers, you must convert the string to the appropriate data type, such as int or float.

age = input("Enter your age: ")  # Input is taken as a string
age = int(age)  # Convert the string to an integer
print(f"You are {age} years old.")

Using input() in Loops

You can combine the input() function with loops to repeatedly ask for user input.

while True:
    name = input("Enter your name (type 'quit' to exit): ")
    if name == 'quit':
        break
    print(f"Hello, {name}!")

Validation of User Input

It’s a good idea to validate user input to ensure the program behaves correctly even if invalid data is entered.

Example:

while True:
    age_input = input("Enter your age: ")
    if age_input.isdigit():  # Check if the input is a digit
        age = int(age_input)
        print(f"You are {age} years old.")
        break
    else:
        print("Invalid input. Please enter a number.")