Python · Syntax · Beginner

Conditions

15 tasks

Practical exercises with conditional statements in Python: comparing numbers, checking ranges, working with strings, passwords, percentages, and basic if, elif, else logic.

How Python makes decisions

#
A program without choices would be pretty boring — it would do the same thing every single time, regardless of what the user enters or what data it receives. Conditional statements fix that. They let your code look at a value and take a different path depending on what it finds. The if statement is the main tool for this. Here is its full form: ```python if condition: # runs when condition is True elif another_condition: # runs when the first was False, but this one is True elif yet_another: # you can have as many elif branches as you need else: # runs when nothing above matched ``` The colon after each condition is required — Python treats it as the start of a block. Everything inside that block must be indented, four spaces by convention. Python uses indentation to know where a block begins and ends, unlike languages that use curly braces for this. Python checks conditions top to bottom and stops at the first one that is True. Only one branch ever runs — the rest are skipped entirely. So order matters: put the most specific checks first. elif and else are both optional. A plain if with nothing after it is completely valid when you only need to act in one specific case and do nothing otherwise.

Comparing values and combining conditions

#
A condition is any expression that evaluates to True or False. Most conditions are comparisons, built with these six operators: ```python a == b # True when a and b are equal a != b # True when they differ a > b # True when a is strictly greater a < b # True when a is strictly less a >= b # True when a is greater than or equal a <= b # True when a is less than or equal ``` One thing worth remembering: == tests equality, while = assigns a value. Using a single = inside a condition is a syntax error in Python — which is actually a good thing, because the language makes this particular mistake impossible. When one condition is not enough, combine them with and and or: ```python if age >= 13 and age <= 17: print("Teenager") if score < 0 or score > 100: print("Score out of range") ``` With and, both sides must be True for the whole condition to pass. With or, it passes if at least one side is True. You can also negate a condition with not: ```python if not is_admin: print("Access denied") ``` Python also supports chained comparisons, which read more naturally for range checks: ```python if 13 <= age <= 17: print("Teenager") ``` This is exactly equivalent to age >= 13 and age <= 17, but looks closer to how you would write it in mathematics. Both forms are valid — use whichever reads more clearly.

Reading input and common patterns

#
In these exercises the program reads something from the user and makes a decision based on it. All input arrives as a string, so the first thing you usually need to do is convert it to the right type. ```python number = float(input("Enter a number: ")) if number > 0: print("Positive") elif number < 0: print("Negative") else: print("Zero") ``` Use int() when you need a whole number and float() when you need a decimal. Forgetting the conversion means Python will try to compare a string against a number, which raises a TypeError at runtime — one of the most common beginner mistakes. Checking divisibility with the modulo operator: ```python n = int(input("Enter a number: ")) if n % 2 == 0: print("Even") else: print("Odd") ``` The % operator returns the remainder after integer division. n % 2 is 0 for every even number and 1 for every odd number. The same idea scales to any divisor: n % 3 == 0 checks divisibility by 3, n % 10 == 0 checks for multiples of ten, and so on. Checking string or list length with len(): ```python password = input("Enter a password: ") if len(password) < 6: print("Too short") else: print("Accepted") ``` len() works on strings, lists, and tuples. You will see it constantly throughout these topics. Guarding against division by zero: ```python a = float(input("a: ")) b = float(input("b: ")) if b == 0: print("Cannot divide by zero") else: print(a / b) ``` Always check the divisor before dividing. If b is zero and you attempt a / b anyway, Python raises a ZeroDivisionError and the program crashes. The if-guard pattern here is the standard fix.

Conditions quick reference

#
**Comparison operators** | Operator | Meaning | Example | |---|---|---| | `==` | equal | `x == 5` | | `!=` | not equal | `x != 0` | | `>` | greater than | `age > 18` | | `<` | less than | `age < 18` | | `>=` | greater or equal | `score >= 60` | | `<=` | less or equal | `score <= 100` | **Boolean operators** | Operator | Result is True when… | |---|---| | `a and b` | both `a` and `b` are True | | `a or b` | at least one of them is True | | `not a` | `a` is False | **Chained comparisons** ```python # instead of age >= 13 and age <= 17 if 13 <= age <= 17: print('Teenager') # works with any chain if 0 < x < 100: print('In range') ``` **Truthy and falsy values** Any value can be used directly in an `if` without comparing to anything. Python treats these as **False**: `0`, `0.0`, `''` (empty string), `[]`, `{}`, `None`. Everything else is **True**. ```python name = input('Enter name: ') if name: # True when name is not empty print('Hello,', name) items = [] if not items: # True when the list is empty print('Nothing here') ``` **Common patterns** ```python # divisibility if n % 2 == 0: print('even') if n % 3 == 0: print('divisible by 3') # range guard if 0 <= score <= 100: print('valid score') # division guard if b != 0: print(a / b) # type conversion before comparison n = int(input('Enter a number: ')) ```
01

Checking the sign of a number.

#

Write a program that takes a number and displays whether it is positive, negative, or zero.

number = float(input("Enter a number: "))
Solution
number = float(input("Enter a number: "))

if number > 0:
    print("The number is positive")
elif number < 0:
    print("The number is negative")
else:
    print("The number is zero")

# Or you can do this: first prepare the message, and then print it once
number = float(input("Enter a number: "))

if number > 0:
    result = "The number is positive"
elif number < 0:
    result = "The number is negative"
else:
    result = "The number is zero"

print(result)
02

Age category.

#

The program takes the user's age and displays: "Child" (up to 12), "Teenager" (13–17), "Adult" (18 and older).

age = int(input("Enter age: "))

Solution
age = int(input("Enter age: "))

if age <= 12:
    print("Child")
elif age <= 17:
    print("Teenager")
else:
    print("Adult")

# second option: the boundaries can be written explicitly
age = int(input("Enter age: "))

if age < 13:
    print("Child")
elif age >= 13 and age <= 17:
    print("Teenager")
else:
    print("Adult")
03

The larger of two numbers.

#

The user enters two numbers. Display the larger one. If they are equal, display the message "The numbers are equal".

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

Solution
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

if a > b:
    print("Larger number:", a)
elif b > a:
    print("Larger number:", b)
else:
    print("The numbers are equal")

# or you can do this using the result variable
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

if a == b:
    result = "The numbers are equal"
elif a > b:
    result = f"Larger number: {a}"
else:
    result = f"Larger number: {b}"

print(result)
04

Temperature: cold, warm, hot.

#

The program takes a temperature and displays: "Cold" (less than 10), "Warm" (10–24), "Hot" (25 and higher).

temp = float(input("Enter temperature: "))

Solution
temp = float(input("Enter temperature: "))

if temp < 10:
    print("Cold")
elif temp <= 24:
    print("Warm")
else:
    print("Hot")
05

Checking if a number is even.

#

The user enters a number. Check whether it is even.

num = int(input("Enter a number: "))

Solution
num = int(input("Enter a number: "))

if num % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")

# or you can do this: store the check in a separate variable
num = int(input("Enter a number: "))

is_even = num % 2 == 0

if is_even:
    print("The number is even")
else:
    print("The number is odd")
06

Checking password length.

#

The user enters a password. If the password length is less than 6 characters — display "Password is too short", otherwise — "Password accepted".

password = input("Enter password: ")

Solution
password = input("Enter password: ")

if len(password) < 6:
    print("Password is too short")
else:
    print("Password accepted")
07

Grade on the A-F scale.

#

The user enters a grade from 0 to 100. Display: A (90–100), B (80–89), C (70–79), D (60–69), F (less than 60).

score = int(input("Enter grade: "))

Solution
score = int(input("Enter grade: "))

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

# or you can do this: move from smaller boundaries to larger ones
score = int(input("Enter grade: "))

if score < 60:
    print("F")
elif score < 70:
    print("D")
elif score < 80:
    print("C")
elif score < 90:
    print("B")
else:
    print("A")
08

Divisibility of two numbers.

#

The user enters two numbers. Check whether the first number is divisible by the second.

a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

Solution
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

if b == 0:
    print("Division by zero is not allowed")
elif a % b == 0:
    print("The first number is divisible by the second")
else:
    print("The first number is not divisible by the second")
09

Rounding within the range 0-100.

#

The user enters a non-integer number. If it is greater than 100 or less than 0 — display "Only from 0 to 100", otherwise round it using round to 2 decimal places.

num = float(input("Enter a number: "))

Solution
num = float(input("Enter a number: "))

if num < 0 or num > 100:
    print("Only from 0 to 100")
else:
    print(round(num, 2))

# or you can do this: store the range check in a variable
num = float(input("Enter a number: "))

in_range = 0 <= num <= 100

if in_range:
    print(round(num, 2))
else:
    print("Only from 0 to 100")
10

Long or short string.

#

The user enters a string. If the string length is greater than 10 characters — display "Long string", otherwise — "Short string".

text = input("Enter a string: ")

Solution
text = input("Enter a string: ")

if len(text) > 10:
    print("Long string")
else:
    print("Short string")

# or you can do this using the message variable
text = input("Enter a string: ")

if len(text) > 10:
    message = "Long string"
else:
    message = "Short string"

print(message)
11

Percentage of a number.

#

The user enters a and b. Calculate what percentage a is of b. Percentage formula: (a/b)*100.

a = float(input("Part: "))
b = float(input("Of whole: "))

Solution
a = float(input("Part: "))
b = float(input("Of whole: "))

if b == 0:
    print("Division by zero is not allowed! And there is no part of 0.")
else:
    result = (a / b) * 100
    result = round(result, 2)
    print(str(result) + "%")

# or you can do this: round immediately when creating result
a = float(input("Part: "))
b = float(input("Of whole: "))

if b == 0:
    print("Division by zero is not allowed! And there is no part of 0.")
else:
    result = round((a / b) * 100, 2)
    print(str(result) + "%")
12

Rounding to the required decimal place.

#

The user enters a non-integer number, for example 5.2564494, and enters to which decimal place (digit after the decimal point) it should be rounded. Perform the calculations.

num = float(input("Enter a number: "))
rounding = int(input("How many decimal places to round to: "))

Solution
num = float(input("Enter a number: "))
rounding = int(input("How many decimal places to round to: "))

if rounding < 0:
    print("The value for the number of decimal places cannot be less than 0.")
    # Although if you pass a negative number to round as the number of digits,
    # the result of rounding will simply be 0. This was done intentionally so there are no errors.
else:
    print(round(num, rounding))
13

Choosing int or float.

#

The user enters a number. Check whether the entered value contains a decimal point. If it does, convert it to float; if there is no point, convert it to int.

num = input("Enter a number: ")

Solution
num = input("Enter a number: ")

if "." in num:
    num = float(num)
else:
    num = int(num)

print(num)

# second option: you can also check for a comma if the user enters the number in that format
num = input("Enter a number: ")

if "." in num or "," in num:
    num = num.replace(",", ".")
    num = float(num)
else:
    num = int(num)

print(num)
14

Division without a zero error.

#

You need to divide a by b. If b equals 0, display a message that division by 0 is not allowed. Otherwise, calculate the result!

a = float(input("Enter a number: "))
b = float(input("Enter the 2nd number: "))

Solution
a = float(input("Enter a number: "))
b = float(input("Enter the 2nd number: "))

if b == 0:
    print("Division by zero is not allowed! Even if you really want to!")
else:
    print("Result:", a / b)


# OR
if b == 0:
    print("Division by zero is not allowed! Even if you really want to!")
else:
    result = a / b
    print("Result:", result)


# OR
if b == 0:
    print("Division by zero is not allowed! Even if you really want to!")
else:
    result = a / b
    print("Result:", round(result, 2))


# OR
if b == 0:
    result = "Division by zero is not allowed! Even if you really want to!"
else:
    result = round(a / b, 2)

print("Result:", result)


# OR other convenient options for this situation, even like this:
if b == 0:
    message = "Division by zero is not allowed! Operation error -"
    result = False
else:
    message = "Result:"
    result = round(a / b, 2)

print(message, result)
15

First name and last name form.

#

The user enters a First Name and then separately a Last Name. Let's try to make it so that if everything is entered correctly, we combine the First Name and Last Name into one string (as one new object) and display it in the terminal. But if the user makes a mistake and enters both the First Name and Last Name at once in the "First Name" field, then display the message: "Fill out the form carefully!! That was the last blank form hahaha)))" and terminate the program. Hints: 1) There will be a space in the string if everything is entered at once. 2) Check the incorrect case first, it will be easier and more correct.

name = input("Enter First Name: ")
last_name = input("Enter Last Name: ")
Solution
name = input("Enter First Name: ")
last_name = input("Enter Last Name: ")

if " " in name:
    print("Fill out the form carefully!! That was the last blank form hahaha)))")
else:
    full_name = name + " " + last_name
    print(full_name)


# or more carefully using the or operator:
if " " in name:
    print("Fill out the form carefully!! That was the last blank form hahaha)))")
elif name == "" or last_name == "":
    print("The form must be filled out completely!! (start over for now)")
else:
    full_name = name + " " + last_name
    print(full_name)