๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 1 ยท Lesson 2 of 15

0% Exit to course

Module 1 ยท Your first program Lesson 2 of 15

Variables and data types

Learning objective

A variable is a labelled box. name = "Asha", age = 21, height = 5.4, is_student = True โ€” strings, integers, floats and booleans carry most of what a fresher ever writes.

The concept

A variable is a labelled box you put a value in. name = "Asha" stores text under the name name. The four types you will meet in the first month are string (text, in quotes), integer (whole number), float (number with a decimal point) and boolean (True or False). Nothing here is abstract: a resume parser, your marks sheet and an attendance register are all made of these four.

The subtlety that matters is that the quote marks change the type. age = 21 is a number you can do arithmetic on; age = "21" is text, and age + 1 on it fails. print(type(age)) tells you which one you have at any moment โ€” use it whenever a value misbehaves. Names should say what they hold: student_marks over m, is_placed over x.

Python
name = "Asha"
age = 21
height = 5.4
is_student = True

print(type(age))        # <class 'int'>
age_text = "21"
print(type(age_text))   # <class 'str'>

Common mistakes

The common mistake is naming a variable something vague and then forgetting what is in it three lines later, and the second is assuming a value taken from anywhere other than your own typing โ€” a file, a form, an API โ€” is a number. It is text until you convert it.

Worked example

name = "Asha"; age = 21; print(type(age)) prints <class 'int'>. Change it to age = "21" and the type becomes str โ€” that difference causes most beginner bugs.

Your practice task

Write five variables about yourself, print each one with its type, then deliberately break one and read the error message before fixing it.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

A variable is a labelled box you put a value in.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task โ€” do them and the final project brief writes itself.