Python Basics: Your First Programs
Working with Numbers and Text
In this lesson you will
- Use arithmetic operators including //, % and **
- Use common string methods and slicing
- Build text with f-strings
Introduction
Almost every program works with numbers and text. Python gives you a rich toolbox for both. In this lesson you will calculate, and then you will slice and reshape words.
Arithmetic
/always returns a float, even for10 / 2, which gives5.0.//divides and rounds down.%gives what is left over, useful to test whether a number is even:n % 2 == 0.- Brackets work as in maths, and multiplication comes before addition:
2 + 3 * 4is 14.
Round and convert
Converting with int() or float() is how you turn typed text into something you can do maths with.
Floating point numbers can surprise you, because computers store decimals in binary:
This happens in every programming language. Use round() when you display results.
Quick quiz
What does 7 // 2 give?
Strings
Write text in single or double quotes. Triple quotes allow several lines.
Indexing and slicing
Each character has a position (an index), starting from 0. Negative numbers count from the end.
In [start:stop], the stop position is not included. This takes practice, so experiment with different numbers.
Strings cannot be changed in place. word[0] = "J" is an error. Instead you build a new string, such as "J" + word[1:].
String methods
Strings come with built-in tools called methods, called with a dot.
Methods do not change the original string. They return a new one.
Quick quiz
What does 'Python'[1:4] give?
f-strings: the easy way to mix text and values
Put an f before the quotes and write values in curly brackets.
Anything inside {} is evaluated, so you can do small calculations. After a colon you can say how to format the value. f-strings are the modern, readable way to build messages, and you should prefer them to joining strings with +.
Try it yourself
A shop sells pens at 1.25 each. Calculate the cost of 12 pens, add 20 percent tax, and print a message such as Total for 12 pens: 18.00. Use an f-string with 2 decimal places.
Summary
- Arithmetic:
+ - * /, plus//(floor division),%(remainder) and**(power). int(),float()andround()convert and round values. Floats can have tiny errors.- Strings are indexed from 0. Slices like
word[1:4]stop before the end index. - Methods such as
.upper()and.split()return new strings. f-strings (f"{x:.2f}") mix text and values.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading