Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 6: Chapter 6 – Meet Python

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.

  1. Open Microsoft Edge and go to python.org. Click Downloads and download the latest Python 3 installer for Windows.
  2. Run the installer. On the first screen, tick the box Add python.exe to PATH. Then click Install Now.
  3. 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.

ModeWhat it isUse it for

Interactive mode You type one instruction after the >>> prompt, Quick tests and

(the Shell)press Enter, and Python runs it immediatelyexperiments
Script mode (an editor window)You type a whole program in a file, save it, and run it all at onceReal 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.

RuleAllowedNot allowed

Use letters, digits and high_score , level2 high-score , high

underscores onlyscore
Must not start with a digitplayer11player

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.

DataPython
What it holdsExamples
typename

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.

FunctionConverts toExampleResult
int()Integerint("12")12
float()Floatfloat("13.5")13.5
str()Stringstr(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

ErrorWhat it meansFix

causes it

SyntaxErrorYou broke Python's grammar rules: a missing bracket, quote or colonprint("Hello)Add the missing "
NameErrorYou used a name Python does not know, often a spelling mistakeprint(scroe)Spell it score
TypeErrorYou used the wrong type of data for an operation"12" + 1Convert with int()
ValueErrorThe type is right but the value cannot be usedint("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.

Illustration from Byte by Byte Book 6: Chapter 6 – Meet Python

✍️ 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

  1. Who created Python, and what is it named after?
  2. What is the difference between interactive mode and script mode in IDLE?
  3. What will this print? print("3" + "4") and print(3 + 4)
  4. Which of these are valid Python variable names? total_marks , 2nd_place , my name , _secret , for , Level3
  5. Name Python's four basic data types and give an example of each.
  6. What data type does input() always give back? Why does this matter?
  1. Write one line of Python that asks the user for a number and stores it as an integer in a variable called marks .
  2. What does score = score + 1 do?
  3. Rewrite using an f-string: print("Hello", name, "you are", age)
  4. 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.
  5. What is the output of print(len("Python") * 2) ?
  6. 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.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...