Variables and types
Programs work with data. This chapter shows how to name it, what kinds of data Python has, and how to move between them.
Variables
A variable is a name that refers to a value. You create one with =:
name = "Ada"
age = 19
print(name)
print(age)
= means "make this name refer to this value", not "is equal to". You can point a name at a new value at any time:
score = 10
score = score + 5
print(score) # 15
Variable names can contain letters, digits and underscores, but cannot start with a digit. Python style is lowercase words joined by underscores, like total_score.
The basic types
int: whole numbers like42or-7.float: numbers with a decimal point like3.14.str: text in quotes, like"hello"or'hello'.bool: eitherTrueorFalse.
Use type() to ask Python what type a value has:
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("hi")
<class 'str'>
Working with numbers
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 % 3) # 1
print(2 ** 10) # 1024
/ always gives a float. Floats are stored in binary, so some decimals cannot be exact: 0.1 + 0.2 gives 0.30000000000000004. That is normal in every language, not a Python bug.
Working with strings
first = "Grace"
last = "Hopper"
full = first + " " + last
print(full) # Grace Hopper
print(len(full)) # 12
print(full.upper()) # GRACE HOPPER
print("ha" * 3) # hahaha
Converting between types
You cannot add a number to a string directly. "Age: " + 19 raises a TypeError. Convert first:
int("42") # 42
float("3.5") # 3.5
str(19) # "19"
int(3.9) # 3 (cuts off the decimal part)
Reading input
input() shows a prompt and waits for the user to type something. It always returns a string, so convert it if you need a number:
name = input("What is your name? ")
year = int(input("What year were you born? "))
print("Hello", name)
f-strings
The cleanest way to mix values into text is an f-string. Put f before the quote and wrap expressions in braces:
name = "Ada"
age = 19
print(f"{name} is {age} years old.")
print(f"Next year: {age + 1}")
print(f"Pi is about {3.14159:.2f}") # 3.14
Exercises
1. Swap
Given a = 1 and b = 2, swap their values so that a is 2 and b is 1.
Show answer
a, b = b, a
Python evaluates the right side first, then assigns both names at once. In many other languages you need a temporary variable.
2. Temperature converter
Ask the user for a temperature in Celsius and print it in Fahrenheit with one decimal place. The formula is F = C × 9 / 5 + 32.
Show answer
c = float(input("Celsius: "))
f = c * 9 / 5 + 32
print(f"{c} C is {f:.1f} F")
3. Predict the output
What does print("5" + "5", 5 + 5, "5" * 3) print?
Show answer
55 10 555. Adding strings joins them, adding numbers does arithmetic, and multiplying a string repeats it. print separates its arguments with spaces.