Python for Beginners: Learn to Code from Zero · Lesson 2 of 10

Lesson 2: Variables and Data Types

Store information in variables and learn the four basic types: whole numbers, decimals, text and True/False.

Lesson 2: Variables and Data Types

A variable is a name for a piece of information, like a labelled box. You create one with =, which means "store this value under that name".

name = "Sita"
age = 16
print(name)
print(age)

Output:

Sita
16

The four basic types

TypePython nameExampleUsed for
Whole numberint25, -3counting, ages, marks
Decimal numberfloat3.14, 72.5prices, measurements
Textstr"Kathmandu"names, messages
True or FalseboolTrue, Falseyes/no decisions

Use type() to ask Python what kind of value something is:

print(type(25))
print(type(72.5))
print(type("Pokhara"))
print(type(True))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

Naming variables

  • Use letters, digits and underscores, and do not start with a digit.
  • Names are case sensitive: marks and Marks are different.
  • Choose meaningful names: total_marks is better than x.

Joining text with f-strings

To put variables inside a sentence, start the text with f and put the variable in curly brackets.

name = "Ram"
marks = 78.5
print(f"{name} scored {marks} marks")

Output:

Ram scored 78.5 marks

Getting input from the user

input() asks the user to type something. It always gives you text, so convert it with int() or float() if you need a number. This example waits for a keyboard, so try it on your own computer:

name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello {name}, next year you will be {age + 1}")

Try it yourself

  1. Make variables for your name, your age and your favourite subject, then print one sentence using an f-string.
  2. Print the type of each variable.
  3. Ask the user for two numbers and print them side by side.

Next lesson: doing arithmetic and comparing values with operators.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 2: Variables and Data Types | MeroSir