YOUR PYTHON TOOLKITHow do I…?
Find an example. Copy the code. Paste it into your editor and give it a go.
1 Read an input2 Work with a value3 Show the result
Use input() to read text. Python calls a piece of text a string.
PYTHON
name = input("What is your name? ")
print("Hello", name)
Try it: Type Alex. The console shows: Hello Alex
Remember: input() gives you a string, even if you type digits.
123INPUT
Read in an integer
Put int() around input() to turn the answer into a whole number.
PYTHON
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
Try it: Type 13. The console shows: Next year you will be 14
Remember: Enter a whole number such as 13. Words or decimal numbers will cause an error.
+CALCULATE
Add two numbers
Read two numbers, add them with +, then show the total.
PYTHON
first = int(input("First number: "))
second = int(input("Second number: "))
total = first + second
print("Total:", total)
Try it: Type 7, then 5. The console shows: Total: 12
Remember: Convert both answers with int(). Otherwise, Python joins the text: "7" + "5" becomes "75".
Use print() to show a message in the console.
PYTHON
print("Hello, world!")
Try it: The console shows: Hello, world!
Remember: Put quotation marks around text. Do not put them around variable names.
A variable is a name for a value. Use = to store a value under that name.
PYTHON
score = 10
score = score + 5
print(score)
Try it: The console shows: 15
Remember: Read the right side of = first. Then store the result in the name on the left.
1.5INPUT
Read a decimal number
Use float() when an answer can have a decimal point.
PYTHON
price = float(input("Price: "))
print("Double the price:", price * 2)
Try it: Type 2.5. The console shows: Double the price: 5.0
Remember: int() is for whole numbers. float() can read numbers such as 2.5.
Use if to check a condition. Use else for what to do when it is false.
PYTHON
age = int(input("Age: "))
if age >= 12:
print("You are 12 or older")
else:
print("You are under 12")
Try it: Type 13. The console shows: You are 12 or older
Remember: End if and else lines with a colon. Indent the code underneath by four spaces.
×3LOOP
Repeat a set number of times
Use a for loop to repeat code. range(3) gives the values 0, 1 and 2.
PYTHON
for number in range(3):
print("Hello", number)
Try it: The console shows Hello 0, Hello 1 and Hello 2 on separate lines.
Remember: range(3) stops before 3. The indented line runs three times.
↻LOOP
Repeat while a condition is true
A while loop keeps going while its condition is true.
PYTHON
count = 1
while count <= 3:
print(count)
count = count + 1
Try it: The console shows 1, 2 and 3 on separate lines.
Remember: Change count inside the loop. Without that change, this loop would never finish.