Module 2 · Beginner · Python basics

Python variables and data types, with examples

Python variables and data types for beginners: naming rules, int, float, str, bool, None, type(), type conversion and input(), with practice questions.

By theprogrammers team · · 4 min read

A variable is a name that points to a value, so your program can remember it and use it later. Every value has a data type, which decides what you can do with it: you can add two numbers, but you can't add a number to a word.

This guide covers creating variables, naming rules, Python's basic data types, checking types with type(), converting between types and reading user input.

Creating a variable

Write a name, an equals sign and a value:

name = "Ahana"
age = 20
height = 1.62
is_student = True

print(name, age)    # Ahana 20

The = sign means assign, not "is equal to". Python works out the type from the value, so you never declare it yourself. You can also change what a variable points to at any time:

age = 20
age = age + 1     # now 21
age += 1          # shorter form: now 22

Naming rules

RuleAllowedNot allowed
Letters, digits and underscores onlytotal_markstotal-marks
Can't start with a digitmarks22marks
Can't be a keywordclass_nameclass
Case-sensitiveAge and age are different

By convention, Python variables use snake_case: lowercase words joined by underscores, like first_name. Choose names that say what the value means: price is better than p, and marks_total is better than x.

Python's basic data types

TypeWhat it holdsExample
intWhole numbers42, -7, 1_000_000
floatDecimal numbers3.14, 0.5, 2e3
strText"hello", 'Kanpur'
boolTrue or falseTrue, False
NoneType"No value"None

A few details worth knowing:

  • Python integers have no size limit: 2 ** 100 works.
  • Floats are approximate: 0.1 + 0.2 gives 0.30000000000000004. Use round() when you display them.
  • Strings can use single or double quotes. Use triple quotes for text over several lines.
  • True and False start with a capital letter.

Checking a type with type()

type(42)        # <class 'int'>
type(3.14)      # <class 'float'>
type("42")      # <class 'str'>
type(True)      # <class 'bool'>

isinstance(42, int)    # True

Notice that "42" in quotes is a string, not a number. This difference causes many beginner bugs.

Converting between types

Use the type's name as a function to convert a value:

int("42")        # 42
float("3.5")     # 3.5
str(100)         # '100'
int(3.9)         # 3: int() cuts off the decimals, it doesn't round
bool(0)          # False
bool("hello")    # True

int("abc") raises a ValueError, because "abc" isn't a number. 0, 0.0, an empty string "" and None all count as False; almost everything else counts as True.

Reading user input

input() shows a message and waits for the user to type something. It always returns a string, so convert it before doing maths:

age = input("How old are you? ")     # the user types 20
print(age + 1)                       # TypeError: can only concatenate str to str

age = int(input("How old are you? "))
print(age + 1)                       # 21

Reading several values at once, and handling someone typing letters instead of a number, are covered in Python input and type conversion.

Several variables at once

x, y = 10, 20          # assign two values
x, y = y, x            # swap them: x is 20, y is 10
a = b = 0              # both start at 0

Constants

Python has no true constants. By convention, a name in CAPITAL letters means "don't change this":

GST_RATE = 0.18
MAX_STUDENTS = 60

Practice

  1. Create variables for a product's name, price and quantity, then print the total cost.
Show the answer
product = "Notebook"
price = 45.5
quantity = 3
print(f"{product}: ₹{price * quantity}")    # Notebook: ₹136.5
  1. What does each line print?
print(type(7 / 2))
print(type(7 // 2))
print("5" + "5")
print(int("5") + 5)
Show the answer

<class 'float'>, <class 'int'>, 55 and 10. The / operator always gives a float (3.5), while // divides and rounds down to a whole number (3). Adding two strings joins them.

  1. Ask the user for two numbers and print their sum.
Show the answer
a = float(input("First number: "))
b = float(input("Second number: "))
print("Sum:", a + b)

Without float(), typing 2 and 3 would print 23, because the strings would be joined.

  1. Swap the values of a = 5 and b = 9 without a third variable.
Show the answer
a, b = 5, 9
a, b = b, a
print(a, b)    # 9 5

Interview questions

Is Python statically or dynamically typed?

Dynamically typed: a variable has no fixed type, and the type belongs to the value it currently points to. Python is also strongly typed, because it won't silently mix types: "5" + 5 raises a TypeError instead of guessing.

What is the difference between / and //?

/ is true division and always returns a float: 7 / 2 is 3.5. // is floor division and rounds down: 7 // 2 is 3, and -7 // 2 is -4.

What values are falsy in Python?

False, None, zero of any number type (0, 0.0), and empty collections: "", [], (), {} and set(). Everything else is truthy.

What are mutable and immutable types?

An immutable value can't be changed after it is created: int, float, str, bool and tuple. A mutable value can be changed in place: list, dict and set. "Changing" a string actually creates a new string.

What to learn next

  1. Do calculations with Python numbers and operators.
  2. Work with text using Python strings and string methods.