Chapter 21 Appendix
Please use Python sandbox to learn Python along with this tutorial.
21.1 Printing on the Screen
Keyword | Action |
---|---|
prints text on screen |
In this first exercise, we use the Python keyword ‘print’ to print a message on the screen.
Type the following code in the Python sandbox and press ‘Run.’
print( "Welcome to the class" )
You will see ‘Welcome to the class’ being printed on the output screen at the bottom.
Next, try a multi-line Python program.
print( "Welcome" )
print( "to the class" )
print( "today" )
You will see the texts ‘Welcome,’ ‘to the class’ and ‘today’ being printed in three separate lines. That is because, by default, Python’s ‘print’ command prints its output in a separate line.
It is possible to change that default option as we will see in the next example.
We should also mention here that, in general, a multi-line Python program starts from the top and runs instruction in each line serially until reaching the bottom. It is also possible to change that default flow by using special Python keywords as we will learn in later sections.
21.1.1 Commas in ‘print’ Statements
If you add a comma at the end of a ‘print’ statement, the output of the following ‘print’ statement is displayed in the same line. Here is an example.
print( "Welcome", )
print( "to the class" )
print( "today" )
You will see that ‘Welcome to the class’ is printed in one line and ‘today’ in the following line. If another comma is added at the end of the second line, the entire text ‘Welcome to the class today’ will be printed together.
Try -
print( "Welcome", "to the class", "today" )
When you use commas within the same ‘print’ statement, the entire text will be printed in the same line. Therefore, the output of the above code is identical to the first code at the top of this tutorial. This may seem like doing something simple in a convoluted way. The usefulness of using commas withing the same print statement will be apparent in the fourth section, where we discuss variables.
21.1.2 Summary of rules
The ‘print’ keyword is used to print information on the screen.
By default, each new ‘print’ statement prints its output in a different line. This behavior can be changed by adding a comma at the end of the statement.
21.3 Mathematical Operations
Python can be used as a calculator to do simple mathematical operations. Try -
print( 7+3*4 )
print( (4-3)*(22+7) )
print( 55%3 )
print( 2**8 )
The mathematical operators ‘+,’‘-,’ ’*‘,’/’ perform addition, subtraction, multiplication and division respectively. Additional operators ’**’ is used for power and ‘%’ is used for remainer in a division.
Operator | Action |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder |
** | Power |
For more sophisticated mathematical operations, Python contains a separate math library with many useful functions. They are described in a later section.
21.4 Numbers and Boolean Variables
Keyword | Action |
---|---|
and | logical ‘and’ |
or | logical ‘or’ |
not | logical ‘not’ |
Let us say you are calculating the tips for a bunch of restaurant bills, and do not like to type the number 0.15 again and again. Python’s variables allow you to save the number for future use. Code here -
tip = 0.15
print( 77*tip )
print( 32.09*tip )
print( 14*tip )
print( 7.99*tip )
You can change the values of the variables any time in your code. For example, if you want the tip to be 15% for some bills and 12% for another set, you can easily do so. Here is an example.
tip = 0.15
print( 77*tip )
print( 32.09*tip )
tip = 0.12
print( 14*tip )
print( 7.99*tip )
21.4.1 Printing a Variable
Try -
x = 1
print( x )
print( "x" )
The statement ‘x = 1’ creates a variable named x and assigns it to 1. When you write a print statement with x within quote, Python prints the text ‘x’ on the screeen. However, if you remove the quote, Python prints the value of the variable x. Make sure x is defined, or otherwise Python will fail or give you an error.
Try -
x = 1
print( "the value of x is", x, "!!!" )
If you remember from the first section, commas are used to print multiple things in the same line. Here we are using comma to print texts and variable in the same line.
21.4.2 Integers and Decimal Numbers
Try -
i = 1
j = 1.0
print( "i = ", i, "j = ", j )
Above code creates two types of variables - integer i and decimal j. They are treated differently in Python.
It is possible to reassign a variable from integer to decimal or back, as shown in the following code.
i = 1
j = 1.0
print( "i = ", i, "j = ", j )
i = 7.77
print( "i = ", i, "j = ", j )
j = 2
print( "i = ", i, "j = ", j )
Operator | Action |
---|---|
x + = 10 | x = x+10 |
x - = 10 | x = x-10 |
x * = 10 | x = x*10 |
x / = 10 | x = x/10 |
21.4.3 Boolean Variables
Boolean Variables take only two values - True and False. Let us see an example -
#
# Logical(Boolean) variables have values True or False
#
x = 7
y = x > 0
print( y )
z = x < 0
print( z )
The code in the second line checks whether x is greater than zero and saves the result True in the variable y. Similarly, z is assigned the value False based on the comparison.
Operator | Action |
---|---|
x > y | If x>y, True, otherwise False. |
x > = y | If x> = y, True, otherwise False. |
x = = y | If x equals y, True, otherwise False. |
x ! = y | If x equals y, False, otherwise True. |
x < y | If x < y True, otherwise False. |
x < = y | If x < = y True, otherwise False. |
21.4.4 Exercises
21.4.4.1 Question
Write a program to convert temperature from Fahrenheit to Centigrade.
21.4.4.2 Question
Write a program to convert temperature from Centigrade to Fahrenheit.
21.5 Lists
Keyword | Action |
---|---|
in | checks if an element is in a list or dictionary |
del | deletes an element from a list or dictionary |
Try -
a = [1,3,2,0]
print( a[2] )
print( a )
The variable ‘a’ is a list (or array). It has 4 entries with indices 0-3.
Try -
a = [1,3,2,0]
b = [2,3,1,7]
print( a + b )
You can use ‘+’ to concatenate two lists.
Try -
a = [1,3,4,9,6,2,0]
b = a[3:7]
print( b )
You can use ‘:’ to get sublist.
Try -
a = [1,3,4,9,6,2,0]
b = a[3:7:2]
print( b )
The above command gives a sublist from 3 to 7, skip 2.
Try -
a = [1,3,4,9,6,2,0]
b = a[::-1]
print( b )
The above command reverses the list.
21.6 Built-in Functions
21.6.1 Function - range()
The function range creates a list of integers.
print( range(3) )
print( range(1,5) )
print( range(1,5,2) )
21.6.2 Function - len()
x = range(9,2,-2)
print( len(x) )
In the following code, the variable i goes from 0 to 3, because len(a) = 4.
a = [0,1,2,3]
print( "loop using list indices" )
for i in range(len(a)):
print( i,"a[i]+8 = ",a[i]+8 )
21.6.3 Function - float()
x = 1
y = float(x)
print( x, y )
The function float converts an integer to a floating point number.
21.6.4 Function - int()
x = 1.7
y = int(x)
print( x, y )
The function int gives the integer part of a floating point number.
21.8 Standard Flow of Code
A. A concept that works for simples code also works for complex code.
B. How variables are stored internally. –> debugging.
At this point, it is helpful to discuss how Python runs programs with multiple lines. Here are the rules.
- Sequential execution: Python starts executing code from line 1 and continues to execute each line sequentially until reaching at the end of the file.
i = 1
j = 10
k = i*j+10
print( i, j, k )

Figure
Comments: Python ignores empty lines. So, you can sprinkle them in your code to improve readability. Also, if a line contains the character ‘#,’ all text to the right of ‘#’ are ignored. An example is shown below.
Loops and conditions: There are situations, where you may not want to execute every line once. You may want some line to be run five times with five different parameters. You may also choose to skip lines, if certain condition is not met. Special keywords (for, while, if) are used to break the flow of sequencial execution, and we will learn about them in the later chapters.
21.8.1 Changing the standard flow
In standard flow, a python script starts from the first line in a file and continues running the code in each line until reaching the last line in the file.
This flow can be changed with specialized code blocks. Those fall in three categories.
- The ‘for’ block allows running the commands within a set of lines multiple times.
for i in [1,2,3,4,5,6,7,8,9,10]:
print( "5 times", i, "is", 5*i )
- The ‘if’ block allows running the commands within a set of lines only if a condition is satisfied.
i = 7
if(i<10):
print( i, " is less than 10" )
else:
print( i, " is greater than 10" )
- The ‘while’ blocks allow running the commands within a set of lines multiple times.
i = 1
while(i< = 10):
print( 5*i )
i = i+1
- The ‘def’ block gives a name to a set of lines of code. Afterward in the code, whenever the programmer wites the name, Python automatically executes those lines of code.
def square(x):
return x*x
print( square(2) )
print( square(3) )
We will see examples of all four methods in the following sections.
21.9 Conditional Statements
Keyword | Action |
---|---|
if, else, elif | conditional statement |
You remember that a Python program runs by executing the code in each sentence, starting from the top. Sometimes that standard flow is not desirable. For example, you may want to execute a block of lines, only if certain condition is satisfied. The keywords ‘if,’ ‘else,’ ‘elif’ help in building such conditional code.
Here is an example. You can interchange the values i and j to see how the flow changes.
Try -
condition = True
if condition:
print( "condition is", condition, ". Line 1 is running" )
else:
print( "condition is", condition, ". Line 2 is running" )
Try -
i = 3
j = 200
if (i == 2):
print( "number is 2" )
elif (i == 1):
print( "number is 1" )
else:
print( i,j )
21.9.1 Summary of rules
- The keywords ‘if,’ ‘else,’ ‘elif’ are used to write conditional execution of code.
21.9.2 Exercises
21.9.2.1 Question
** Write a program that start with an integer. If the integer divides by 3, it print( s Fizz. If the integer divides by 5, it prints Buzz. If the integer divides by both 3 and 5, it print( s FizzBuzz.**
21.10 ‘for’ Loops
Keyword | Action |
---|---|
for | loop |
continue | skips over the remaining lines and repeats |
break | quits the loop |
There are situations, where similar code-block needs to be written many times. An example is shown below.
Try -
print( "5 times 1 is", 5*1 )
print( "5 times 2 is", 5*2 )
print( "5 times 3 is", 5*3 )
print( "5 times 4 is", 5*4 )
print( "5 times 5 is", 5*5 )
print( "5 times 6 is", 5*6 )
print( "5 times 7 is", 5*7 )
print( "5 times 8 is", 5*8 )
print( "5 times 9 is", 5*9 )
print( "5 times 10 is", 5*10 )
The above code print( s the multiplication table for 5, but it is too tiring to type. Imagine if you have to type the same multiplication table to 5 times 100.
Python provides a shortcut for such situations using the keyword ‘for.’ The following code produces the same output as the long code shown above.
for i in [1,2,3,4,5,6,7,8,9,10]:
print( "5 times", i, "is", 5*i
print( "completed for loop" )
The keyword ‘for’ is used to repeat a block of code many times. That block of code needs to follow the line with ‘for’ statement with an indentation.
Here is how the above code works. On the ‘for’ statement, Python creates a variable i with value = 1 and runs the code in the indented block. After completion, i becomes 2, 3, etc. up to 10 based on the list, and each time the indented block is executed with the new value of i. Once the final value of the list is reached, Python continues with the following unidented statement and print( s “completed for loop.”
It is possible to condense the code further. Instead of writing the entire list, you can use the range() function to auto-generate the list, as shown below.
for i in range(1,11):
print( "5 times", i, "is", 5*i )
print( "completed for loop" )
Converting the above code to type the multiplication table up to 5 time 100 is rather easy. Just replace 11 in the range function to 101.
21.10.1 Expansion of ‘for’ Loops
Here are some examples to help you better understand ‘for’ loops. With these examples, we are giving you the code using ‘for.’ You need to write the expanded code, where you do not use ‘for.’
21.10.1.1 Expand -
for i in [1,3,5,7,9,11,13,15,17,19]:
print( "5 times", i, "is", 5*i )
Answer -
print( "5 times 1 is", 5*1 )
print( "5 times 3 is", 5*3 )
print( "5 times 5 is", 5*5 )
print( "5 times 7 is", 5*7 )
print( "5 times 9 is", 5*9 )
print( "5 times 11 is", 5*11 )
print( "5 times 13 is", 5*13 )
print( "5 times 15 is", 5*15 )
print( "5 times 17 is", 5*17 )
print( "5 times 19 is", 5*19 )
21.10.1.2 Expand -
x = 7
for i in [1,2,7,9]:
x = x+7*i*(i-1)
print( x )
Answer -
x = 7
x = x+7*1*0
x = x+7*2*1
x = x+7*7*6
x = x+7*9*8
print( x )
21.10.1.3 Expand -
x = 7
for i in [2,1,0]:
x = i-2
print( x )
Answer -
x = 7
x = 2-2
x = 1-2
x = 0-2
print( x )
21.10.2 Keywords ‘break’ and ‘continue’
Sometimes it is necessary to break out of ‘for’ loop, if certain conditions are satisfied. The keywords ‘break’ and ‘continue’ help in interrupting the standard flow. They are explained in the following section with respect to ‘while’ loops, but work for ‘for’ in a similar manner.
21.10.3 Summary
Python keyword ‘for’ executes the same block of code many times. The block of code needs to be written immediately after the ‘for’ statement with indentation. After completion of the ‘for’ block, Python continues with subsequent non-indented code.
The ‘for’ statement can state a changing variable given based on a list, dictionary or string. The block of code executing in each ‘for’ run uses the new value of the variable. Later we will learn that the ‘for’ statement can be extended for other kinds of custom variables known as ‘iterables.’
One weakness of ‘for’ is that the values of the looping variable need to be know a-priori. There are situations, where the next value of the looping variable is determined based on the execution of the loop. Such codes are written using the Python keyword ‘while,’ as explained in the following section.
21.10.4 Exercises
21.10.4.1 Question
Expand -
x = 7
for i in [1,2,7,9]:
x = x+7*i*(i-1)
print( x )
21.10.4.2 Question
Expand -
x = 7
for i in [2,1,0]:
x = i-2
print( x )
21.10.4.3 Question
You are given a positive integer n. Print sum 1+2+…+n.
21.10.4.4 Question
You are given a positive integer n. Print sum 13+23+…+n^3. Also, sum of squares.
21.10.4.5 Question
Given a positive integer n, add 30+31+…3^n. Is there an easy rule to get the sum?
21.10.4.6 Question
Given a positive integer n, add 20+21+…2^n. Is there an easy rule to get the sum?
21.10.4.7 Question
Given N, print factorial N.
21.10.4.8 Question
** Explain the outputs of the following two codes.**
a = [1,3,2,0]
for i in a:
print( i,"a[i]+8 = ",a[i]+8 )
a = [1,3,2,0]
for i in range(len(a)):
print( i,"a[i]+8 = ",a[i]+8 )
21.10.4.9 Question
Write code to compute compound interest.
21.11 ‘while’ Loops
Keyword | Action |
---|---|
while | conditinal loop |
continue | skips over the remaining lines and repeats |
break | quits the loop |
Try -
i = 0
while i<10:
i = i+1
print( "5 times", i, "is", 5*i )
The keyword ‘while’ is used to loop over the same code many times. However, how many times the loop will run is not pre-determined. Instead, the ‘while’ statement checks for a condition or logical variable. The loop continues to run as long as the condition remains True.
21.11.1 Keywords ‘break’ and ‘continue’
‘While’ loops become even more powerful, when they are customized using an internal condition (‘if’). The keywords ‘break’ and ‘continue’ come handy in that situation.
Code -
i = 0
while i<10:
i = i+1
if(i == 4):
break
print( "5 times", i, "is", 5*i )
The keyword ‘break’ halts further execution of the ‘while’ block, and moves to the subsequent unidented lines in the code.
Try -
i = 0
while True:
i = i+1
if i == 4:
break
print( "5 times", i, "is", 5*i )
In the above code, the condition for ‘while’ is always True. Therefore, it is expected to run infinite times. That does not happen, because the loop is terminated using ‘break,’ when i reaches 4.
Try -
i = 0
while i<10:
i = i+1
if i == 4:
continue
print( "5 times", i, "is", 5*i )
The keyword ‘continue’ skips over the remaining lines of the ‘while’ block and starts the following run of the ‘while’ loop.
21.11.2 Summary
Python keyword ‘while’ combines the power of looping with the ability to check a condition. Therefore, it is used to create loops, where the number of times the loop is run is not easy to pre-determine.
Overall, the keywords ‘if,’ ‘else,’ ‘elif,’ ‘for,’ ‘while,’ ‘break,’ ‘continue’ covered over the last three chapters give a programmer immense flexibility to write wide variety of programs. However, often it is necessary to read the input from the keyboard or a file and save the output in a file as well. We explore that in the followng section.
21.12 Creating New Functions
Keyword | Action |
---|---|
def | Defines new function |
return | Returns value at the end of function |
from | Gives name of an external file |
import | Brings in functions from an external file |
You have been using many Pythons functions, such as range(), sort(), etc., to improve your code. Internally, a function is block of code with a given name. When you use a function (e.g. range(4)) within your code, Python executes the corresponding block of code and returns the result. That way your code stays small and readable.
Apart from the in-built functions Python provides you with, you can also create your own functions. Here is an example.
Code -
def square(x):
return x*x
print( square(2) )
print( square(3) )
The keyword ‘def’ gives name to a function, and the variables within the parenthesis are its parameter. The block of indented code following def represents the code of the function, and the ‘return’ statement gives its return value to be used by the main program.
Here, you created a function named ‘square’ that takes only one parameter x. Internally, this function computes x*x and returns the result. Whenever you use square() in your main code, Python runs the block of code from its definition to get a result.
21.12.1 Code Flow with Functions
We need to also make clear that your main code consists of all lines after excluding the def blocks. The standard linear flow of execution from top to bottom does not hold for the functions. Let us illustrate the point with two codes.
Code 1 -
i = 2
j = 3
def square(x):
print( "inside",i,j )
return x*x
print( square(i) )
print( square(j) )
Code 2 -
def square(x):
print( "inside",i,j )
return x*x
i = 2
j = 3
print( square(i) )
print( square(j) )
You will see that both produce the same output. You may find that odd, because i and j are not defined before the function in the second case. How does the function know their values?
They work identically in both cases, because Python isolates the def block and keeps it separately. Then it takes the remaining lines and executes the code from top to bottom. Hence, i and j are already defined by the time the function square is called.
21.12.2 Default Parameter
Code -
def square(x = 1):
return x*x
print( square() )
print( square(2) )
print( square(3) )
The above code gives default value of 1 to the parameter x. When the function square() is called without any number, Python uses the default value to print( 1*1.
21.2 Comments
As you learned in the last section, Python starts from the top of a multi-line code and executes every line of instruction until it reaches the bottom. However, it is possible to tell Python to ignore certain lines, and to do that add ‘#’ at the front of the line. If the character ‘#’ is placed in the middle of a line, all texts written on the right of ‘#’ are ignored.
Try this command -
You will see that Python only prints ‘Today is Saturday’ and ignores everything else. Since Python ignores all text after the character ‘#,’ the part ‘print “Yesterday was Friday”’ is ignored.
There is only one exception to the rule as shown in the following code.
If “#” is within the quotes of a valid string, it is not ignored. If you are unfamiliar with the word string, it is the computer science term for a set of characters. We describe string variables in section 5.
21.2.1 Summary of rules