Byte by Byte › Book 6: Python, Data and How Computers Work › Chapter 6: Meet Python
Chapter 6: Meet Python
You will learn: what Python is and how to install it, how to use IDLE in interactive mode and script mode, how to output text with print, how to use comments and variables, Python's four basic data types, how to get input from the user and convert it, how to use f-strings, and how to read the four most common error messages.
🌟 The Adventure
The word carved beside the black stone was print .
"The Old Makers called their language Python," said Octavia. "Every instruction to the Speaking Stone was written in it. I learned a few words when I was young, but I have forgotten almost everything. When I touch the stone now, I only make it angry." She reached out an arm and tapped the stone. Red letters flashed across it: SyntaxError: invalid syntax . Octavia sighed.
Memoon looked at the blinking cursor. It was not like Scratch. There were no coloured blocks to drag, no categories to click. Just an empty space, waiting for words. For a moment it felt like standing at the edge of the deep end.
Then she remembered she was a very good swimmer.
She took a breath and typed exactly what was on her sticker.
💡 Learn With Memoon
What is Python? Python is a high-level, text-based programming language. It was created by a Dutch programmer, Guido van Rossum, and first released in 1991. It is named after a British comedy show, Monty Python's Flying Circus, not the snake. Python is designed to be easy to read: its instructions look a lot like simple English. That is why schools and universities all over the world teach it first. But it is not a toy. Python is used to build websites such as Instagram, to analyse data in science and medicine, to control robots, and above all to build artificial intelligence. Most AI you have ever used was built by people writing Python.
Python is free and open source: anyone can download it, use it and even look at how it was built.
Getting Python. Ask a grown-up to help with this.
- Open Microsoft Edge and go to python.org. Click Downloads and download the latest Python 3 installer for Windows.
- Run the installer. On the first screen, tick the box Add python.exe to PATH. Then click Install Now.
- When it finishes, click Start and type
IDLE. Open IDLE (Python 3).
(Python 3 is also available from the Microsoft Store: search for "Python 3" from the Python Software Foundation.)
IDLE: two modes. IDLE is a simple program for writing and running Python that comes with Python. The window that opens first is the Python Shell.
| Mode | What it is | Use it for |
|---|
Interactive mode You type one instruction after the >>> prompt, Quick tests and
| (the Shell) | press Enter, and Python runs it immediately | experiments |
| Script mode (an editor window) | You type a whole program in a file, save it, and run it all at once | Real programs you want to keep |
To use script mode: in IDLE click File → New File. Type your program. Click File → Save and give it a name ending in .py, for example hello.py . Then click Run → Run Module or press F5. The output appears in the Shell window. Python files are called scripts. Programmers usually say they run a program.
Your first program: print. The print() function shows output on the screen:
print("Hello, Deep Engine!")
Output:
Hello, Deep Engine!
Three important details. print is all small letters: Python is case-sensitive, so Print will not work. The brackets show what is being given to print. And the words are inside quotation marks, which tells Python they are text, not instructions. You can use double quotes "like this" or single quotes 'like this' , as long as both ends match.
A program can have many lines. Python runs them in order, from top to bottom. That is sequence, the first building block.
print("Welcome to Pearlhaven")
print("Population: 4,000 fish")
print()
print("Please swim carefully")
An empty print() prints a blank line. You can also print several things at once by separating them with commas; Python puts a space between them:
print("The tide gate is set to", 13)
Output: The tide gate is set to 13
Comments. Any line, or part of a line, that starts with # is a comment. Python ignores it completely. Comments are notes for people reading the code, including you next month.
# Tide Keeper program, written by Memoon
print("Tide Keeper starting") # this message appears first
Variables in Python. In Python you create a variable simply by giving it a value with = :
keeper = "Octavia" age = 212 water_level = 13.5
The = sign is called the assignment operator. It does not mean "equals" as in maths. Read age = 212 as "age gets 212" or "store 212 in age". The right side is worked out first, then stored in the variable on the left. That is why this is allowed:
score = 10 score = score + 5 print(score)
Output: 15 . The computer takes the current value of score (10), adds 5, and stores the answer back in score. It is exactly like change score by 5 in Scratch.
Rules for variable names.
| Rule | Allowed | Not allowed |
|---|
Use letters, digits and high_score , level2 high-score , high
| underscores only | score |
| Must not start with a digit | player1 | 1player |
Case matters Score and score are two different
variables
Must not be a Python keyword my_list if , for , while ,
True
In Book 5 you used camelCase, like highScore . Python allows it, but most Python programmers use snake_case instead: all small letters, with words joined by underscores, like high_score . This book uses snake_case, because that is the style professional Python programmers agree on.
Data types. Every value in Python has a data type, which tells Python what kind of data it is and what you can do with it.
| Data | Python |
|---|
| What it holds | Examples |
|---|
| type | name |
|---|
Integer int Whole numbers, positive or 13 , -4 , 0 , 2026
negative
Float float Numbers with a decimal point 13.5 , -0.25 , 3.0
String str Text, inside quotes "Memoon" , "13" , ""
(empty)
Boolean bool Only True or False True , False
The type() function tells you a value's type. Try this in the Shell:
>>> type(13)
<class 'int'>
>>> type(13.0)
<class 'float'>
>>> type("13")
<class 'str'>
>>> type(True)
<class 'bool'>
Notice that 13 and "13" are completely different. The first is a number you can do maths with. The second is a string of two characters, the 1 and the 3, just like the character codes in Chapter 4.
Doing things with types. Numbers can be added, subtracted, multiplied with * and divided with / . (Division always gives a float: 10 / 2 is 5.0 .) Strings can be joined with + , which is called concatenation, and repeated with * :
first = "Pearl"
second = "haven"
print(first + second) # Pearlhaven
print("Ho! " * 3) # Ho! Ho! Ho!
print(len("Memoon")) # 6, the number of characters
print("memoon".upper()) # MEMOON
len() gives the length of a string. .upper() and .lower() give a copy in capital or small letters.
Getting input. The input() function shows a message, waits for the user to type something and press Enter, and gives back what they typed:
name = input("What is your name? ")
print("Welcome to the Deep Engine,", name)
Notice the space after the question mark inside the quotes. Without it, the user's typing would be squashed against the question.
The most important fact about input. input() always gives back a string, even if the user types a number. So this goes wrong:
age = input("How old are you? ")
print(age + 1)
Python cannot add the number 1 to the string "12" , and it stops with an error. You have to convert the string to a number first. Converting one data type to another is called type casting.
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | Integer | int("12") | 12 |
float() | Float | float("13.5") | 13.5 |
str() | String | str(12) | "12" |
The usual way is to wrap input() inside int() :
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
f-strings: neat output. When you want to mix text and variables, an f-string is the clearest way. Put the letter f before the opening quote, and put variable names inside curly brackets { } :
name = "Memoon"
age = 12
print(f"{name} is {age} years old.")
print(f"In 10 years, {name} will be {age + 10}.")
Output:
Memoon is 12 years old. In 10 years, Memoon will be 22.
You can even put a calculation inside the curly brackets.
Errors are normal. Every programmer makes errors every day. Python tells you what went wrong and on which line. Learning to read error messages is one of the most useful skills you can have.
Example that
| Error | What it means | Fix |
|---|
causes it
| SyntaxError | You broke Python's grammar rules: a missing bracket, quote or colon | print("Hello) | Add the missing " |
| NameError | You used a name Python does not know, often a spelling mistake | print(scroe) | Spell it score |
| TypeError | You used the wrong type of data for an operation | "12" + 1 | Convert with int() |
| ValueError | The type is right but the value cannot be used | int("twelve") | Type digits, not words |
Syntax errors are found before the program runs, because Python checks the grammar first. The others are runtime errors: they happen while the program is running, when Python reaches the bad line.
💡 Memoon’s tip: When you see an error, read the last line first: it names the error. Then look at the line number just above it. The mistake is on that line, or very often the line just before it.

✍️ Try It Yourself
Type every program yourself. Save each one in a folder called Python Practice inside your Documents folder.
Activity 1: Shell experiments. In the IDLE Shell, type each of these and press Enter. Predict the answer before you press Enter.
>>> 7 + 5
>>> 7 * 5
>>> 7 / 2
>>> "7" + "5"
>>> "7" * 5
>>> type(7 / 2)
>>> len("Deep Engine")
Which answers surprised you? Write down why "7" + "5" gives '75' .
Activity 2: All about me. Click File → New File and type:
# All about me
name = "Memoon"
age = 12
favourite_food = "masala dosa"
print(f"My name is {name}.")
print(f"I am {age} years old.")
print(f"My favourite food is {favourite_food}.")
Save it as about_me.py and press F5. Change the values to describe yourself and run it again.
Activity 3: The greeter. Make a new file called greeter.py :
name = input("What is your name? ")
city = input("Which city do you live in? ")
age = int(input("How old are you? "))
print(f"Hello, {name} from {city}!")
print(f"You have been alive for about {age * 365} days.")
Run it. Then run it again and type twelve for your age. What error appears? Which line does it point to?
Activity 4: Rectangle calculator. Write a program called rectangle.py that asks for the length and the breadth of a rectangle in centimetres (they can have decimals, so use float() ), then prints the area and the perimeter with their units. Test it with length 5 and breadth 3: the area should be 15.0 and the perimeter 16.0.
Activity 5: Error hunt. This program has three errors. Type it exactly as shown, run it, and fix one error at a time. Write down the name of each error message.
print("Tide Keeper"
level = input("Enter the water level: ")
level = level + 2
print(f"New level: {levle}")
Unplugged: Type detective. Write each of these on a card: 42 , "42" , 4.2 , True , "True" , "" , -7 , 0.0 , "Memoon" . Sort the cards into four piles: int, float, str and bool. Check your piles with type() in the Shell.
🎉 Memoon Solves It
Memoon typed:
print("Hello, Deep Engine!")
She pressed the glowing key. The stone was silent for a moment. Then, in calm white letters, it wrote back: Hello, Deep Engine!
Octavia made a sound that was half laugh and half sob. "It has not spoken in thirty years," she whispered.
Memoon kept going. She stored the Keeper's name in a variable. She asked the Engine for input and converted it with int() . She printed the gate settings with f-strings. When Noodles strolled across the stone and typed jjjjjjj( , the Engine answered with a SyntaxError, and Memoon simply read the line number, deleted Noodles' contribution and ran it again. "Errors aren't the stone being angry," she told Octavia. "They're the stone telling you exactly where to look."
By the end of the day she had written a program that asked for the water level and printed it back with a message. But it could not yet decide anything. It printed the same thing whether the river was flooding or bone dry.
"The pseudocode had IFs," said Kachui, tapping her slate. "Your Python needs them too."
❓ Check Your Knowledge
- Who created Python, and what is it named after?
- What is the difference between interactive mode and script mode in IDLE?
- What will this print?
print("3" + "4")andprint(3 + 4) - Which of these are valid Python variable names?
total_marks,2nd_place,my name,_secret,for,Level3 - Name Python's four basic data types and give an example of each.
- What data type does
input()always give back? Why does this matter?
- Write one line of Python that asks the user for a number and stores it as an integer in a variable called
marks. - What does
score = score + 1do? - Rewrite using an f-string:
print("Hello", name, "you are", age) - Match each error to its cause: SyntaxError, NameError, TypeError, ValueError. Causes: (a)
int("abc"); (b) a misspelt variable; (c) a missing closing bracket; (d) adding a string to a number. - What is the output of
print(len("Python") * 2)? - Challenge: Write a program that asks for a temperature in degrees Celsius and prints it in degrees Fahrenheit, using the formula F = C × 9 ÷ 5 + 32. Test it with 0, 100 and 37.
📚 Word Bank
- Python: a high-level, free and open-source programming language that is easy to read.
- IDLE: the simple editor and Shell that comes with Python.
- Interactive mode: typing Python one line at a time in the Shell and seeing the result immediately.
- Script mode: writing a whole program in a .py file and running it.
- Script: a file containing a Python program.
- Function: a named instruction that does a job, such as print() or input().
- Case-sensitive: treating capital and small letters as different.
- Comment: a note in code, starting with #, that Python ignores.
- Assignment: storing a value in a variable using =.
- snake_case: the Python naming style that uses small letters joined by underscores.
- Data type: the kind of data a value is, such as int, float, str or bool.
- Integer (int): a whole number.
- Float: a number with a decimal point.
- Boolean (bool): a value that is either True or False.
- Concatenation: joining strings together with +.
- Type casting: converting a value from one data type to another, such as with int().
- f-string: a string starting with f that can include variables inside { }.
- Syntax error: a mistake in the grammar of the code, found before it runs.
- Runtime error: an error that happens while the program is running.
Keep learning with Byte by Byte
Explore Book 6: Python, Data and How Computers Work. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment