Python Variables and Types

Primitive Python types are string, integer, float, bool, and None.

Python uses camel_case for variable names.

Type annotations are optional in Python, but help other programmers and your linter to understand your code.

name: str = "John Doe"
phone_number: str = "0800 101 101"
age: int = 23
temperature: float = 25.5
is_true: bool = True
is_false: bool = False
non_existent: None = None

also_an_int = 30

We can print out most Python variables using print(). We can take input as a string using input().

format method and f-strings are helpful for debug output. The format language has a lot of possibilities, as found in the documentation.

# single and double quotes are both fine for Python strings

print('Hello world!')
name: str = input("What's your name?")

greeting: str = "Hi there, {name}".format(name=name)

print(greeting, end=" ")
print(f"Indeed your name is {name}")

We can generally convert between types in Python by using the function with the name of that type.

We can use type() to check that these conversions are successful.

# most conversions are between string and some other type
num_str = "101"
num = int(a)
boo_str = "True"
boo = bool(true_str)

print(type(num_str))
print(type(num))
print(type(boo_str))
print(type(boo))

Knowledge Check

What do each of the type() and print() calls output?

a = "hello"
b = None
c = "12"
d = False

type(a)
type(b)
type(c)
type(d)
type(e)
type(int(c))

print(float(c))

Exercise

Write a program which prompts a user to enter their name, age, and hometown, then prints those details back to them. For example:

Name: Frank
Age: 30
Hometown: Dorking, Surrey, UK

Extension 1: Convert the Age input into a number before printing it.

Extension 2: Print out the type of each of the variables you used.