Almost every program does the same three things: it takes in data, works on it, and shows a result. In this lesson you learn the building blocks for the first two: variables to hold data, the main kinds of data (numbers and text), and input() to ask a person for data. We will use a small shopping example.
Variables
A variable is a name that points to a value. You create it with a single equals sign, which in Python means *store this value under this name*, and does not mean *is equal to*. Choose names that say what the value is. Python style uses lowercase words joined by underscores, such as unit_price. A name cannot start with a digit or contain spaces, and it cannot be a word Python already uses, such as if or for.
Numbers, text and types
Every value has a type. The ones you will meet first are int (whole numbers like 120), float (decimal numbers like 0.1) and str (text, short for string). The function type(value) tells you which one. Run this program and read the output line by line.
price = 120 # a whole number (int)
quantity = 3
discount = 0.1 # a decimal number (float)
subtotal = price * quantity
total = subtotal * (1 - discount)
print("Subtotal:", subtotal)
print(f"Total after discount: {total:.2f}")
print(f"Big number with commas: {1234567:,}")
name = " asha verma "
print(name.strip().title())
print(len(name.strip()))
print(type(price), type(discount), type(name))
# Text and numbers do not mix by themselves
age_text = "25"
age = int(age_text)
print(age + 1)
print(age_text + "1")
Subtotal: 360
Total after discount: 324.00
Big number with commas: 1,234,567
Asha Verma
10
<class 'int'> <class 'float'> <class 'str'>
26
251
- The operators are
+-*/for the usual four./always gives a float.//divides and drops the decimals,%gives the remainder and**is power. For example7 // 2is 3,7 % 2is 1, and2 ** 3is 8. - In an f-string,
{total:.2f}means: showtotalwith two decimals.{1234567:,}adds commas. Formatting like this is what makes output look professional. - Text has useful methods, which are functions that belong to the value, written with a dot:
.strip()removes spaces at both ends,.title()capitalises each word,.upper()and.lower()change the case.len(text)counts the characters. - Notice the last two lines of the output:
25plus 1 gives26, but the text"25"plus"1"gives251. With text,+joins pieces together. This is why the types matter.
Converting between types
Python will not guess. If you try "25" + 1, it stops with a TypeError. You convert on purpose with int(), float() and str(). int("25") gives the number 25. str(25) gives the text "25". If the text is not a number, such as int("abc"), Python raises a ValueError. Lesson 9 shows how to handle that safely.
Asking the user: input()
input("question") shows the question, waits for the user to type and press Enter, and gives you what they typed. The result is always text, even if the user typed a number, so convert it when you need a number.
name = input("Your name: ")
hours = int(input("Hours studied today: "))
print(f"Hi {name}, that is {hours * 60} minutes.")
Run it. The lines below are a real session. Your answers are what you type.
Your name: Asha
Hours studied today: 3
Hi Asha, that is 180 minutes.
The program turns the second answer into a whole number with int(...), and then multiplies it. If you forget the int, then hours * 60 would repeat the text 60 times, and you would see a very long line. This is one of the most common beginner surprises.
Rounding and money
Computers store decimal numbers in a way that cannot represent some values exactly. For example, 0.1 + 0.2 shows 0.30000000000000004. For display, round with an f-string such as {value:.2f} or with round(value, 2). For serious money calculations in a business program, many developers store whole amounts in the smallest unit, such as paise or cents, or use Python's decimal module. For learning, rounding for display is enough.
Common mistakes
- Using
=when you mean==. Use==to compare in lesson 3. - Forgetting quotes around text:
print(Hello)looks for a variable named Hello and fails with aNameError. - Mixing tabs and spaces at the start of a line.
- Forgetting that
input()gives text. - Using a name before you create it. Python runs from top to bottom.
Your task
- Create
shop.py. Ask for a product name, a price and a quantity. Print the name in title case and the total price with two decimals. - Add a 5 percent discount if you like, and show both the price before and after.
- Try typing text instead of a number when the program asks for the price. Read the error and write down what it says.
- Print
7 // 2,7 % 2and2 ** 3and check them.
How to check it worked
- For name
pen, price12.5and quantity4, the total shows50.00. - The product name is printed as
Pen. - You can explain why
"25" + "1"gives251.