Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 2 of 22 · 4 min read

Python variables, data types and input()

Python variables and data types notes: naming rules, int, float, str and bool, input(), type conversion with int() and float(), and swapping values.

What is a variable?

A variable is a name that stores a value, like a labelled box. You create one with =, which in Python means *store*, not *equals*.

name = "Asha"
marks = 87
print(name, marks)      # Asha 87

You can change what a variable holds at any time. The old value is replaced.

score = 10
score = score + 5       # take the old value, add 5, store it back
print(score)            # 15

Rules for naming variables

RuleAllowedNot allowed
Letters, digits and _ onlytotal_markstotal-marks, total marks
Cannot start with a digitclass1010class
Cannot be a keywordmy_classclass, if, for
Case mattersName and name are two different variables

Good names say what the value means: fee_per_month is better than x. Python programmers write variable names in lower case with underscores (this is called *snake_case*).

The four basic data types

TypeMeaningExamples
intwhole number16, -3, 2026
floatnumber with a decimal point3.14, 99.5, -0.5
strtext (string), always in quotes"Ranchi", 'A', "123"
booltruth valueTrue, False

Use type() to check:

print(type(16))        # <class 'int'>
print(type(16.0))      # <class 'float'>
print(type("16"))      # <class 'str'>
print(type(True))      # <class 'bool'>

Note that "16" in quotes is a string, not a number. "16" + "4" gives "164", not 20.

input(): let the user type a value

city = input("Which city do you live in? ")
print("You live in", city)

The program pauses, shows the message, and waits for the user to type and press Enter.

input() always gives a string

This is the most common beginner bug:

age = input("Your age: ")     # the user types 15
print(age + 1)                # TypeError: can only concatenate str (not "int") to str

Convert the text to a number first:

age = int(input("Your age: "))
print("Next year you will be", age + 1)

Converting between types

FunctionConverts toWorksFails
int()whole numberint("42"), int(9.8) gives 9int("9.8"), int("abc")
float()decimalfloat("9.8"), float(3) gives 3.0float("ten")
str()textstr(25) gives "25"(always works)

int(9.8) cuts off the decimal part; it does not round. Use round(9.8) to round.

Converting text that is not a number gives a ValueError. You will learn to handle that safely in the errors and exceptions topic.

Multiple assignment and swapping

x, y, z = 1, 2, 3           # three variables in one line
a = b = 0                    # both start at 0

p, q = 5, 9
p, q = q, p                  # swap: p is now 9, q is now 5

In most other languages swapping needs a third, temporary variable. In Python one line does it.

Example: a tea stall bill

tea = int(input("Cups of tea: "))
samosa = int(input("Samosas: "))
total = tea * 10 + samosa * 15
print("Total bill: Rs", total)

Common mistakes

  • Forgetting to convert input() before doing maths.
  • Putting a number in quotes by accident: marks = "90" is text.
  • Using a variable before giving it a value: NameError: name 'total' is not defined.
  • Spaces or hyphens in names: first name = "Riya" is a SyntaxError.

Key points

  • = stores a value in a variable; the newest value replaces the old one.
  • The four basic types are int, float, str and bool; type() shows which one you have.
  • input() always returns a string, so wrap it in int() or float() for numbers.
  • a, b = b, a swaps two values.

Practice questions

1. Which of these are valid variable names: 2nd_place, second_place, second-place, _temp?

second_place and _temp. A name cannot start with a digit or contain a hyphen.

2. What is printed by print("5" + "5") and by print(5 + 5)?

55 (two strings joined together) and 10 (two numbers added).

3. Write a program that asks for a temperature in Celsius and prints it in Fahrenheit.
c = float(input("Celsius: "))
f = c * 9 / 5 + 32
print("Fahrenheit:", f)
4. What is the value of int(7.9), and how is it different from round(7.9)?

int(7.9) is 7 because it cuts off the decimal part. round(7.9) is 8.

5. After a, b = 3, 8 and then a, b = b, a, what are a and b?

a is 8 and b is 3. The values have been swapped.