, ,

Variables, Numbers, and Text in Python (Python for Beginners, Part 3)

Python variables, numbers, strings, and the four core types explained plainly, with runnable code, the classic string-plus-number bug, and the expense tracker storing its first real data.

Python for Beginners · Part 3 of 20

Type these two lines into a file and run it:

types_demo.py
price = 19.99
print(price)
output
19.99

That first line made a variable. The name price now stands for the number 19.99, and your program can use that name anywhere it needs the value. Change the number, run the file again, and the output follows. Almost every program you will ever write rests on that one move: give a value a name, then work with the name.

Start hereA variable is a name that points at a value. Python sorts values into types: whole numbers, decimals, text, and true or false. You never write the type yourself; Python reads it from the value. The one rule that trips up nearly everyone is that text and numbers do not mix, so '10' + 5 is an error, not 15. Everything below is that idea, shown with code you can run.

This part is written for someone who has never stored a value in code before. If you can run a file the way Part 2 showed, you are ready for all of it. You need Python 3 and about twenty minutes, nothing else to install. Copy or retype each block and run it exactly as shown, and you should see the same output on your screen.

What a variable really is

The equals sign in Python does not mean 'is equal to' the way it does in maths. It means 'take the value on the right and attach this name to it'. Read price = 19.99 as: make the name price point at 19.99. Because it is just a name, you can point it somewhere else later.

price the name points at 19.99 the value

A variable is a label on a value, not a box you pour a number into.

You can repoint a name whenever you like. Watch the value change:

python
price = 19.99
price = 24.50
print(price)
output
24.50

The first value is simply forgotten. There are a few naming rules worth knowing now: a name can hold letters, digits, and underscores, it cannot start with a digit, and it cannot contain spaces. Most Python code uses lowercase words joined by underscores, such as total_spent, because it reads well and matches what you will see in real projects.

The four types you will meet first

Every value in Python has a type, and the type decides what you can do with the value. You can multiply two numbers, but multiplying two pieces of text makes no sense. Four types cover almost everything a beginner touches.

TypeWhat it holdsExample value
intWhole numbers, positive or negative3, 0, -12
floatNumbers with a decimal point19.99, 0.5, -3.0
strText, wrapped in quotes'Notebook', 'Groceries'
boolA yes or no answerTrue, False
int 42 float 19.99 str 'Notebook' bool True

The four types a beginner uses most, with one example value each.

You can ask Python the type of any value with type(). This is handy when a program behaves oddly and you want to check what you are really holding.

python
print(type('Notebook'))
print(type(3))
print(type(19.99))
output
<class 'str'>
<class 'int'>
<class 'float'>

The word class here just means type. So 'Notebook' is of type str, 3 is an int, and 19.99 is a float.

Whole numbers: int

Integers are counting numbers with no decimal point. They add, subtract, and multiply the way you expect. Division is the one surprise: dividing with a single slash always gives a float, even when the answer is whole.

python
print(6 + 4)
print(10 / 2)
output
10
5.0

That 5.0 is not a mistake. A single slash is float division, so its result carries a decimal point. If you want a whole number back, use two slashes for floor division: 10 // 2 gives 5.

Decimals: float

Floats hold numbers with a fractional part, like prices and averages. They have one quirk that looks like a bug the first time you meet it.

python
print(0.1 + 0.2)
output
0.30000000000000004

You did nothing wrong. Computers store decimals in binary, and a few fractions cannot be written exactly in binary, so tiny rounding errors creep in. For money and for display, round the result: round(0.1 + 0.2, 2) gives 0.3. Keep this in the back of your mind. It comes back the moment you total up real numbers.

GotchaNever compare two floats with == and expect an exact match. 0.1 + 0.2 == 0.3 is False because of that rounding. When you need to check whether two decimals are close, round both first, or compare the difference against a very small number.

Text: str

A string is text inside quotes. Single or double quotes both work in Python, as long as the pair matches. You can join strings with a plus sign and repeat them with a star.

python
first = 'Pra'
last = 'nay'
print(first + last)
print('ha' * 3)
output
Pranay
hahaha
Copy paste trapWhen you copy code off a web page, straight quotes can turn into curly ones, and Python does not accept curly quotes. If a line with a string refuses to run and reports a SyntaxError, delete the quotes and type them yourself with the key next to your Enter key. This bites almost every beginner once, and it is invisible until you know to look for it.

Yes or no: bool

A bool is either True or False, always capitalised. You rarely type them by hand. They fall out of comparisons, and you will lean on them in Part 5 when your program starts making decisions.

python
print(10 > 3)
print(5 == 4)
output
True
False

Turning one type into another

Types do not mix on their own, so you often convert a value from one type to another. Each type has a function named after it that does the job.

You haveYou wantUseResult
'42' (str)a whole numberint('42')42
'7.5' (str)a decimalfloat('7.5')7.5
59.97 (float)textstr(59.97)'59.97'
3.9 (float)a whole numberint(3.9)3

Notice the last row. Turning a float into an int does not round, it chops off everything after the decimal point, so int(3.9) is 3, not 4. If you want proper rounding, use round() instead.

Here is where the mixing rule bites. This looks reasonable and fails:

python
count = '10'
print(count + 5)
traceback
Traceback (most recent call last):
  File "prog.py", line 2, in <module>
    print(count + 5)
TypeError: can only concatenate str
(not "int") to str

A traceback looks alarming, but read the last line first, always. It says TypeError and then explains plainly: you tried to join a str and an int with a plus sign, and Python refuses to guess whether you meant to add numbers or stick text together. The value '10' is text because of the quotes. Convert it, and the code works:

python
count = '10'
print(int(count) + 5)
output
15

This is not a rare edge case. In Part 4 you will ask the user to type something, and whatever they type arrives as a string every single time. The int() and float() conversions you just saw are what turn that typed text into numbers you can add up.

'42' str int() 42 int

Text that looks like a number is still text until you convert it.

Project check-in: the tracker remembers somethingIn Part 2 your expenses.py file printed one title line. Now give it two variables to hold a single expense, an amount and a category, and print them under the title. Open the same file and make it read like this:
expenses.py
print('My Expense Tracker')
amount = 250.0
category = 'Groceries'
print(category, amount)
output
My Expense Tracker
Groceries 250.0
The amount is a float and the category is a str, the two types you just learned. Passing both to print with a comma puts a space between them. It still only knows one hard coded expense, but the tracker now holds data. In Part 4 the user gets to type that data in.
Why this matters in your first jobReal code spends most of its time moving values between types: a price arrives from a web form as text, a quantity comes from a database as a number, a total gets formatted back into text for a receipt. The bug where someone joins a string and a number by accident shows up in production systems constantly, and knowing to check types with type() is often how you find it in minutes instead of an afternoon. This is not beginner filler. It is the daily texture of the work.
A real opinionBeginners are often told to add type hints, the price: float style annotations, from day one. I disagree while you are still learning the basics. Type hints are useful in large codebases, but early on they add syntax to memorise and hide the more important lesson: Python figures out types from values, and you build a feel for that by watching real values flow. Learn what the types are first. Add hints later, when a project is big enough that you actually forget what a function returns.
Real interview questionA junior candidate is asked: your program reads two numbers a user typed and, instead of adding them, it prints them stuck together, so 10 and 5 becomes 105. What went wrong, and how do you fix it? The answer: input from a user is always a string, so the plus sign joined text rather than adding numbers. Wrap each value in int() before adding. It is a small question, but it tells the interviewer whether you understand the difference between text and numbers.
Try it yourselfMake three variables: a product name as text, a price as a float, and a quantity as a whole number. Work out the total cost, then print a line that reads exactly like the expected output below. Run it on Windows with python file.py or on macOS and Linux with python3 file.py.
expected output
3 Notebook at 19.99 each = 59.97
Show solution
solution.py
name = 'Notebook'
price = 19.99
qty = 3
total = price * qty
print(qty, name, 'at', price,
      'each =', round(total, 2))
output
3 Notebook at 19.99 each = 59.97

Build a one line receipt, step by step

Types click into place when you use them together on something small and real. Build a single receipt line that a shop till might print, one piece at a time, so you can see each type doing its job. Start with the raw facts as variables.

receipt.py
item = 'Coffee'
price = 3.5
qty = 4

Three variables, three types: a str, a float, and an int. Nothing prints yet. Next work out the total, which is a plain multiplication of the float by the int.

receipt.py
item = 'Coffee'
price = 3.5
qty = 4
total = price * qty
print(total)
output
14.0

The result is a float because one of the values was a float. Now try to build a readable line by joining the pieces with a plus sign, the way you joined strings earlier. This is the natural next step, and it fails on purpose.

receipt.py
print(item + ' costs ' + total)
traceback
Traceback (most recent call last):
  File "receipt.py", line 6, in <module>
    print(item + ' costs ' + total)
TypeError: can only concatenate str
(not "float") to str

Same lesson, new dress. The last line names the problem: you tried to join a str and a float. The value total is a number, and the plus sign will not glue a number onto text. Convert it with str() and the line comes together.

receipt.py
line = item + ' costs ' + str(total)
print(line)
output
Coffee costs 14.0

That works, and it is worth pausing on why. Every time text and a number meet, one of them has to change type. Here you pushed the number into text with str() so the whole line is one string. There is a cleaner way to stitch text and numbers together without all these conversions, and it arrives in Part 10. For now, the plus sign with str() shows you exactly what is happening under the hood, which is the better thing to understand first.

A few questions before Part 4

Do I have to say what type a variable is when I make it? No. Unlike some languages, Python reads the type from the value you assign. Write age = 25 and it is an int; write age = 25.0 and it is a float. You can even repoint the same name to a different type later, though that often signals a confusing design.

When do I use single quotes versus double quotes for text? They behave the same. Pick one and stay consistent. The one time it matters is when the text itself contains a quote: if your string has an apostrophe, wrap it in double quotes so the apostrophe does not end the string early.

Why did my division give 5.0 instead of 5? A single slash is always float division in Python 3, so it returns a float. Use two slashes, 10 // 2, for whole number division when you want a plain int back.

Is it bad that 0.1 + 0.2 is not exactly 0.3? It is not a Python flaw. Every language that uses standard floats behaves this way. For anything involving money or display, round the result to the number of decimal places you need.

What happens if I use a variable I never created? Python stops with a NameError telling you the name is not defined. Usually it is a typo in the name. Check the spelling against where you first assigned it.

You can now store values in named variables, tell Python's four everyday types apart, convert text to numbers and back, and read a TypeError instead of fearing it.

Part 4 opens the door to a real conversation with your program: you will ask the user a question, read what they type, and feed it into the tracker. Keep expenses.py exactly where it is. We build straight on top of it.

References

Python tutorial: an informal introduction, numbers and strings
Python docs: built-in types
Python docs: floating point arithmetic, issues and limitations

Python for Beginners · Part 3 of 20
« Previous: Part 2  |  Complete Guide  |  Next: Part 4

About The Author


Discover more from Journal of Intelligent Infrastructure – By Dr Pranay Jha

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Architect’s Toolkit

About the Author

Dr. Pranay Jha is a Cloud and AI Consultant with 18+ years of experience in hybrid cloud, virtualization, and enterprise infrastructure transformation. He specializes in VMware technologies, multi-cloud strategy, and Generative AI solutions. He holds a PhD in Computer Applications with research focused on Cloud and AI, has published multiple research papers, and has been a VMware vExpert since 2016 and a VMUG Community Leader.

Discover more from Journal of Intelligent Infrastructure - By Dr Pranay Jha

Subscribe now to keep reading and get access to the full archive.

Continue reading