Lesson 8 +10 XP

Variables

Variables

Variables are named boxes that hold values. In Python you create one with a single =, and no type name is needed.

x = 5
name = "Ada"
price = 19.99

No type declaration

Unlike C or Java, Python figures out the type from the value. x = 5 makes x an integer automatically.

You can reassign

A variable can change value at any time, even to a different type:

x = 5
x = "now I'm text"
print(x)  # now I'm text

Use the variable

a = 10
b = 20
print(a + b)  # 30

Casting (changing type)

You can force a type with int(), float(), and str():

x = str(3)    # "3"
y = int(3.7)  # 3
z = float(3)  # 3.0

Find the type

type() tells you what type a value is:

print(type(5))     # <class 'int'>
print(type("hi"))  # <class 'str'>

Strings can use single or double quotes

a = "double"
b = 'single'

Both are strings.

TL;DR

  • variable = value creates a variable.
  • No type keyword needed; Python guesses from the value.
  • Variables can be reassigned to any type.
  • type() shows a value's type.