Unays Learn · Python

Your first Python program: input, loops and lists

Python is a popular first programming language because its code reads almost like English. You will write several short programs and finish with a quiz game.

Reading input

input() reads a line the user types. It always returns text, so convert it when you need a number:

name = input("What is your name? ")
year = int(input("What year were you born? "))
print(f"Hi {name}, you are about {2026 - year} years old.")

If the user types something that is not a whole number, int() raises a ValueError. You will learn to handle that below.

Making decisions

score = int(input("Your test score: "))

if score >= 90:
    print("Excellent!")
elif score >= 50:
    print("You passed.")
else:
    print("Keep practising.")

Python uses indentation (usually four spaces) to show which lines belong to the if. Inconsistent indentation causes an IndentationError.

Loops and lists

A list holds several values in order. A for loop visits each one:

fruits = ["apple", "banana", "cherry"]
fruits.append("mango")

for fruit in fruits:
    print(fruit.upper())

print(len(fruits), "fruits")

To repeat something a set number of times, loop over range(). range(1, 6) gives 1, 2, 3, 4, 5 (the end number is not included):

for n in range(1, 6):
    print(n, "x 3 =", n * 3)

Project: a small quiz

questions = [
    ("What is the capital of Albania?", "tirana"),
    ("How many sides does a hexagon have?", "6"),
    ("What gas do plants take in?", "carbon dioxide"),
]

score = 0
for question, answer in questions:
    reply = input(question + " ").strip().lower()
    if reply == answer:
        print("Correct!")
        score += 1
    else:
        print(f"Not quite. The answer is {answer}.")

print(f"You scored {score} out of {len(questions)}.")

.strip() removes extra spaces and .lower() makes the comparison ignore capital letters, so "Tirana" and " tirana " both count as correct.

Handling bad input

while True:
    try:
        age = int(input("Your age: "))
        break
    except ValueError:
        print("Please type a whole number.")

The program keeps asking until it gets a valid number instead of crashing.

Try it yourself

Open Unays Code, choose Python, and add three questions of your own to the quiz. Then show a different message for a perfect score.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].