In Python, you can use logical conditions to make decisions in your code. These conditions are similar to the ones you’ve seen in mathematics:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
These conditions are often used in "if statements" and loops to control the flow of your program. An "if statement" allows your program to execute certain code only if a specific condition is true. You can write an if statement using the if keyword.
a = 50 b = 100 if b > a: print("b is greater than a.") |
In this example, we have two variables, a and b. The if statement checks if b is greater than a. Since a is 50 and b is 100, the condition b > a is true, so the program prints "b is greater than a".
Importance of Indentation
Python uses indentation (spaces or tabs at the beginning of a line) to define the scope of code blocks. This is different from many other programming languages that use curly braces {}.
Example Without Proper Indentation:
a = 50 b = 100 if b > a: print("b is greater than a.") |
In this example, the lack of indentation for the print statement will raise an error because Python expects the code inside the if statement to be indented. Correct indentation is crucial for your code to work properly.
Example:
Problem Statement: Write a Python program that takes a single character input from the user and checks if it is a vowel (a, e, i, o, u). If the character is a vowel, print "The character <char> is a vowel".
Instructions:
- Prompt the user to enter a single character.
- Use an if statement to check if the character is in the string 'aeiou'.
- If the condition is true, print "The character <char> is a vowel".
Example Output:
Enter a character: a |
Solution:
# Step 1: Prompt the user to enter a single character char = input("Enter a character: ") # Step 2: Check if the character is a vowel if char in 'aeiou': # Step 3: Print the result print(f"The character {char} is a vowel") |