CS GR6 Python+Notes
CS GR6 Python+Notes
A. Quick Recap
We start Python by double clicking on the Python shortcut icon on the desktop or on the taskbar. You can
also use Cortana to search for IDLE and open it.
Python IDLE stands for Integrated Development and Learning Environment. Python IDLE is the interactive
mode of Python where we type program commands one line (or one block of code) at a time. This line of
code gets executed instantly and the output is displayed on the IDLE.
A.1 Python IDLE:
Print function in Python 3 version performs the same task as Python print statement in 2.7. It helps us
display things. If you want to print some text like the example given below, you put the text within quotes.
Python allows both single as well as double quotes for inputting text.
If you want to print a numeric value, then do not use quotes.
The first print function causes 10 to be printed. Since it is a number, we do not use quotes while printing it.
The second print function prints text. So, we need to use quotes.
The third print function uses a combination of number and text. We use a comma to separate number and
text here.
1
The fourth print function uses double quotes at the beginning of text and single quotes at the end. This
causes Python to return an error. You can see that an error is returned by Python (line in red). Let us correct
this error by matching the single quote at the end with one at the beginning.
The New File that opens is a text editor and looks like this:
2
2. You will see a dialog box open that asks you to save your program first. Give a suitable name for the
program and save it. In Windows, the default location is Python folder.
3
3. IDLE pops up with the output:
A+ B Addition operation
4
A == B Checks if A is equal to B. == operator is different
from = operator. = is used for assigning a value to a
variable. == is used for checking if 2 values are
equal.
A = 3.4
A = 2 + 3.0
print (A)
9/4
9/4.0
9.0/2
B=A
B=3
B == A
17 % 7
17.0%7
‘Ha’*3
5
‘Ha’ * ’3’
print (‘red’)
print (‘green’)
print (‘blue’)
We use the input( ) function to accept user value in Python 3. This has the same functionality as raw_input()
in Python 2.7. Observe the example given below:
input() accepts any value given by the user and assigns it to the variable on the left hand side. The text that
appears inside the input() is the prompt given to the user. If you want to ask the user to input his name, then
the prompt can be ‘Enter your name’.
Note:input() accepts any input given by user as string (text) value. But numbers are not text. If we want to
accept numbers, we need to use an additional function outside the input().
If the user has to input an integer, we use int() which encloses input(). If the user has to input decimal
fractions, we use float().
6
Note: A comma separator in print function adds a space automatically in output. In input(), we need to put
an extra space when typing our prompt so that there is a space seen after the prompt when it appears on
IDLE.
B. IF Statements in Python
If statement checks if a condition is true. We have already seen how conditions can be checked in the
Algorithms and Flowcharts unit. When a condition is true, one branch of the program gets executed.
Otherwise, another branch of the program gets executed. In Python, If statements form a block of
statements. (A block is a set of statements which are executed as a unit.)
B.1 Simple IF Statement
Syntax for a simple IF statement:
In this case, a condition is tested. If it is true, then a code block is executed.
if <condition to be tested>:
<statements to be executed>
Notice that the statements to be executed are indented. Python automatically indents statements when it
reads the colon separator. Colon separator indicates the beginning of a code block.
7
But wouldn’t it be more informative if we had an output when the entered number is not positive? We need
an IF-ELSE block in order to achieve this.
If we want to test the truth of a condition, we can use IF or IF-ELSE statements. But, what if we have
multiple conditions that need to be tested? One example of such a scenario is when we check the marks
obtained by a student and allot a grade. Look at the table given below:
8
Marks Grade
Marks < 35 F
When the marks lie between a particular range, a corresponding grade will be given. This requires not just
one IF statement, but multiple statements. This type of IF statements are known as concatenated IF
statements.
if <condition1>:
<statements>
elif <condition2>:
<statements>
elif <condition3>:
<statements>
:
:
else:
<statements>
Output:
9
Points to ponder:
● and operator ensures that marks are in the range 75 to 100. It is a logical operator. There are three
Logical operators in Python: not, and, or. When we want to check if multiple conditions are
simultaneously true, we use and. When we want to check if any one of the conditions is true out of
many, we use or.
● The upper limit of marks is not checked in the elif statements. Why do you think we need not check
it?
● What happens if a user inputs negative number? How can we modify the program such that user
gets a message ‘Invalid input’ if negative numbers are input.
Output:
10
Practice Exercise:
1. Write a program that accepts a number from 1 to 7 and displays the corresponding day of the week.
If any other number is entered, program should display the message, “Invalid Number “.
A function is a routine or a procedure in programming. It accepts some input, modifies the input and returns
an output. Examples of Python function you have seen before include: input(), float(), int() etc. These are
known as Built in functions since they already exist in Python and have not been created newly by anyone.
The input given to a function is known as an argument. The output given by a function is known as its return
value.
Let us take a look at some important builtin functions in Python: (All these functions can be used to compare
values of different data types but this aspect is beyond the scope of this unit.)
len (s) It returns the length of a Python string or a list. >>> len('red rose')
8
>>> len([1,2,3,4])
4
11
A list in Python is a series of values, which are generating the iterable.
separated by comma and placed inside square
brackets. Each of these values is known as an
element.
Parameters in range()
Why do we get an empty list here?
Start indicates the starting value of the number Python assumes that starting value is
in the iterable. 10 and stop value is 3. Step size is 1,
that means by incrementing 1 from
Stop value indicates the ending value in the list. 10, Python should reach 3. Since that
However, in Python the end value is excluded is never possible, it returns an empty
from the iterable. list.
len(5)
len([1,2,3,4])
len(‘apple’)
max(-9, 5, 0.5)
max([1,2,3], 5.6)
12
list(range(2, 21, 3))
list(range(4))
list(range(10, 4, -2))
list(range())
round(33.336, 2)
round(3.141592, 2)
D. Loops in Python
A loop is the programmer’s way of telling the computer to do something and keep doing until something
changes. If we know the number of times a block of instructions has to be executed, we use the FOR loop.
If we do not know how many times a specific block of instructions need to be executed, we use the WHILE
loop in Python.
Real life examples of FOR loop:
● Completing 10 rounds of jogging around the park.
● Making 15 rotis for dinner.
● Reciting the multiplication table for any number.
We use the range function to create an iterable based on the start, stop and step values. The variable i
stands for each of the numbers present in the iterable object.
Example 1: Consider the following example that prints the numbers 1 to 10 using for loop:
13
Notice that the stop value is 11 and not 10. range(1,11) returns the collection of numbers: 1, 2, 3, 4, 5, 6, 7,
8, 9, 10. Since there are 10 elements in the iterable object, the loop runs 10 times. Each time the loop is
run, the value of the variable i changes from 1 to 2 to 3 and so on.
We print each element using the print(i) function.
Example 2:
Output:
Example 3: Write a program that accepts user name and prints it 6 times.
range(6) creates the list [0, 1, 2, 3, 4, 5]. In this example, the for loop’s only purpose is to keep track of the
number of times the statements are executed. Since the name has to be printed 6 times, we need the loop
to run 6 times. In other words, the number of elements present inside the list should be 6. If we start from 0
and stop at 5, we have 6 elements in the list. We can achieve the same result using this range function:
range(1,7).
Output:
14
Example 4: To print multiplication table for a user given number.
We can use FOR statement without using range function. Instead of creating an iterable object, we can use
a list of values in our loops.
Output:
15
i takes the value of ‘a’ first, then ‘b’ and so on.
What does 4*i mean? We are multiplying a string value with a number.
The * operator is known as replication operator when used with strings. It replicates the string that many
times.
Python returns an error. We can use the replication operator with strings only when there is one number and
one string as operands.
Here s is a string, not a list. But, s is still a sequence that has elements, just like a list. The variable, i takes
on the values from the string - ‘r’, ‘a’, ‘c’, ‘e’ etc.
What is the use of end = ‘ ‘ in print()? This causes the next value to be printed on the same line instead of
a new line.
Output:
16
4. Print the following pattern:
11111
22222
33333
5. Given that l = [1,3,5,7,9], print 2, 4, 6, 8, 10 using a FOR loop.
Example 1: Accept a number from the user and print ‘Hello’ that many times using a while loop. (Note: This
program is easier using FOR. This example is given to demonstrate how while loop works.)
Output:
The condition in the program is that as long as the number entered is greater than 0, ‘hello’ will be printed.
Within the body of the loop, everytime we print ‘hello’, we have to reduce n by 1. This statement, n = n - 1 is
known as the update statement. What will happen if we do not decrement n?
Output:
The word Hello keeps printing on IDLE and the program execution will not end unless we stop it by closing
IDLE.
17
If an update statement is not given in a while block, we will have an infinite loop. An infinite loop keeps
running until we close the program.
Output:
18
Example 3: Accept number n1 and number n2. Print the first ‘n2’ multiples of ‘n1’. If n1 = 5 and n2 = 3, then
the program needs to print the first 3 multiples of 5.
Output:
19
Exercises
A. Correct the errors in the given programs:
1.
2.
3.
B. Predict the output of the given programs and state the purpose of the program.
1. n1 = 12, n2 = 3, n3 = 5.
2.
3.
20
1. When do we need to use IF-ELIF-ELSE block?
2. Explain range() with examples.
3. What is the difference between FOR and WHILE loop?
4. Write the syntax for while loop.
21