Skip to content

← Grade 9 Computer

Concept of Programming

Unit 7 · CDC textbook pages 185–244

Hide the stories, facts, photos, activities and interactives, for revising before an exam
In this unit 16 sections
  1. 7.1 Introduction to programming languages
  2. Programming tools: algorithm and flowchart
  3. Coding, testing and debugging
  4. Compiler and interpreter
  5. Introduction to Python
  6. Input, output and string formatting
  7. Data types and variables
  8. Operators and expressions
  9. Conditional statements
  10. Iteration: for and while loops
  11. Python list
  12. Python dictionary
  13. Uses of library functions
  14. Practice tasks
  15. Project work
  16. Exercise

Ask a friend to make you a cup of tea and they will simply do it. Now ask a robot. It doesn’t know that water must boil before the tea leaves go in, that a cup must be under the strainer, or what to do when the milk has run out. Every step must be said, in the right order, with nothing left out and nothing left to guess. That is what giving instructions to a computer is like.

A computer is fast and never gets bored, but it can’t think for itself: it only follows instructions, exactly. In this unit you will learn to plan those instructions as an algorithm and draw them as a flowchart, see how a program written by a person is translated into the 0s and 1s a processor understands, and then write real programs in Python: programs that ask questions, do sums, make decisions, repeat jobs and keep lists. Every program here can be run on this page: press Run under it, and Edit to change it.

Just as people talk to each other in Nepali, Newari, Maithili, Bhojpuri, English or French, we talk to computers in programming languages. Everything a computer does is written in one: operating systems such as Windows and Linux, application software such as an office package, web browsers, games and apps.

A long cream-colored card printed with rows of the digits 0 to 9 and the words FORTRAN STATEMENT, with small rectangular holes punched in some of its columns; printed along the top edge is the line of code it holds, Z(1) = Y + W(1)
Figure 7.1 A punched card holding one line of a FORTRAN program, Z(1) = Y + W(1). The holes in each column stand for one character. Early programmers punched each line of a program on a card like this, and fed the stack of cards into the computer. Photo: Arnold Reinhold, CC BY-SA 2.5

7.1 Introduction to programming languages

A programming language is a language, with its own words and rules, in which we write instructions that tell a computer what to do and how to do it. Python, Java, C++, JavaScript and PHP are popular programming languages.

  • Programming is the process of writing those instructions, step by step, so that a computer does a particular job. The instructions together are a program, and the text of a program is its code.
  • A programmer is a person who writes programs.
  • Syntax is the set of rules for writing the instructions of a language correctly: which words to use, in what order, with which brackets, colons and quotes. Just as “rice eat I” breaks the grammar of English, print "Hello" breaks Python’s syntax: Python needs brackets, print("Hello"). A computer is far stricter than a reader: one wrong symbol, and the program won’t run.

Which is not a programming language?

Pick an answer to see why.

High-level and low-level languages

There are two main types of programming language, depending on how close they are to people or to the machine.

Low-level language High-level language
What it looks like machine code: 0s and 1s (or, in assembly language, short codes such as ADD) words and symbols close to English and maths: if marks >= 40: print("Pass")
Who understands it the processor, directly people; the processor needs it translated first
Easy to write and read? very hard; one mistake is hard to find much easier
Works on one kind of processor only any computer that has a translator for it
Examples machine language, assembly language Python, Java, C, C++, JavaScript

A program written in a high-level language is called source code: people can read it, but a processor can’t. Before it can run (be executed), it must be converted into low-level machine code. Programs called language translators do this: compilers, interpreters and assemblers, which you meet below.

A processor can carry out, directly, a program written in …

Pick an answer to see why.

Programming tools: algorithm and flowchart

Before a builder in Bhaktapur lays a single brick, someone draws the house on paper. Before writing a program, a programmer plans it too. Two tools help: an algorithm, the steps written in words, and a flowchart, the same steps drawn as a diagram. Both help you work out the logic of a solution before you worry about any language’s syntax, and a plan in either can be turned into a program in any language.

Algorithm

An algorithm is a set of step-by-step instructions for solving a particular problem or doing a particular task. It is like a recipe: a recipe lists the steps for making a dish, in order; an algorithm lists the steps a computer must follow.

  • It begins with Start and ends with Stop.
  • Its steps are numbered, in the order they are done, and each step is clear and does one thing.
  • It is written in simple, everyday language, not in any programming language.
  • It must end after a limited number of steps, and give the right result.

Here is an algorithm to find the area of a rectangle:

Step 1: StartStep 2: Read the length (l) and the breadth (b)Step 3: area = l × bStep 4: Display areaStep 5: Stop

Flowchart

A flowchart is a pictorial (graphical) representation of an algorithm. Each kind of step has its own shape, and flow lines (arrows) show which step comes next. A flowchart shows the whole logic at a glance: where the program decides between two ways, and where it goes back to repeat.

Shape Name Used for
Oval (rounded rectangle) Terminal Start and Stop: where the flowchart begins and ends
Parallelogram Input/Output reading a value from the user, or displaying a result
Rectangle Process a calculation or other step that does something: sum = a + b
Diamond Decision a question with two ways out, Yes and No (or True and False)
Arrow Flow line the direction of flow: which step comes next
Small circle Connector joins two parts of a flowchart, for example where it goes on to another page, instead of a long line
StartStart or stopwhere the algorithmbegins and endstotal = 0Processa step that does something:set or work out a valueINPUT marksInput or outputask for a value,or show onemarks ≥ 35?Decisiona question with twoways out: yes or noSORT listProcedurea job that has aflowchart of its ownAConnectorjoins two partswithout a long arrowFlow linewhich stepcomes next StartStart or stopwhere the algorithmbegins and endstotal = 0Processa step that does something:set or work out a valueINPUT marksInput or outputask for a value,or show onemarks ≥ 35?Decisiona question with twoways out: yes or noSORT listProcedurea job that has aflowchart of its ownAConnectorjoins two partswithout a long arrowFlow linewhich stepcomes next
Figure 7.2 The flowchart symbols, drawn as the international standard (ISO 5807) draws them. The double-sided rectangle, for a job that has a flowchart of its own, is used in bigger programs.

A few rules make a flowchart easy to follow: it has exactly one Start and at least one Stop; flow goes from top to bottom (or left to right); every shape except Stop has an arrow out; a decision has two arrows out, labeled Yes and No; and lines should not cross.

Which flowchart symbol would you use for the step “Display the total”?

Pick an answer to see why.

How many arrows leave a decision (diamond) box?

Pick an answer to see why.

Coding, testing and debugging

Once the plan is ready, a program is made in three steps, again and again until it works:

  1. Coding: writing the instructions in a programming language. The instructions are called code, and they tell the computer exactly what to do.
  2. Testing: running the program to check that it does what it should, with different inputs, including unusual ones (a zero, a negative number, a very big number, letters where a number is expected), to find any bugs (mistakes).
  3. Debugging: finding where a bug is in the code, understanding why it happens, and correcting it. Then test again.

These three steps make software that is reliable and runs smoothly. Programmers often spend more time testing and debugging than writing new code.

Bugs come in three kinds:

Kind of error What it is Example in Python
Syntax error the code breaks the language’s rules, so it can’t be translated at all print("Hello" (a bracket missing)
Runtime error the code is correct but something goes wrong while it runs, and it stops print(10 / 0): you can’t divide by zero
Logical error the program runs and finishes, but gives the wrong answer, because the plan or a formula is wrong average = a + b / 2 (it should be (a + b) / 2)

A logical error is the hardest to find, because nothing warns you: only testing with numbers whose answer you already know shows it up. Try the last one: the average of 4 and 8 should be 6.

a = 4b = 8average = a + b / 2print(average)

Output

8.0

Python divides before it adds, so this works out 4 + 8 ÷ 2 = 4 + 4 = 8. Press Edit, put brackets round a + b, and run it again.

A page of a handwritten logbook with times and notes; a dead moth is taped to the middle of the page, with the words First actual case of bug being found written below it
Figure 7.5 The page of the Mark II logbook with the moth taped to it, now in the Smithsonian’s National Museum of American History. Photo: Courtesy of the Naval Surface Warfare Center, Dahlgren, VA., 1988., Public domain

A program to work out the area of a circle runs without any error message, but gives the wrong answer. What kind of error is this?

Pick an answer to see why.

Compiler and interpreter

Imagine two friends: one speaks only Nepali, the other only Sanskrit. To chat, they need someone who knows both languages to translate. A programmer speaks Python or C; the processor speaks only machine code. Compilers and interpreters are the translators between them.

Compiler

A compiler is a translator program that converts the whole of a high-level program into machine code in one go, before any of it runs. If the program has errors, the compiler reports the errors it finds together, after reading the whole program, and no machine code is made. If there are none, it writes a separate file of machine code (on Windows, an .exe file), which then runs by itself, as many times as you like, with no more translating; it doesn’t even need the compiler or the source code any more.

Languages that are usually compiled include C, C++, C#, FORTRAN, COBOL and Go. Examples of compilers are the GNU Compiler Collection (GCC), which compiles C, C++ and FORTRAN, and Microsoft Visual C++, the compiler inside the Microsoft Visual Studio programming tool. (Java is compiled too, by javac, into a code of its own, which the Java Virtual Machine then runs.)

Interpreter

Imagine telling a friend how to cook a dish in a language they only partly know. You explain one step, they do it; you explain the next, they do that. An interpreter works the same way: it takes one line (instruction) of the program, translates it, runs it at once, and then moves on to the next line. It makes no separate machine-code file, so the program is translated again every time it runs.

This is slower than running a compiled program, but it is handy while writing and testing: you can change a line and run it again at once, and when the interpreter meets an error it stops right at that line and tells you, after the lines before it have already run. An interpreted program is also portable: the same program runs on any kind of computer that has the interpreter, without being compiled again for each kind of processor.

Languages that are usually interpreted include Python, JavaScript, Ruby, LISP and MATLAB. Their interpreters are programs too: the standard Python interpreter (called CPython) from python.org, and the JavaScript engine inside every web browser. QBASIC, which many Nepali schools used to teach, was an interpreted language; today Python and JavaScript are the most widely used ones.

Compilertranslate everything first, then runInterpretertranslate one line, run it, then the nextif errorsnext lineif a line is wrongThe wholeprogramCompilerMachine-code fileRuns onits ownor: a list ofits errorsThe program,line by lineInterpreter:translateRun thatlineError: stopsat that line
Figure 7.6 How a compiler and an interpreter get a program run. A compiler translates everything first, then the machine-code file runs; an interpreter goes round its loop once for every line.

Try it

Compile it, or interpret it?

The same five-line program goes to a compiler and to an interpreter. Line 4 has a mistake. Watch which lines run before the mistake is found; then fix it, and press Run twice with each translator.

A program in a simple high-level language

1 show "Namaste!"
2 set total to 5 + 3
3 show total
4 shw "Bye!"
5 show "Done"
Translator:
Line 4:

Output

     
Lines translated this run
0
Lines translated in all
0
Machine-code file
none

Choose a translator and press Run. Line 4 has a mistake: “shw” instead of “show”.

Both translate a high-level language (friendly to people) into a low-level one (the 0s and 1s a processor understands), so that a computer can carry out a program written by a person. They differ in how they do it:

Compiler Interpreter
translates the whole program at once, then it runs translates and runs the program line by line
shows the errors it finds together, after reading the whole program, and nothing runs until they are fixed stops at the first error it meets, while the program runs; the lines before it have already run
the compiled program runs faster, since translating is already done the program runs slower, since each line is translated every time it runs
makes a separate machine-code file (such as an .exe) makes no separate file of machine code
e.g. GCC for C and C++ e.g. the Python interpreter

Which translator stops at the first error it meets, after running the lines before it?

Pick an answer to see why.

Which of these is made by a compiler but not by an interpreter?

Pick an answer to see why.

Introduction to Python

Python is a high-level programming language created by Guido van Rossum and first released in 1991. It has become one of the most popular languages in the world because it is simple and can do so much: with Python you can solve maths problems, sort data, control robots and even make your own games. Its code reads almost like English, which makes it a good first language, and it comes with a large set of ready-made tools (libraries), so a programmer doesn’t have to start from scratch every time.

Python is used in web development, data science and data analysis, machine learning and artificial intelligence, automating everyday jobs (scripts), game development, collecting data from websites (web scraping) and cyber security. Instagram, Spotify and Netflix use it, and NASA’s scientists use it to study pictures from space.

Guido van Rossum, a man with glasses, short gray hair and a gray beard, in an orange T-shirt
Figure 7.7 Guido van Rossum, who created Python, in 2014. Photo: Daniel Stroud (retouched by Deedub1983 and HarJIT), CC BY-SA 4.0

Python’s code is easy to read partly because it uses indentation (spaces at the start of a line) instead of curly braces { } to group lines together. The lines that belong to a loop or an if are indented, usually by four spaces, and the indentation itself shows where the group (the block) begins and ends:

if marks >= 40:    print("Pass")          # indented: inside the if    print("Well done!")    # indented: inside the ifprint("Result checked")    # not indented: after the if, always runs

Many languages ask programmers to indent neatly; Python makes it a rule, so every Python program is laid out the same clear way.

Features of Python

  • Easy to read and write: its simple syntax, close to English, makes code easy to write and to understand later.
  • Versatile: one language for many jobs, from small scripts that automate a task to websites, data analysis and artificial intelligence.
  • Beginner-friendly: short programs do useful things, and its error messages point to the line that went wrong.
  • Extensive standard library: it comes with a large library of ready-made code (for maths, dates, files, random numbers and much more), so you don’t write everything from the ground up.
  • Rich ecosystem: beyond the standard library there are hundreds of thousands of free packages and frameworks (ready-made structures for building something bigger, such as a website), made by Python’s community.
  • Free and open source: anyone may download, use and share it, on Windows, macOS, Linux and even phones.
  • Interpreted: a program runs as soon as you write it, with no separate compiling step.

How does Python mark which lines belong to an if or a loop?

Pick an answer to see why.

Installing Python

You can write Python on a computer of your own, or with no installing at all, on this page or on an online Python site.

  1. Download the installer. Visit the official website, python.org/downloads. It detects your operating system and offers the right installer (for Windows, the 64-bit one on almost every computer today). Download the latest Python 3.
  2. Run the installer. Find the downloaded file (usually in your Downloads folder) and double-click it. On Windows, tick Add python.exe to PATH on the first screen, so that other programs can find Python.
  3. Install. Click Install Now (or choose your own settings under Customize installation). It takes a few minutes.
  4. Get an editor (IDE). Python comes with a simple one, IDLE. Many programmers use a bigger integrated development environment (IDE), a program for writing, running and debugging code in one window, such as Thonny (made for beginners) or Visual Studio Code.

In IDLE, the window with the >>> prompt is the Python shell: type one line, press Enter, and it runs at once. For a whole program, choose File → New File, type the program, save it with a name ending in .py, and press F5 (Run → Run Module). The output appears in the shell.

>>> 2 + 35>>> print("Namaste")Namaste

Comments in Python

A comment is a note that a programmer writes in the code to explain what it does, like a helpful hint for whoever reads it next (often yourself, months later). The Python interpreter ignores comments: they don’t change what the program does.

Single-line comments. A comment starts with the # sign and goes on to the end of the line. It can have a line to itself, or come after code on the same line. A longer note simply takes several lines, each starting with #. Programmers usually put one space after the #, which makes it easier to read.

# This is an example of a single-line comment.print("Nepal has great cultural diversity.")

Output

Nepal has great cultural diversity.
# This program prints what is special about Nepal.# Each line of a longer note starts with its own # sign.print("Nepal is famous for adventure tourism.")   # a comment after code

Output

Nepal is famous for adventure tourism.

Multi-line comments. For a long note, typing # on every line is tiresome. Python lets you put the note between three quotes, ''' (or """), at its beginning and end, and it may run over many lines:

'''This is an example of a multi-line comment.This program prints what is special about Nepal.'''print("Nepal is home to many ethnic groups, languages and traditions.")

Output

Nepal is home to many ethnic groups, languages and traditions.

Keywords

In programming, keywords are words that are reserved: the language has given each one a fixed meaning. if, else, for, while, True and import are keywords in Python. Because they already mean something, a keyword can’t be used as an identifier, the name of a variable or function: if = 5 is a syntax error.

Python 3 has 35 keywords. You will meet the ones in bold in this unit:

False None True and as
assert async await break class
continue def del elif else
except finally for from global
if import in is lambda
nonlocal not or pass raise
return try while with yield

Keywords are written in small letters, except True, False and None, and spelling matters: True is a keyword, but true is not. Python can list them for you:

import keywordprint(len(keyword.kwlist))print(keyword.kwlist)

Output

35['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

print, input and int are not keywords but the names of built-in functions; it is allowed, but a bad idea, to use them as variable names, since the function is then lost for the rest of the program.

What are keywords in Python?

Pick an answer to see why.

Input, output and string formatting

Input/output (I/O) statements let a program talk with its user: input gives the program data and instructions, and output shows the results on the screen. In Python, input() takes input and print() gives output. String formatting puts values neatly into the text a program prints.

The print() function

print() displays on the screen whatever you put inside its brackets: text in quotes, numbers, variables or calculations. Things separated by commas are printed with one space between them, and each print() ends by moving to a new line.

print("Hello, Python!")print("The answer is", 6 * 7)

Output

Hello, Python!The answer is 42

Two optional settings change this: sep sets what goes between the things, and end sets what comes at the end instead of a new line.

print("2082", "06", "15", sep="-")print("Kathmandu", end=" → ")print("Pokhara")

Output

2082-06-15Kathmandu → Pokhara

The input() function

input() shows a message (the prompt), waits for the user to type something and press Enter, and gives back what was typed. Store it in a variable to use it later:

name = input("What is your name? ")print("Namaste,", name)

Output

What is your name? TashiNamaste, Tashi

(Press Run, and the page asks you for your own answer.)

String formatting

String formatting is like filling in a form: you write a message with blanks, and Python fills each blank with a value, such as a name or a number. Python has three ways to do it.

1. Old-style formatting, with %. Python’s oldest way: %s is a blank for a string and %d for a whole number (%f for a decimal), and the values come after a % sign, in brackets, in order.

name = "Phulmaya"age = 15print("My name is %s and I am %d years old." % (name, age))

Output

My name is Phulmaya and I am 15 years old.

2. New-style formatting, with str.format(). Each blank is a pair of curly braces {}, and the values go in .format() after the string, in order. ({0}, {1}… pick a value by its position.)

name = "Abdul"age = 16print("My name is {} and I am {} years old.".format(name, age))

Output

My name is Abdul and I am 16 years old.

3. Formatted string literals (f-strings). The newest way, and the one most used today: put an f before the opening quote, and write the variables, or any expression, straight inside the curly braces.

name = "Lhamu"age = 14print(f"My name is {name} and I am {age} years old.")print(f"Next year I will be {age + 1}.")

Output

My name is Lhamu and I am 14 years old.Next year I will be 15.

f-strings are easiest to read, because each value sits where it will appear. Use them in your own programs.

What does this line print? print(f"{3} + {4} = {3 + 4}")

Pick an answer to see why.

Data types and variables

In your kitchen, rice goes in one jar, oil in a bottle and salt in a small tin: each kind of thing is kept in its own kind of container, because you use it differently. A program sorts its data the same way. A number can be added to another number; a name can’t be. The kind of a piece of data is its data type: data classified by its nature.

Data type What it holds Examples
Integer (int) a whole number: positive, negative or zero, as large as you like -3, 0, 42, 8848
Float (float) a number with a decimal point 3.14, -0.5, 1.567, 36.6
String (str) text: letters, digits, spaces and symbols, between quotes (double "…" or single '…') "hello", "Python@", "Mahendranagar1", '@#@#kathmandu'
Boolean (bool) only one of two values, True or False is_student = True, has_mobile = False

A few things to notice:

  • "42" in quotes is a string, not a number: Python treats it as two characters, 4 and 2.
  • True and False start with capital letters and have no quotes. A comparison such as 5 > 3 gives a Boolean: True.
  • type() tells you the type of any value:
print(type(42))print(type(3.14))print(type("Namaste"))print(type(True))

Output

<class 'int'><class 'float'><class 'str'><class 'bool'>

Identifiers

An identifier is a name a programmer gives to something in a program: a variable, a function, a class or another item. Identifiers aren’t built into the language; programmers make them up. But they must follow these rules:

  1. An identifier must start with a letter or the underscore character _.
  2. It can’t start with a digit (number).
  3. It may contain only letters, digits and underscores (A–Z, a–z, 0–9 and _): no spaces, and no other symbols such as -, @ or ..
  4. It is case-sensitive: age, Age and AGE are three different identifiers.
  5. It can’t be a Python keyword.
Valid identifiers Invalid identifiers, and why
A1 1A: starts with a digit
B34 34BA: starts with a digit
First_Name first-name: - is not allowed (Python reads it as a minus)
x_1 def: a keyword
_total my marks: a space is not allowed

int and print are not keywords, so Python will accept them as names, but they are names Python already uses for its own functions; using them hides those functions, so treat them as forbidden too. Good identifiers say what they hold: total_marks is better than tm or x.

Why is 3Number an invalid identifier?

Pick an answer to see why.

Variables

A variable is a named place in the computer’s memory that holds a value, like a labeled box: the label is the variable’s name, and what is inside is its value. Python has no command for declaring a variable: a variable is created the moment a value is assigned (given) to it with =.

a = 15print(a)a = 20          # the box now holds 20; 15 is goneprint(a)

Output

1520

The value can change while the program runs, which is why it is called a variable. A variable gets its type from the value put in it:

Variable Data type In Python
age integer: holds the whole number 15 age = 15
height float: holds the decimal number 5.7 (feet) height = 5.7
fname string: holds the text "Sanjog" fname = "Sanjog"
is_student Boolean: holds the value True is_student = True

city = "Birgunj". What is the data type of city?

Pick an answer to see why.

Type casting

Imagine a bakery in Butwal that takes cake orders through a website. Every order arrives as text: “3” cakes, “2.5” kilograms. To add up the orders and work out the bill, the program must turn that text into numbers. Changing a value from one data type into another is type casting (or type conversion). There are two kinds.

Implicit type casting (automatic type conversion): Python converts a value automatically, by itself, when an expression needs it. Add a whole number to a decimal number, and Python first turns the integer into a float, so no information is lost:

x = 10        # integery = 5.5       # floatz = x + y     # x is converted to the float 10.0 for the additionprint(z)print(type(z))

Output

15.5<class 'float'>

Explicit type casting: the programmer converts a value on purpose, with a function named after the type it should become:

  • int(x) converts x to an integer. From a float it drops the decimal part (it doesn’t round): int(4.9) is 4. From a string, the string must be a whole number: int("25") is 25, but int("2.5") and int("twenty") are errors.
  • float(x) converts x to a float: float(4) is 4.0, float("3.14") is 3.14.
  • str(x) converts x to a string: str(11) is "11".

A conversion makes a new value; it doesn’t change the variable unless you store the new value in it:

x = 4.5x = int(x)          # cast x to int, and store it back in xprint(x) y = 4y = float(y)        # cast y to floatprint(y) z = 11z = str(z)          # cast z to stringprint(z + "1")      # joining strings: "11" + "1"

Output

44.0111

The last line shows why the type matters: 11 + 1 would be 12, but "11" + "1" joins two strings into "111".

What is the result of float("3.14")?

Pick an answer to see why.

Operators and expressions

Operators are special symbols that do something with values: add them, compare them, combine conditions or store a result. They are the tools in a programmer’s toolbox. The values an operator works on are its operands. Python’s main kinds are arithmetic, relational (comparison), logical and assignment operators.

Arithmetic operators

Arithmetic operators do mathematics.

Operator Meaning Example Result
+ addition print(5 + 3) 8
- subtraction print(7 - 2) 5
* multiplication print(4 * 6) 24
/ division (always gives a float) print(10 / 2) 5.0
// floor division: divide and drop the decimal part print(17 // 5) 3
% modulus: the remainder after dividing print(17 % 5) 2
** exponent: the power print(3 ** 2) 9

% and // are more useful than they look: n % 2 is 0 exactly when n is even, n % 10 is the last digit of n, and n // 10 is n with its last digit removed. You will use all three in the practice programs.

Python works out ** first, then *, /, // and %, then + and -, as in maths; brackets come before everything.

print(17 / 5, 17 // 5, 17 % 5)print(2 ** 10)print(2 + 3 * 4, (2 + 3) * 4)

Output

3.4 3 2102414 20

Relational operators

Relational operators (comparison operators) compare two values and give a Boolean: True if the relationship holds, False if it doesn’t.

Operator Name Asks Example Result
== equal to are the two the same? 5 == 5 True
!= not equal to are they different? 3 != 5 True
> greater than is the left one bigger? 7 > 5 True
< less than is the left one smaller? 3 < 9 True
>= greater than or equal to bigger, or the same? 8 >= 8 True
<= less than or equal to smaller, or the same? 4 <= 6 True

Logical operators

Logical operators combine conditions, so a program can decide on more than one thing at once. Python has three: and, or and not.

  • and: the result is True only if both conditions are True. (5 < 2) and (5 > 3) is False, because 5 < 2 is False.
  • or: the result is True if at least one condition is True. (5 < 2) or (5 > 3) is True, because 5 > 3 is True.
  • not: gives the opposite of a condition. not (5 < 2) is True.

A truth table lists every combination; 1 stands for True and 0 for False.

A B A and B A or B
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
A not A
0 1
1 0

(In books, not A is also written Ā, with a bar over the A.)

print((5 < 2) and (5 > 3))print((5 < 2) or (5 > 3))print(not (5 < 2))age = 15print(age >= 13 and age <= 19)     # a teenager?

Output

FalseTrueTrueTrue

Try it

Fill in the truth table

Work out each empty cell from its row: 1 for True, 0 for False. Then press Check.

ABA AND BA OR BNOT A
00
01
10
11

Tap an empty cell to write 1; tap again for 0. Fill each column from the columns to its left, then press Check.

Assignment operators

Assignment operators store a value in a variable. = is the plain one; the others do a calculation with the variable’s own value and store the result back, a short way of writing it.

Operator Name Example Means
= assignment a = 7 put 7 in a
+= addition assignment a += 1 a = a + 1
-= subtraction assignment a -= 3 a = a - 3
*= multiplication assignment a *= 4 a = a * 4
/= division assignment a /= 3 a = a / 3
//= floor division assignment a //= 10 a = a // 10
%= remainder assignment a %= 10 a = a % 10
**= exponent assignment a **= 10 a = a ** 10

In a kitchen we put salt, sugar, spices and turmeric in different containers and label each one, so we know what is inside. The assignment operator = is the labeling machine: in my_age = 15 it puts 15 in the box named my_age, and whenever the program uses my_age it opens the box and finds 15.

a = 10      # assign 10 to ab = 5       # assign 5 to ba += b      # a = a + b, so a becomes 15print(a)

Output

15

Expressions and operands

An expression is a combination of values, variables and operators that Python works out to produce a value, like a formula. 5 + 3 is an expression (its value is 8); so is marks >= 40 (its value is True or False).

result = 5 + 3                     # a maths expression: 8greeting = "Namaste" + " Nepal"    # a text expression: joins two stringscombined = str(5 * 3) + " Python"  # 5 * 3 is 15; str() makes it text so it can joinprint(result)print(greeting)print(combined)

Output

8Namaste Nepal15 Python

A number and a string can’t be added directly: (5 * 3) + "Python" is an error (a TypeError), which is why the number is converted with str() first.

Formulas from maths are written in Python with its own operators:

Algebraic expression Python expression
A + B − C A + B - C
A × B ÷ C A * B / C
(a + b)(a − b) (a + b) * (a - b)
I = PTR ÷ 100 I = (P * T * R) / 100
a² + 2ab + b² a ** 2 + 2 * a * b + b ** 2

Notice that Python always needs the *: in maths, ab means a × b, but in Python ab is just a variable’s name.

Operands are the values or variables that an operator works on. In add = 5 + 3, the operator is + and the operands are 5 and 3.

In the Python statement x = a + 5 - b, what are a and b?

Pick an answer to see why.

Which of the following is an arithmetic operator?

Pick an answer to see why.

What is the value of 17 % 5 + 17 // 5?

Pick an answer to see why.

Conditional statements

Every morning you decide: if it is raining, take an umbrella; otherwise, don’t. A program decides the same way. A conditional statement is a decision-making statement: it checks a condition (something True or False) and chooses which code to run. Python has three forms: if, if-else and if-elif-else, and one if can sit inside another (a nested if).

The condition ends with a colon :, and the code to run when it is True is indented under it. Python’s indentation rule decides which lines belong to the if.

if statement

The if statement runs its block only when the condition is True; when it is False, the block is skipped and the program carries on after it.

if condition:    # statements run when the condition is True
StartRead numbernumber > 0 ?Display “Thenumber is positive.”StopYesNo
Figure 7.8 The if statement as a flowchart. When the condition is False, the flow goes round the block: nothing is displayed.
# Check whether a number is positivenumber = int(input("Enter a number: "))if number > 0:    print("The number is positive.")

Output

Enter a number: 25The number is positive.

Run it again with −4: the condition is False, line 4 is skipped, and the program prints nothing at all.

if-else statement

The if-else statement chooses between two blocks: the if block when the condition is True, the else block when it is False. Exactly one of them runs, every time. else has no condition of its own.

if condition:    # statements run when the condition is Trueelse:    # statements run when the condition is False
StartRead user_ageuser_age>= 18 ?Display “Youare an adult!”Display “You are ateenager or a kid.”StopYesNo
Figure 7.9 The if-else statement as a flowchart: two ways out of the decision, and exactly one of them is taken.
# Ask the user's age and give the resultuser_age = int(input("How old are you? "))if user_age >= 18:    print("You are an adult!")else:    print("You are a teenager or a kid.")

Output

How old are you? 14You are a teenager or a kid.

if-elif-else statement

For more than two choices, add elif (short for “else if”) branches between the if and the else. Python checks the conditions from the top, one by one, runs the block of the first one that is True, and skips all the rest. If none is True, the else block runs. There can be as many elifs as you need; the else is optional.

if condition1:    # run if condition1 is Trueelif condition2:    # run if condition1 is False and condition2 is Trueelse:    # run if condition1 and condition2 are both False
StartRead user_numberuser_number> 0 ?Display“positive”user_number== 0 ?Display“zero”Display“negative”StopYesYesNoNo
Figure 7.10 The if-elif-else statement as a flowchart: the second question is asked only when the answer to the first is No.
# Is the number positive, negative or zero?user_number = int(input("Enter a number: "))if user_number > 0:    print("The number is positive.")elif user_number == 0:    print("The number is zero.")else:    print("The number is negative.")

Output

Enter a number: 0The number is zero.

Nested if

A nested if is an if statement inside another if (or else) block. The inner condition is checked only when the outer one has let the program in. It is used to test several conditions one after another, and gives more possible outcomes.

if condition1:    # run if condition1 is True    if condition2:        # run if condition1 and condition2 are both True    else:        # run if condition1 is True but condition2 is Falseelse:    # run if condition1 is False

In Nepal you can get your citizenship certificate at 16 and vote at 18. The program checks age 16 first; only for someone 16 or over does it go on to ask about 18:

age = int(input("Enter your age: "))if age >= 16:    print("You are eligible for citizenship.")    if age >= 18:        print("You are eligible to cast a vote.")    else:        print("You are not eligible to cast a vote yet.")else:    print("You are a minor.")

Output

Enter your age: 17You are eligible for citizenship.You are not eligible to cast a vote yet.
StartRead ageage >= 16 ?Display “eligiblefor citizenship”age >= 18 ?Display“can vote”Display“can’t vote”Display“a minor”StopYesNoYesNo
Figure 7.11 The nested if as a flowchart, with the messages shortened. The second decision sits on the Yes path of the first, so it is reached only when age >= 16.

Try it

A flowchart that runs

Another program with if, elif, else and an if inside an if: it sorts a number into positive, negative or zero, and a positive one into even or odd. Pick the number the user types and follow its path.

TrueFalseTrueFalseTrueFalseStartInput nn > 0 ?Print “Positive”n % 2 == 0 ?Print “Even”Print “Odd”n < 0 ?Print “Negative”Print “Zero”Stop
The user types:

Output

PositiveOdd

7 > 0 is True, so the first branch runs: “Positive”. Then the inner if: 7 % 2 is 1, not 0, so “Odd”. The elif and else are never even checked.

Try it

Step through a nested if: leap years

A year is a leap year if 4 divides it, except a century year (one ending in 00), which must be divisible by 400. Choose a year, then step through to see which conditions Python checks.

year = int(input("Enter the year: "))if year % 100 == 0:    if year % 400 == 0:        print("Leap year")    else:        print("Not a leap year")else:    if year % 4 == 0:        print("Leap year")    else:        print("Not a leap year")
Step 1 / 4
The user types:

The user types 2024, and int() turns it into a number.

Variables

year
2024

Output

Enter the year: 2024 

x = 7. What does this print?

if x > 10:    print("A")elif x > 5:    print("B")elif x > 0:    print("C")else:    print("D")

Pick an answer to see why.

Iteration: for and while loops

Iteration means doing something again and again: repeating a set of instructions a given number of times, or until a condition is met. Without it, printing the numbers 1 to 100 would need 100 print lines; with a loop it needs two. Loops make programs shorter and save the programmer from writing the same code repeatedly. Python has two loops: the for loop and the while loop.

A watercolor portrait of Ada Lovelace, a young woman with dark hair and a yellow flower in it, in a pale purple dress with a black lace shawl, holding a closed fan
Figure 7.12 Ada Lovelace, painted by Alfred Edward Chalon in about 1840. Photo: Alfred Edward Chalon, Public domain

for loop

A for loop repeats a block once for each item in a sequence (it iterates over the sequence): each number in a range, each letter of a string, each item of a list. It is used when we know how many times to repeat. The for keyword names a variable that takes each item in turn:

for item in sequence:    # code that does something with each item
for x in range(5):    print("Jump!")

Output

Jump!Jump!Jump!Jump!Jump!
StartAnother numberin range(5)?x = that numberDisplay “Jump!”StopYesNo
Figure 7.13 The for loop as a flowchart. The arrow back up to the decision is the loop: it is followed once for each of the five numbers.

range() gives a sequence of whole numbers. By default it counts from 0 and goes up by 1, and it always stops before the number it is given:

You write It gives
range(5) 0, 1, 2, 3, 4
range(1, 6) 1, 2, 3, 4, 5 (start at 1, stop before 6)
range(2, 11, 2) 2, 4, 6, 8, 10 (the third number is the step)
range(10, 0, -1) 10, 9, 8, … 1 (a negative step counts down)

So range(5) gives five numbers, and the loop above runs five times. The variable x takes the values 0 to 4; this loop doesn’t use it, but it could: print(x).

A for loop can go over a string, one character at a time, too:

for letter in "Nepal":    print(letter)

Output

Nepal

How many times does print("Hi") run in for i in range(2, 8):?

Pick an answer to see why.

pass, continue and break

pass is a statement that does nothing. Python needs at least one statement in every block; pass holds the place where code is required but no action is wanted (or where you will write the code later).

marks = 75if marks >= 40:    print("Pass")else:    pass        # nothing happens in the else case, for now

Output

Pass

continue skips the rest of the loop’s body for this time round only, and goes straight on to the next item. The loop doesn’t end.

for number in range(1, 6):    if number == 3:        continue    # skip the rest of the loop for 3    print(number)

Output

1245

break ends the loop at once, even though items are left, and the program carries on after the loop.

for number in range(1, 6):    if number == 3:        break       # leave the loop when number is 3    print(number)

Output

12

Try it

Step through continue

Step through the continue program a line at a time. Watch what happens to the print line when number is 3.

for number in range(1, 6):    if number == 3:        continue    print(number)print("Done")
Step 1 / 17

range(1, 6) gives the next number: number is now 1. Into the loop’s body.

Variables

number
1

Output

     

while loop

A while loop repeats its block as long as its condition is True. Before each time round, it checks the condition; when the condition becomes False, the loop ends. It is used when we don’t know in advance how many times to repeat: until the user types the right password, until a number has no digits left.

while condition:    # code run again and again while the condition is True    # (it must change something, so the condition becomes False one day)
# Print the numbers from 1 to 5 with a while loopcount = 1while count <= 5:    print(count)    count += 1

Output

12345
Startcount = 1count <= 5 ?Display countcount += 1StopYesNo
Figure 7.14 The while loop as a flowchart: the condition is checked before each time round, and count += 1 brings it nearer to False.

Three things make a while loop work: the variable is set before the loop (count = 1), the condition checks it (count <= 5), and the body changes it (the increment count += 1). Leave out the last one and count stays 1 for ever: the condition is always True, and the loop never ends. This is an infinite loop (stop it with Ctrl + C, or the page’s Stop button).

for loop and while loop compared

for loop while loop
used when the number of repetitions is known (or there is a sequence to go through) used when the number of repetitions is not known in advance
repeats once for each item of a sequence (a range, a string, a list) repeats as long as a condition is True
the loop variable is set and moved on by the loop itself the variable must be set before the loop and changed inside it by the programmer
ends by itself when the sequence runs out can run for ever if the condition never becomes False
e.g. for i in range(1, 11): e.g. while password != "nepal123":

Which loop is used when the number of iterations is known beforehand?

Pick an answer to see why.

What is printed by this program?

n = 1while n < 20:    n = n * 3print(n)

Pick an answer to see why.

Python list

To store the marks of one student you need one variable; for forty students, forty variables would be silly. A list stores many values in a single variable. It is one of Python’s built-in data types. Its items (elements) are written inside square brackets [ ], separated by commas, and they can be of different types, heterogeneous: integers, strings, floats and Booleans in the same list.

thislist = ["Computer", "Science", 20, True]print(thislist)

Output

['Computer', 'Science', 20, True]

Lists support the operations that all of Python’s sequence types (lists, tuples, strings and ranges) share: indexing, finding the length, going through them with a for loop, and checking whether an item is in them. Strings, ranges and lists all behave alike in these ways.

Features of a list

List elements are indexed. Each element has a position number, its index, and the index always begins at 0: the first element is at index 0, the second at index 1, and so on. The index is how you reach an element: write it in square brackets after the list’s name. A negative index counts from the end: [-1] is the last element.

thislist = ["Computer", "Science", 20, True]print(thislist[0])print(thislist[2])print(thislist[-1])

Output

Computer20True

The output of thislist[2] is 20 because 20 is the element at index 2, the third element. Asking for an index the list doesn’t have, such as thislist[4] here, is an IndexError.

A list can have duplicate elements: the same value may appear more than once.

thislist = ["Computer", "Science", 20, True, "Computer"]print(thislist)

Output

['Computer', 'Science', 20, True, 'Computer']

A list is ordered. Its elements keep their places, and a new element added with the append() method always goes at the end. A method is a function that belongs to a value; it is joined to the list’s name with a dot, .

thislist = ["Computer", "Science", 20, True]thislist.append("Social")      # add a new element at the endprint(thislist)

Output

['Computer', 'Science', 20, True, 'Social']

A list is changeable (in Python’s word, mutable). Elements can be added, changed and removed after the list is made. To remove an element, write the keyword del before the list’s name with the element’s index:

thislist = ["Computer", "Science", 20, True, "Social"]del thislist[4]                # removes the element at index 4, "Social"thislist[2] = 25               # changes the element at index 2print(thislist)

Output

['Computer', 'Science', 25, True]

List length

The len() function gives the number of elements in a list:

thislist = ["Computer", "Science", 20, True]a = len(thislist)print(a)

Output

4

The last element’s index is always one less than the length: here 3.

Looping through a list

A for loop goes through a list’s elements one by one, in order:

thislist = ["Computer", "Science", 20, True]for x in thislist:    print(x)

Output

ComputerScience20True
thislist"Computer"0−4"Science"1−3202−2True3−1
Figure 7.15 A list as a row of numbered boxes. The first row of numbers under them are the indexes, which start at 0, so the fourth box is number 3; the second row counts from the end, −1 being the last.

subjects = ["Nepali", "English", "Maths", "Science"]. What is subjects[1]?

Pick an answer to see why.

Python dictionary

Picture a real dictionary: you look up a word and find its meaning. A Python dictionary works the same way, but instead of words and meanings it stores pairs of keys and values. You look up a key, and get the value that goes with it, quickly. A dictionary is a collection of data in key:value pairs, written inside curly braces { }, a colon between each key and its value, and commas between the pairs.

mydict = {    "student": "pen",    "teacher": "marker",    "tailor": "needle",    "marks": 30,    "is_present": True}print(mydict)

Output

{'student': 'pen', 'teacher': 'marker', 'tailor': 'needle', 'marks': 30, 'is_present': True}

Here the key "student" has the value "pen", "teacher" has "marker" and "tailor" has "needle". You can add as many key:value pairs as you like. The values can be of any data type (here strings, an integer and a Boolean); the keys are usually strings or numbers.

mydictkeyvalue"student""pen""teacher""marker""tailor""needle""marks"30"is_present"True
Figure 7.16 A dictionary as labeled boxes: you find a value by its key, the label, not by a position number.

Features of a dictionary

Duplicate keys are not allowed. Each key appears only once. If the same key is given two values, the newer value replaces the older one:

mydict = {    "student": "pen",    "teacher": "marker",    "tailor": "needle",    "marks": 30,    "is_present": True,    "teacher": "duster"}print(mydict)

Output

{'student': 'pen', 'teacher': 'duster', 'tailor': 'needle', 'marks': 30, 'is_present': True}

The older value of the key "teacher", "marker", has been replaced by "duster". (Values may repeat; only keys can’t.)

A dictionary is changeable (mutable): pairs can be added and removed after it is made. A new pair is added by writing the new key in square brackets and assigning its value:

mydict = {"student": "pen", "teacher": "marker", "tailor": "needle", "marks": 30, "is_present": True}mydict["mechanic"] = "tools"print(mydict)

Output

{'student': 'pen', 'teacher': 'marker', 'tailor': 'needle', 'marks': 30, 'is_present': True, 'mechanic': 'tools'}

(Assigning to a key that already exists changes its value instead: mydict["marks"] = 35.)

The keyword del removes a pair, named by its key:

mydict = {"student": "pen", "teacher": "marker", "tailor": "needle", "marks": 30, "is_present": True, "mechanic": "tools"}del mydict["mechanic"]print(mydict)

Output

{'student': 'pen', 'teacher': 'marker', 'tailor': 'needle', 'marks': 30, 'is_present': True}

Accessing a value

A value is found by its key, written in square brackets after the dictionary’s name:

mydict = {"student": "pen", "teacher": "marker", "tailor": "needle", "marks": 30, "is_present": True}a = mydict["teacher"]print(a)

Output

marker

Asking for a key that isn’t there, such as mydict["doctor"], is a KeyError. To check first, use in: "doctor" in mydict is False.

Dictionary length

len() gives the number of key:value pairs:

mydict = {"student": "pen", "teacher": "marker", "tailor": "needle", "marks": 30, "is_present": True}b = len(mydict)print(b)

Output

5

Looping through a dictionary

A for loop over a dictionary goes through its keys, one by one:

mydict = {"student": "pen", "teacher": "marker", "tailor": "needle", "marks": 30, "is_present": True}for x in mydict:    print(x)

Output

studentteachertailormarksis_present

To print the values too, use each key to look up its value: print(x, mydict[x]).

List and dictionary compared

List Dictionary
stores elements in a sequence, written in square brackets [ ] stores data in key:value pairs, written in curly braces { }
an element is reached by its index (position): marks[0] a value is reached by its key: marks["Nepali"]
elements have a position, and the same value may appear twice keys are unique; a value is found by its key, not by a position
elements are added with append() and removed by index with del pairs are added as d[key] = value and removed by key with del d[key]

prices = {"momo": 150, "chowmein": 120, "tea": 30}. What does print(prices["tea"]) show?

Pick an answer to see why.

Which statement about lists and dictionaries is true?

Pick an answer to see why.

Uses of library functions

A function is a named, ready-made group of instructions that does one particular job, such as a calculation or a check, and usually gives back a result. Python’s library functions (built-in functions, and those in its standard library’s modules) are written for you: you just call a function by its name, with the values it needs in brackets. Grouping a job that is done often into a function means it is written once and used many times. You have already used several: print(), input(), int(), len(), type().

String functions

Strings have many built-in methods (functions that belong to them, called with a dot) to work on text. Each gives back a new string; the original is unchanged.

center() returns the string padded on both sides, to the given width, so that it sits in the middle.

string.center(width, fillchar)
  • width: the length of the new string, padding included;
  • fillchar (optional): the padding character; a space if none is given.
string = "Python is awesome"new_string = string.center(24)print("[" + new_string + "]")print(string.center(24, "*"))

Output

[   Python is awesome    ]***Python is awesome****

The string has 17 characters, so 7 are added to make 24: 3 before and 4 after. (The square brackets are printed only to show the spaces.)

upper() returns a copy of the string with every letter in capitals (uppercase); lower() returns a copy with every letter small (lowercase). Characters that aren’t letters stay as they are.

text = "this is a string example....wow!!!"print(text.upper())shout = "THIS IS A STRING EXAMPLE....WOW!!!"print(shout.lower())

Output

THIS IS A STRING EXAMPLE....WOW!!!this is a string example....wow!!!

They are handy for comparing what a user types: answer.lower() == "yes" is True whether the user typed yes, Yes or YES.

len() returns the length of a string, the number of characters in it, spaces and symbols included:

text = "this is string example....wow!!!"print("Length of the string:", len(text))

Output

Length of the string: 32

Numeric functions

Some built-in functions work on numbers:

Function What it gives Example Result
sum() the total of the items in a list (or another sequence) sum([1, 2, 3, 4, 5]) 15
abs() the absolute value: the number without its minus sign abs(-10) 10
round() the number rounded to the given number of decimal places round(3.14159, 2) 3.14
max() the largest of the items, or of the values given max(1, 2, 3, 4, 5) 5
min() the smallest min(1, 2, 3, 4, 5) 1
total = sum([1, 2, 3, 4, 5])absolute = abs(-10)rounded = round(3.14159, 2)maximum = max(1, 2, 3, 4, 5)minimum = min(1, 2, 3, 4, 5)print("total is", total)print("absolute is", absolute)print("rounded is", rounded)print("maximum is", maximum, "and minimum is", minimum)

Output

total is 15absolute is 10rounded is 3.14maximum is 5 and minimum is 1

Mathematical functions

More maths functions are in Python’s math module, a part of its standard library. A module must be imported before its functions are used: write import math once, at the top, then call each function as math.name(). They work with integers and floats (not with complex numbers, which you will meet in higher classes).

Function What it gives Example Result
math.sqrt(x) the square root of x math.sqrt(16) 4.0
math.ceil(x) x rounded up to a whole number math.ceil(3.14) 4
math.floor(x) x rounded down to a whole number math.floor(3.14) 3
math.factorial(n) n! = 1 × 2 × … × n math.factorial(5) 120
math.pow(x, y) x to the power y, as a float math.pow(2, 3) 8.0
math.sin(x), math.cos(x), math.tan(x) the sine, cosine and tangent of an angle x in radians math.sin(math.pi / 2) 1.0
math.log(x) the natural logarithm of x (to the base e) math.log(10) 2.302585092994046
import mathprint("root is", math.sqrt(16))print("ceiling is", math.ceil(3.14), "and floor is", math.floor(3.14))print("factorial is", math.factorial(5))print("power is", math.pow(2, 3))print("sine is", math.sin(math.pi / 2))print("cosine is", math.cos(0))print("tangent is", math.tan(math.pi / 4))print("natural_log is", math.log(10))

Output

root is 4.0ceiling is 4 and floor is 3factorial is 120power is 8.0sine is 1.0cosine is 1.0tangent is 0.9999999999999999natural_log is 2.302585092994046

The tangent of 45° (π/4 radians) is exactly 1 in maths, but the computer prints 0.9999999999999999. A float holds only about 16 digits, so π itself is stored a tiny bit wrong, and the error shows in the last digit. round(math.tan(math.pi / 4), 10) gives 1.0.

What does math.ceil(7.01) give?

Pick an answer to see why.

Practice tasks

Each task below is a short program of the kind the exam asks you to write or to read. Try writing it yourself first, on paper or with Edit on any program on this page; then open the program, run it, and change the input to test it.

Input, output and operators

Decisions with if

Loops

Try it

Step through reversing a number

Tasks 27 and 28 take a number apart digit by digit with % 10 and //= 10. Choose what the user types, then step through the reversing program, and watch the three variables change each time round the loop.

number = int(input("Enter a number: "))reversed_number = 0while number > 0:    digit = number % 10    reversed_number = reversed_number * 10 + digit    number //= 10print("Reversed number:", reversed_number)
Step 1 / 16
The user types:

The user types 472.

Variables

numberdigitreversed_number
472––

Output

Enter a number: 472 

Exam practice

The final exam’s short and long questions on this unit read a program, dry-run it, or ask you to write one. Here is one of each kind, written like the exam’s.

Try it

Check your dry run

Step through the same program. Each step shows the line that just ran and every variable after it: your table, a row at a time.

n = 11d = 0p = 0while n != 0:    c = n % 2    d = d + c * 10 ** p    p += 1    n //= 2print(f"The final output is {d}")
Step 1 / 25

n starts at 11.

Variables

ncdp
11–––

Output

 

Project work

Exercise

1. Answer these questions

a.

Explain programming languages with their types.

Answer
b.

Differentiate between compiler and interpreter.

Answer
c.

Define algorithm and flowchart.

Answer
d.

Write five symbols used in a flowchart, with their functions.

Answer
e.

Create an algorithm to find whether a given number is odd or even. Also make a flowchart from the algorithm.

Answer
f.

Explain Python programming with its features.

Answer
g.

Describe the use of input/output statements in Python.

Answer
h.

Define formatted string literals. Demonstrate their use in a simple program where the user inputs their name and the output is displayed as “Hello (user_name)! Welcome to our program”.

Answer
i.

Explain the data types with examples.

Answer
j.

Describe typecasting with its types.

Answer
k.

List the types of operators. Explain any one of them in detail with examples.

Answer
l.

Explain a conditional statement with an example.

Answer
m.

Define iteration. Differentiate between the for loop and the while loop.

Answer
n.

Differentiate between list and dictionary.

Answer
o.

Here are the elements of a list:
[Kathmandu, Biratnagar, Nepalgunj, Pokhara, Butwal, Birendranagar, Mahendranagar, Balefi]

  • a.Add the list item Malangawa.
  • b.Remove the list item Balefi.
  • c.Print the list items one by one using a loop.
Answer

2. Write the technical terms

2.
  • a.A set of instructions to perform a specific task.
  • b.The set of rules for writing a program.
  • c.A language translator that reads and translates program code into machine code line by line.
  • d.The graphical or pictorial representation of a program’s steps.
  • e.Text added to source code to give information or an explanation, which the Python interpreter ignores.
  • f.A data type that has only the values True and False.
  • g.A special symbol used to check the relationship between two variables.
  • h.The values or entities that operators act on in programming.
  • i.A decision-making control structure that helps a program choose what to do.
  • j.The process of repeating a task until a specified condition is met.
Answer

3. Write true or false

Programming languages are used to give commands to the computer.

Pick an answer to see why.

Computers understand high-level programming languages easily.

Pick an answer to see why.

Compilers and interpreters translate program code into machine code.

Pick an answer to see why.

Algorithms are a graphical representation of instructions.

Pick an answer to see why.

Python is a machine-understandable programming language.

Pick an answer to see why.

The print statement is used to display output in Python.

Pick an answer to see why.

In Python, the data type “int” stands for alphabetical characters such as hello.

Pick an answer to see why.

Type casting is the conversion of one data type into another.

Pick an answer to see why.

With the AND operator, all the conditions must be True for the result to be True.

Pick an answer to see why.

In Python, an if statement runs its block of code when its condition is False.

Pick an answer to see why.

A for loop in Python repeats a process until a time given by the user.

Pick an answer to see why.

Dictionaries have key:value pairs.

Pick an answer to see why.

List items can’t be changed.

Pick an answer to see why.

In a dictionary, data is deleted by its value.

Pick an answer to see why.

4. Write the full forms

4.
  • i.LLL
  • ii.HLL
  • iii.I/O
  • iv.IDE
Answer

5. Choose the correct answer

In programming, what does the term “syntax” refer to?

Pick an answer to see why.

A computer understands …

Pick an answer to see why.

How does a flowchart represent a process in a program?

Pick an answer to see why.

How does an algorithm differ from a flowchart?

Pick an answer to see why.

Python is a … programming language.

Pick an answer to see why.

What are keywords in Python?

Pick an answer to see why.

The input function is used in Python to …

Pick an answer to see why.

Which data type in Python is suitable for text and characters?

Pick an answer to see why.

What is the result of the expression float("3.14")?

Pick an answer to see why.

What does the NOT operator do in Python?

Pick an answer to see why.

StartIs itraining?Bring anumbrellaNo need foran umbrellaStopYesNo
Figure 7.18 A decision drawn as a flowchart.

What does the flowchart above represent?

Pick an answer to see why.

How are elements accessed in a Python list?

Pick an answer to see why.

Which statement correctly describes the mutability of Python lists and dictionaries?

Pick an answer to see why.

What is the main purpose of a Python list?

Pick an answer to see why.

6. Practical questions

Input and output

a.

Write a program that asks the user for their name and greets them by name.

Answer
b.

Write a program that reads the three sides of a triangle and prints its area.

Answer
c.

Write a program that reads a radius and prints the area and the circumference of the circle.

Answer
d.

Write a program that reads three integers and prints their sum and average.

Answer
e.

Write a program that reads the diameter of a circle and prints its area and circumference.

Answer

Constant values and operators

a.

Write a program that reads a radius and finds the area and the circumference of the circle, keeping π as a constant.

Answer
b.

Write a program to show the use of arithmetic operators: add, subtract, multiply, divide, square and find the remainder (modulus) of two numbers.

Answer
c.

Write a program to show the use of comparison operators between two variables, with ==, <=, >= and !=.

Answer

if…else statements

a.

Write a program that uses an if statement to check whether a given number is positive.

Answer
b.

Write a program that takes a person’s age as input and checks whether they are eligible to vote. (The voting age is 18 and above.)

Answer
c.

Write a program to check whether a given number is even or odd, using an if-else statement.

Answer
d.

Write a program that reads two numbers and finds the smaller.

Answer
e.

Write a program that takes a student’s marks as input and says whether the student passed or failed. (40 or more is a pass.)

Answer
f.

Write a program that takes three numbers as input and displays the smallest.

Answer
g.

Make a program like a traffic light, using an if-elif-else statement. Ask the user for a color: green means “Go”, red means “Stop”, orange means “Be ready”, and any other color is “Invalid color”.

Answer
h.

Write a program that reads the practical and the theory marks of Computer and says whether the student passed or failed. Also check that the user has entered valid marks, for both theory and practical.

Answer

for loops

a.

Write a program to print the numbers from 1 to 15.

Answer
b.

Write a program that reads a name and prints it 20 times.

Answer
c.

Write a program to print the squares of the numbers from 1 to 5 using a for loop.

Answer
d.

Write a program to print the first 20 odd numbers.

Answer
e.

Write a program that takes an integer as input and prints its multiplication table.

Answer

while loops

a.

Write a program to print the numbers from 1 to 20 using a while loop.

Answer
b.

Write a program to print the first 30 even numbers using a while loop.

Answer
c.

Write a program to calculate the factorial of a given number using a while loop.

Answer
d.

Write a program to print the sum of the first 20 odd numbers using a while loop.

Answer
e.

Write a program that reads a number with several digits and displays the sum of its digits.

Answer

Lists

1.

Write a Python program to create a list of 5 integers and print the list.

Answer
2.

Write a Python program to print the second and fourth elements of a list.

Answer
3.

Write a Python program to append a new element to the end of a list and print the updated list.

Answer
4.

Write a Python program to print the first three elements of a list using slicing.

Answer
5.

Write a Python program to print the length of a list.

Answer
6.

Write a Python program to go through a list and print each element.

Answer
7.

Write a Python program to create a list of the squares of the numbers from 1 to 10 using a list comprehension.

Answer
8.

Write a Python program to remove the third element from a list and print the updated list.

Answer

Dictionaries

1.

Write a Python program to create a dictionary with 3 key:value pairs and print it.

Answer
2.

Write a Python program to print the value of a particular key in a dictionary.

Answer
3.

Write a Python program to add a new key:value pair to a dictionary and print the updated dictionary.

Answer
4.

Write a Python program to remove a key:value pair from a dictionary using the del statement and print the updated dictionary.

Answer
5.

Write a Python program to go through a dictionary and print all its keys.

Answer
6.

Write a Python program to create a dictionary whose keys are the numbers 1 to 5 and whose values are their squares, using a dictionary comprehension.

Answer
7.

Write a Python program to check whether a particular key exists in a dictionary.

Answer
8.

Write a Python program to merge two dictionaries and print the result.

Answer

A companion to your textbook, not a replacement for it: study from the book your school uses, and where the two differ, follow your teacher. Found a mistake? Please tell us.