A variable is a name that points to a value. Think of it as a labelled box: you put something in, then use the label to get it back later.
age = 30
name = "Ada"
print(name, "is", age)Output:
Ada is 30
The = sign here does not mean "equals" like in math. It means assign: take the value on the right and store it under the name on the left. You can reassign a variable at any time:
score = 10
score = score + 5
print(score) # 15Naming rules
- Use letters, digits, and underscores. A name can't start with a digit.
- Names are case-sensitive:
ageandAgeare different variables. - Python style is
snake_case, liketotal_price. - You can't use reserved words such as
if,for, orwhileas names.
Tip
Pick names that say what the value is. seconds_left is much easier to read than x.
The basic data types
Every value has a type. Use the built-in type() function to check:
| Type | Name | Example | Used for |
|---|---|---|---|
int | integer | 42, -7 | whole numbers |
float | floating-point | 3.14, -0.5 | numbers with decimals |
str | string | "hello" | text |
bool | boolean | True, False | yes/no answers |
NoneType | none | None | "no value yet" |
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hi")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>A few things worth knowing:
TrueandFalsemust start with a capital letter.Noneis Python's way of saying "nothing here". It's useful as a placeholder, for exampleresult = Nonebefore you've calculated anything.5is anintbut5.0is afloat, even though they look alike."5"is a string, not a number. You can't do math with it.
Type conversion
Sometimes you need to turn one type into another. Use the type's name as a function:
int("42") # 42
float("3.5") # 3.5
str(100) # "100"
int(3.9) # 3 (cuts off the decimal, doesn't round)
bool(0) # FalseThis matters because input() always gives you text, even if the user typed a number:
n = int(input()) # read a line and turn it into an integer
price = float(input())To round a number, use round(number, digits):
print(round(3.14159, 2)) # 3.14
print(round(2.5)) # 2Warning
Converting text that doesn't look like a number crashes the program. int("hello") raises a ValueError, and so does int("3.5"). Use int(float("3.5")) if you need to go from decimal text to an integer.
Why does round(2.5) give 2 instead of 3?
Python uses "banker's rounding": when a number is exactly halfway, it rounds to the nearest even number. So round(2.5) is 2 and round(3.5) is 4. For everyday numbers that aren't exactly halfway, it behaves just like you'd expect.
Putting it together
celsius = 20
fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit) # 68.0
print(type(fahrenheit)) # <class 'float'>Dividing with / always produces a float. You'll meet more operators in the next lesson.
Now try it yourself. The next step is two puzzles where you store values in variables and convert between types.