Variables and Data Types

40 min read Getting Started with Python

This is a free course. Log in to run the code exercises and track your progress.

Variables and Data Types

A variable is a name that refers to a value stored in memory. You create one by assigning a value with =. The value can be changed later.

name = "Riya"      # str (string): text
age = 14           # int: whole number
height = 1.52      # float: number with a decimal point
is_student = True  # bool: True or False
print(type(age))   # <class 'int'>

Rules for naming a variable (an identifier):

  • It can contain letters, digits and the underscore _, and cannot start with a digit (marks1 is valid, 1marks is not).
  • It cannot be a keyword such as if, for or while. Avoid built-in names such as print or input too: reusing one hides the function.
  • Python is case-sensitive: Marks and marks are two different variables.

Use type(x) to find the data type of a value.

Python exercise

Read a name and an age from one line. Store the age as an int and print <name> will be <age + 1> next year.

name, age = input().split()
# age is a string here: convert it to int before adding 1
print(name, "will be", age, "next year")

Log in to edit and run this code.