Variables, numbers and text
Whole numbers, decimal numbers and text are different kinds of values. Learn to use each one, convert between them, and print them neatly with f-strings.
In 60 seconds
Variables, numbers and text
Whole numbers, decimal numbers and text are different kinds of values. Learn to use each one, convert between them, and print them neatly with f-strings.
| Type | Name in Python | Examples | Good for |
|---|---|---|---|
| Whole number | int | 7, 250, -3 | Counting: runs, students, items |
| Decimal number | float | 7.5, 99.9, 0.25 | Measuring: weight, run rate, percentage |
| Text | str (string) | "Priya", "Chennai", "42" | Names, messages, labels |
type().runs = 45
average = 38.5
player = "Smriti"
print(type(runs))
print(type(average))
print(type(player))Numbers
int and float values. A few extra operators are handy:balls = 23
print(balls // 6, "overs and", balls % 6, "balls") # // whole part, % remainder
print(2 ** 3) # ** means "to the power of"
print(round(187 / 20, 2)) # round to 2 decimal places23 // 6 is 3 (three full overs) and 23 % 6 is 5 (five balls left over). So 23 balls is 3 overs and 5 balls.Text
'…' or double "…". You can join strings with +, and strings have useful tools called methods, which you use with a dot.city = "mumbai"
print(city.upper()) # MUMBAI
print(city.title()) # Mumbai
print(len(city)) # 6 letters
print("Hello " + "Mumbai") # joining two stringsf-strings: the neat way to mix text and numbers
f just before the opening quote. Then anything inside curly brackets { } is replaced by its value. This is called an f-string.name = "Arjun"
marks = 87
print(f"{name} scored {marks} marks.")
print(f"Run rate: {187 / 20:.2f}") # :.2f shows 2 decimal placesConverting between types
"12" read from a scoreboard or a file. You cannot do maths with it until you convert it.| You have | You want | Use | Result |
|---|---|---|---|
"12" (text) | a whole number | int("12") | 12 |
"7.5" (text) | a decimal number | float("7.5") | 7.5 |
36 (number) | text | str(36) | "36" |
"12" + "8"gives"128": two pieces of text stuck together"12" + 8gives an error: text and number cannot be added
int("12") + 8gives20f"Score: {12 + 8}"givesScore: 20
Why there is no typing-in here
input(), which waits for you to type something. The browser runner used in this course cannot wait for typing, so input() is not available here. Instead, we set the values in the code. To try different values, just change the numbers and press Run again. Programs that read their data from a variable or a file are very common in real work too.Good variable names
- Use lower-case words joined by underscores:
total_runs,price_each. - Choose names that say what is inside:
marksis better thanx. - Names cannot start with a digit:
2nd_scoreis not allowed;score_2is fine. - Upper and lower case are different names:
Totalandtotalare two separate variables.
Watch and read more
Lab
A cricket scoreboard summary that Python calculates and prints neatly.
The problem
A team scored some runs from the bat, and the extras were written on the scoreboard as text. Finish the starter:
- Make
total_runs: the bat runs plus the extras. The extras are text, so convert them withint()first. - Make
run_rate: total runs divided by overs. It will be a decimal number. - Make
summaryan f-string that includes the team name and the total runs, for exampleChennai Stars scored 187 runs. - Print the summary and the run rate rounded to 2 decimal places. Press Run.
Then press Check. Try changing the numbers afterwards: your code should still work.
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1If you wrote <code>total_runs = str(bat_runs) + extras_text</code>, what would you get, and why?Reveal
You would get the text "17512". Both parts are strings, and + joins strings end to end instead of adding them. To add, both sides must be numbers: bat_runs + int(extras_text).
Q2Why is <code>run_rate</code> a float even though both 187 and 20 are whole numbers?Reveal
In Python 3, / always gives a float, because division often has a decimal part (187 / 20 = 9.35). If you only wanted the whole number part, you would use //, which gives 9.
Questions people ask
Why does 0.1 + 0.2 print 0.30000000000000004?
Computers store decimal numbers in binary, and some decimals, like 0.1, cannot be stored exactly. The tiny difference shows up sometimes. It is normal in almost every programming language. Use round() when you print, and for money you can work in whole paise to stay exact.
Should I use single or double quotes?
Either works, as long as the start and end match. Double quotes are handy when your text has an apostrophe inside: "Ravi's bat".
What happens if I use a variable before creating it?
Python stops with a NameError, which means "I don't know this name". Make sure the line that creates the variable comes first, and check the spelling. Lesson 7 is all about errors like this.
Can a variable change its value?
Yes. score = 10 and later score = score + 4 makes it 14. The name now points to the new value. That is why they are called variables.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.