Python from zeroBeginnerLesson 1007 min read

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.

Lesson in motion

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.

1/4
In simple words
In a kitchen you keep rice in one jar, oil in a bottle and salt in a small box. Each container suits what is inside. Python also has different kinds of values: whole numbers, decimal numbers and text. Knowing which kind you have tells you what you can do with it.
Every value in Python has a type. Here are the three you will use most:
TypeName in PythonExamplesGood for
Whole numberint7, 250, -3Counting: runs, students, items
Decimal numberfloat7.5, 99.9, 0.25Measuring: weight, run rate, percentage
Textstr (string)"Priya", "Chennai", "42"Names, messages, labels
You can ask Python which type a value is with type().
Python: checking typespython
runs = 45
average = 38.5
player = "Smriti"
print(type(runs))
print(type(average))
print(type(player))

Numbers

You can do maths with int and float values. A few extra operators are handy:
Python: more mathspython
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 places
23 // 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

Text (a string) goes inside quote marks, single '…' or double "…". You can join strings with +, and strings have useful tools called methods, which you use with a dot.
Python: playing with textpython
city = "mumbai"
print(city.upper())         # MUMBAI
print(city.title())         # Mumbai
print(len(city))            # 6 letters
print("Hello " + "Mumbai")  # joining two strings

f-strings: the neat way to mix text and numbers

Put the letter f just before the opening quote. Then anything inside curly brackets { } is replaced by its value. This is called an f-string.
Python: f-stringspython
name = "Arjun"
marks = 87
print(f"{name} scored {marks} marks.")
print(f"Run rate: {187 / 20:.2f}")   # :.2f shows 2 decimal places

Converting between types

Sometimes a number arrives as text, for example "12" read from a scoreboard or a file. You cannot do maths with it until you convert it.
You haveYou wantUseResult
"12" (text)a whole numberint("12")12
"7.5" (text)a decimal numberfloat("7.5")7.5
36 (number)textstr(36)"36"
Surprise
  • "12" + "8" gives "128": two pieces of text stuck together
  • "12" + 8 gives an error: text and number cannot be added
What you meant
  • int("12") + 8 gives 20
  • f"Score: {12 + 8}" gives Score: 20

Why there is no typing-in here

On your own computer, Python has 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: marks is better than x.
  • Names cannot start with a digit: 2nd_score is not allowed; score_2 is fine.
  • Upper and lower case are different names: Total and total are two separate variables.
Try this. Make a variable for your age. Use an f-string to print "In 5 years I will be …" with the right number. Well done if it worked first time, and well done if you fixed it!

Watch and read more

Lab

A cricket scoreboard summary that Python calculates and prints neatly.

~10 min

The problem

A team scored some runs from the bat, and the extras were written on the scoreboard as text. Finish the starter:

  1. Make total_runs: the bat runs plus the extras. The extras are text, so convert them with int() first.
  2. Make run_rate: total runs divided by overs. It will be a decimal number.
  3. Make summary an f-string that includes the team name and the total runs, for example Chennai Stars scored 187 runs.
  4. 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.

Output

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.

Please sign in to continue.

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.

Sign in to take the test and save your progress