Skip to content

Python Basics: Variables, Data Types and Type Casting

Python is a simple, readable and powerful programming language used for web development, automation, data science, data engineering and AI. In this first lesson you will learn how to create variables, work with different data types, convert between types and print values in a clean way.

  • Variables and multiple assignment
  • Data types and the type() function
  • Type casting
  • Unpacking a list into variables
  • f-strings and docstrings
  • match-case (Python 3.10+)

Your First Python Program

Python needs no class or main method. One line is a complete program:

print("Hello Students!!")

Variables

A variable is a name that refers to a value. You don't declare the type: Python works it out from the value you assign.

x1 = 20
y1 = x1          # y1 now refers to the same value
print(y1)        # 20

a = 45           # int
b = "heyy"       # str
c = 3.14         # float
print(a, b, c)

Assigning values in a single line

# same value to many variables
aa = bb = cc = 44
print(aa, bb, cc)          # 44 44 44

# different values to many variables
mm, nn, oo = 23, "Divyani", 56.0
print(mm, nn, oo)          # 23 Divyani 56.0

Rules for variable names

  • Must start with a letter or underscore, never with a digit
  • Can contain only letters, digits and underscore
  • Names are case-sensitive: age, Age and AGE are three variables
  • Cannot be a Python keyword such as if, for or class

Data Types and type()

Use type() to see the data type of any value.

x2 = 47.79
print(type(x2))            # <class 'float'>

print(type(10))            # <class 'int'>
print(type("Python"))      # <class 'str'>
print(type(True))          # <class 'bool'>
print(type([1, 2, 3]))     # <class 'list'>
print(type((1, 2, 3)))     # <class 'tuple'>
print(type({1, 2, 3}))     # <class 'set'>
print(type({}))            # <class 'dict'>  - empty braces create a dictionary, not a set

Type Casting

Type casting converts a value from one type to another using int(), float() and str().

x = str("45")       # '45'  (string)
y = int(8)          # 8     (integer)
z = float(45)       # 45.0  (float)
print(x, y, z)

age = int("25")     # text from input() is always str - convert it before doing maths
print(age + 5)      # 30

Unpacking

The values of a list (or tuple) can be assigned to separate variables in one line. The number of variables must match the number of values.

student = [44, "Divyani", 787.8]
roll_no, name, marks = student
print(roll_no, name, marks)     # 44 Divyani 787.8

Operations on Variables

x2 = 56
y2 = 43
print(x2 + y2)      # 99
print(x2 - y2)      # 13
print(x2 * y2)      # 2408
print(x2 / y2)      # 1.302...  (always a float)
print(x2 // y2)     # 1         (floor division)
print(x2 % y2)      # 13        (remainder)
print(2 ** 5)       # 32        (power)

f-strings

An f-string puts variables directly inside text. Write f before the quotes and the variable inside { }.

name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hey, my name is {name} and I am {age} years old")

Docstrings

A docstring is the first string inside a function. It describes what the function does and can be read with __doc__.

def cube(n):
    """Takes in a number and prints its cube"""
    print(n * n * n)

cube(5)                 # 125
print(cube.__doc__)     # Takes in a number and prints its cube

if / else with a List of Records

A real example: give a 20% raise to employees with 5 or more years of experience.

employees = [
    ['Rajesh', 50000, 5],
    ['Sudhir', 90000, 7],
    ['Vishal', 40000, 1],
    ['Kusum', 30000, 3],
    ['Divyani', 10000, 4]
]

for emp in employees:
    name = emp[0]
    salary = emp[1]
    experience = emp[2]

    if experience >= 5:
        print(name, salary + (salary * 20 / 100))
    else:
        print(name, salary)

match-case (Python 3.10+)

match-case compares a value against several patterns, like switch in C# or Java. The underscore _ is the default case.

x = int(input("Value of x is: "))
match x:
    case 0:
        print("x is zero")
    case 10:
        print("x is ten")
    case _:
        print(x)