Module 003 · 35 min
Python Programming
Write your first line of Python, then build a calculator and a guessing game.
Learn
Your first program
Type print('Hello, dragon!') in a Python 3 editor and run it. print displays a message. Use an offline Python 3 editor. On a shared or managed device, check with the person who manages it before installing software.
Variables and types
A variable gives a value a name. In score = 3, score holds an integer. In name = 'Dragon', name holds a string (text). input returns text. int or float can convert number-shaped text to a number.
Conditions and loops
if runs a block when its condition is true. elif checks another condition and else handles the remaining case. A for loop repeats a block for each item in a sequence. Four spaces show which lines belong inside each block.
Addition and subtraction calculator
try:
a = float(input("First number: "))
operation = input("Choose + or -: ").strip()
b = float(input("Second number: "))
if operation == "+":
print("Answer:", a + b)
elif operation == "-":
print("Answer:", a - b)
else:
print("Please choose + or -.")
except ValueError:
print("Please enter numbers such as 4 or 2.5.")Number-guessing game
from random import randint
secret = randint(1, 10)
for attempt in range(1, 5):
text = input(f"Turn {attempt}: Guess 1 to 10: ").strip()
if text not in [str(number) for number in range(1, 11)]:
print("Choose a whole number from 1 to 10.")
continue
guess = int(text)
if guess == secret:
print("You found it!")
break
if guess < secret:
print("Too low.")
else:
print("Too high.")
else:
print("The number was", secret)Practise
- Run your first print command and change the words between the quotes.
- Save the calculator as calculator.py. Try 2.5 + 3, then try entering an invalid number.
- Save the game as guess.py. Play a round. Change range(1, 5) to range(1, 7) and count the turns.
Check your understanding
Quotes make '7' text. int('7') converts this text to the integer 7. break leaves the loop immediately when your guess matches the secret.Completion checklist
Tick each item when you can do it. Finish the checklist to earn the Python Builder badge.