Python Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Program 5.

6 : To demonstrate Numeric literals


# Program to demonstrate Numeric Literals
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
print ("Integer Literals :",a,b,c,d)
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
print ("Float Literals :",float_1,float_2)
#Complex Literal
x = 1 + 3.14 j
print ("Complex Literals :")
Print ("x = ", x , "Imaginary part of x = ", x.imag, "Real part of x = ", x.real)
#End of the Program
Output:
Integer Literals : 10 100 200 300
Float Literals : 10.5 150.0
Complex Literals :
x = (1+3.14j) Imaginary part of x = 3.14 Real part of x = 1.0

(ii) String Literals


In Python a string literal is a sequence of characters surrounded by quotes. Python
supports single, double and triple quotes for a string. A character literal is a single character
surrounded by single or double quotes. The value with triple-quote "' '" is used to give multi-
line string literal. A Character literal is also considered as string literal in Python.

Program 5.7 To test String Literals


# Demo Program to test String Literals
strings = "This is Python"
char = "C"
multiline_str = "'This is a multiline string with more than one line code."'
print (strings)
print (char)
print (multiline_str)
# End of the Program

Output:
This is Python
C
This is a multiline string with more than one line code.

XII Std Computer Science 62

12th Computer Science_EM Chapter 5.indd 62 26-12-2022 17:27:29


(iii) Boolean Literals
A Boolean literal can have any of the two values: True or False.
Program 5.8 To test Boolean Literals:
# Demo Program to test String Literals
boolean_1 = True
boolean_2 = False
print ("Demo Program for Boolean Literals")
print ("Boolean Value1 :",boolean_1)
print ("Boolean Value2 :",boolean_2)
# End of the Program
Output:
Demo Program for Boolean Literals
Boolean Value1 : True
Boolean Value2 : False

(iv) Escape Sequences


In Python strings, the backslash "\" is a special character, also called the "escape"
character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a
newline, and "\r" is a carriage return. For example to print the message "It's raining", the
Python command is
>>> print ("It\'s rainning")
It's rainning
Python supports the following escape sequence characters.

Escape sequence Description Example Output


character

\\ Backslash >>> print("\\test") \test

\’ Single-quote >>> print("Doesn\'t") Doesn't


\” Double-quote >>> print("\"Python\"") "Python"
\n New line print("Python","\n","Lang..") Python
Lang..
\t Tab print("Python","\t","Lang..") Python Lang..

5.8 Python Data types


All data values in Python are objects and each object or value has type. Python has
Built-in or Fundamental data types such as Number, String, Boolean, tuples, lists, sets and
dictionaries etc.
63 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 63 26-12-2022 17:27:29


5.8.1 Number Data type
The built-in number objects in Python supports integers, floating point numbers and
complex numbers.
Integer Data can be decimal, octal or hexadecimal. Octal integer use digit 0 (Zero)
followed by letter 'o' to denote octal digits and hexadecimal integer use 0X (Zero and either
uppercase or lowercase X) and L (only upper case) to denote long integer.
Example :
102, 4567, 567 # Decimal integers
0o102, 0o876, 0o432 # Octal integers
0X102, 0X876, 0X432 # Hexadecimal integers
34L, 523L # Long decimal integers

A floating point data is represented by a sequence of decimal digits that includes a


decimal point. An Exponent data contains decimal digit part, decimal point, exponent part
followed by one or more digits.

Example :
123.34, 456.23, 156.23 # Floating point data
12.E04, 24.e04 # Exponent data

Complex number is made up of two floating point values, one each for the real and
imaginary parts.
5.8.2 Boolean Data type
A Boolean data can have any of the two values: True or False.
Example :
Bool_var1=True
Bool_var2=False

5.8.3 String Data type


String data can be enclosed in single quotes or double quotes or triple quotes.

Example :
Char_data = ‘A’
String_data= "Computer Science"
Multiline_data= ”””String data can be enclosed in single quotes or
double quotes or triple quotes.”””

XII Std Computer Science 64

12th Computer Science_EM Chapter 5.indd 64 26-12-2022 17:27:29


Points to remember:
• Python is a general purpose programming language created by Guido Van Rossum.
• Python shell can be used in two ways, viz., Interactive mode and Script mode.
• Python uses whitespace (spaces and tabs) to define program blocks
• Whitespace separation is necessary between tokens, identifiers or keywords.
• A Program needs to interact with end user to accomplish the desired task, this is done
using Input-Output facility.
• Python breaks each logical line into a sequence of elementary lexical components
known as Tokens.
• Keywords are special words that are used by Python interpreter to recognize the
structure of program.

Evaluation
Part - I
Choose the best answer (1 Marks)
1. Who developed Python ?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<<
C) # D) <<
3. Which of the following shortcut is used to create new Python Program ?
A) Ctrl + C B) Ctrl + F
C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($)
C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers
C) Keyword D) Operators

65 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 65 26-12-2022 17:27:29


7. Which of the following is not a Keyword in Python ?
A) break B) while
C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational
C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or
C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational
C) Logical D) Assignment

Part - II
Answer the following questions : (2 Marks)
1. What are the different modes that can be used to test Python Program ?
2. Write short notes on Tokens.
3. What are the different operators that can be used in Python ?
4. What is a literal? Explain the types of literals ?
5. Write short notes on Exponent data?

Part - III
Answer the following questions : (3 Marks)
1. Write short notes on Arithmetic operator with examples.
2. What are the assignment operators that can be used in Python?
3. Explain Ternary operator with examples.
4. Write short notes on Escape sequences with examples.
5. What are string literals? Explain.

Part - IV
Answer the following questions : (5 Marks)
1. Describe in detail the procedure Script mode programming.
2. Explain input() and print() functions with examples.
3. Discuss in detail about Tokens in Python

XII Std Computer Science 66

12th Computer Science_EM Chapter 5.indd 66 26-12-2022 17:27:29


CHAPTER 6
Unit II
CONTROL STRUCTURES

Learning Objectives

After studying this lesson, students will be able to:

• To gain knowledge on the various flow of control in Python language.

• To learn through the syntax how to use conditional construct to improve the efficiency of
the program flow.

• To apply iteration structures to develop code to repeat the program segment for specific
number of times or till the condition is satisfied.

6.1 Introduction

Programs may contain set of statements. These statements are the executable segments
that yield the result. In general, statements are executed sequentially, that is the statements
are executed one after another. There may be situations in our real life programming where
we need to skip a segment or set of statements and execute another segment based on the test
of a condition. This is called alternative or branching. Also, we may need to execute a set of
statements multiple times, called iteration or looping. In this chapter we are to focus on the
various control structures in Python, their syntax and learn how to develop the programs
using them.

6.2 Control Structures


A program statement that causes a jump of control from one part of the program to
another is called control structure or control statement. As you have already learnt in C++,
these control statements are compound statements used to alter the control flow of the process
or program depending on the state of the process.

67

12th Computer Science_EM Chapter 6.indd 67 26-12-2022 16:44:45


There are three important control structures

Sequential

Alternative or
Branching

Iterative or Looping

6.2.1 Sequential Statement


A sequential statement is composed of a sequence of statements which are executed
one after another. A code to print your name, address and phone number is an example of
sequential statement.

Example 6.1
# Program to print your name and address - example for sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN

6.2.2 Alternative or Branching Statement


In our day-to-day life we need to take various decisions and choose an alternate path
to achieve our goal. May be we would have taken an alternate route to reach our destination
when we find the usual road by which we travel is blocked. This type of decision making is
what we are to learn through alternative or branching statement. Checking whether the given
number is positive or negative, even or odd can all be done using alternative or branching
statement.

Python provides the following types of alternative or branching statements:


• Simple if statement • if..else statement • if..elif statement

(i) Simple if statement


Simple if is the simplest of all decision making statements. Condition should be in the
form of relational or logical expression.

XII Std Computer Science 68

12th Computer Science_EM Chapter 6.indd 68 26-12-2022 16:44:45


Syntax:
if <condition>:
statements-block1

In the above syntax if the condition is true statements - block 1 will be executed.

Example 6.2
# Program to check the age and print whether eligible for voting
x=int (input("Enter your age :"))
if x>=18:
print ("You are eligible for voting")
Output 1:
Enter your age :34
You are eligible for voting
Output 2:
Enter your age :16
>>>

As you can see in the second execution no output will be printed, only the Python
prompt will be displayed because the program does not check the alternative process when the
condition is failed.

(ii) if..else statement


The if .. else statement provides control to check the true block as well as the false
block. Following is the syntax of ‘if..else’ statement.

Syntax:
if <condition>:
statements-block 1
else:
statements-block 2

69 Control Structures

12th Computer Science_EM Chapter 6.indd 69 26-12-2022 16:44:45


Entry

if condition is if condition is
true condition false

Statement Statement
block -1 block -2

Exit
Fig. 6.1 if..else statement execution

if..else statement thus provides two possibilities and the condition determines which
BLOCK is to be executed.

Example 6.3: #Program to check if the accepted number odd or even


a = int(input("Enter any number :"))
if a%2==0:
print (a, " is an even number")
else:
print (a, " is an odd number")
Output 1:
Enter any number :56
56 is an even number
Output 2:
Enter any number :67
67 is an odd number

An alternate method to rewrite the above program is also available in Python. The
complete if..else can also written as:

Syntax:
variable = variable1 if condition else variable 2

XII Std Computer Science 70

12th Computer Science_EM Chapter 6.indd 70 26-12-2022 16:44:45


Note
The condition specified in the if statement is checked, if it is true, the value of
variable1 is stored in variable on the left side of the assignment, otherwise variable2 is
taken as the value.

Example 6.4: #Program to check if the accepted number is odd or even


(using alternate method of if...else)
a = int (input("Enter any number :"))
x="even" if a%2==0 else "odd"
print (a, " is ",x)
Output 1:
Enter any number :3
3 is odd
Output 2:
Enter any number :22
22 is even

(iii) Nested if..elif...else statement:


When we need to construct a chain of if statement(s) then ‘elif ’ clause can be used
instead of ‘if else’.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n

In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then


statements-block1 is executed, otherwise the control checks condition-2, if it is true statements-
block2 is executed and even if it fails statements-block n mentioned in else part is executed.

71 Control Structures

12th Computer Science_EM Chapter 6.indd 71 26-12-2022 16:44:45


Test false
Expression
of if

True Test false


Expression
Body of if of elif

True

Body of else
Body of elif

Fig 6.2 if..elif..else statement execution

‘Multiple if..else statements can be combined to one if..elif…else. ‘elif ’ can be


considered to be abbreviation of ‘else if ’. In an ‘if ’ statement there is no limit of ‘elif ’ clause
that can be used, but an ‘else’ clause if used should be placed at the end.

Note
if..elif..else statement is similar to nested if statement which you have learnt in C++.

XII Std Computer Science 72

12th Computer Science_EM Chapter 6.indd 72 26-12-2022 16:44:45


Example 6.5: #Program to illustrate the use of nested if statement

Average Grade
>=80 and above A
>=70 and <80 B
>=60 and <70 C
>=50 and <60 D
Otherwise E

m1=int (input(“Enter mark in first subject : ”))


m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)

Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D

Output 2 :
Enter mark in first subject : 67
Enter mark in second subject : 73
Grade : B

Note
In the above example of if and elif statement are both indented four spaces, which
is a typical amount of indentation for Python. In most other programming languages,
indentation is used only to help make the code look pretty. But in Python, it is required
to indicate to which block of code the statement belongs to.

73 Control Structures

12th Computer Science_EM Chapter 6.indd 73 26-12-2022 16:44:45


Example 6.5a: #Program to illustrate the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)
Output 1:
Enter a character :e
e is a vowel
Output 2:
Enter a character :x
x the letter is not a/b/c

6.2.3. Iteration or Looping constructs

Iteration or loop are used in situation when the user need to execute a block of code
several of times or till the condition is satisfied. A loop statement allows to execute a statement
or group of statements multiple times.

False
Condition

True else
Statement 1
Statement 1 Statement 2
Statement 2 ...
... Statementn
Statementn
Further
Statements
of Program
Fig 6.3 Diagram to illustrate how looping construct gets executed
Python provides two types of looping constructs:
• while loop
• for loop
XII Std Computer Science 74

12th Computer Science_EM Chapter 6.indd 74 26-12-2022 16:44:45


(i) while loop
The syntax of while loop in Python has the following syntax:

Syntax:
while <condition>:
statements block 1
[else:
statements block2]

while Expression:
Statement (s)
Condition

if conditions is true
if condition is
Conditional Code
false

Fig 6.4 while loop execution


In the while loop, the condition is any valid Boolean expression returning True or
False. The else part of while is optional part of while. The statements block1 is kept executed
till the condition is True. If the else part is written, it is executed when the condition is tested
False. Recall while loop belongs to entry check loop type, that is it is not executed even once if
the condition is tested False in the beginning.

Example 6.6: program to illustrate the use of while loop - to print all numbers
from 10 to 15

i=10 # intializing part of the control variable


while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable

Output:
10 11 12 13 14 15

75 Control Structures

12th Computer Science_EM Chapter 6.indd 75 26-12-2022 16:44:46


Note
In the above example, the control variable is i, which is initialized to 10. Next the
condition i<=15 is tested, if the value is true i gets printed, then the control variable i gets
updated as i=i+1 (this can also be written as i +=1 using shorthand assignment operator).
When i becomes 16, the condition is returned as False and this will terminate the loop.

Note
print can have end, sep as parameters. end parameter can be used when we need to give
any escape sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sep as parameter can be
used to specify any special characters like, (comma) ; (semicolon) as separator between
values (Recall the concept which you have learnt in previous chapter about the formatting
options in print()).

Following is an example for using else part within while loop.

Example 6.7: program to illustrate the use of while loop - with else part

i=10 # intializing part of the control variable


while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable
else:
print ("\nValue of i when the loop exit ",i)
Output: 1
10 11 12 13 14 15
Value of i when the loop exit 16

(ii) for loop


The for loop is usually known as a definite loop, because the programmer knows exactly
how many times the loop will be executed.

Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]

The for .... in statement is a looping statement used in Python to iterate over a sequence
of objects, i.e., it goes through each item in a sequence. Here the sequence is the collection of
ordered or unordered values or even a string.
XII Std Computer Science 76

12th Computer Science_EM Chapter 6.indd 76 26-12-2022 16:44:46


The control variable accesses each item of the sequence on each iteration until it reaches the
last item in the sequence.

Example 6.8 (a) Example 6.8 (b)


for x in "Hello World": for x in (1,2,3,4,5):
print(x, end=' ') print("Hello World")
Output:
Output: Hello World
Hello World Hello World
Hello World
Hello World
Hello World

In the above example 6.8(a), we have created a string “Hello World”, as the sequence.
Initially, the value of x is set to the first element of the string, (i.e. ‘H’), so the print statement
inside the loop is executed. Then, the control variable x is updated with the next element of
the string and the print statement is executed again. In this way the loop runs until the last
element of the string is accessed.
In the same way, example 6.8(b) prints the string “Hello World”, five times, until the control
variable x reaches last element of the given sequence.
Instead of creating sequence of values manually, we can use range().
The range() is a built-in function, to generate series of values between two numeric intervals.
The syntax of range() is as follows:
range (start,stop,[step])

Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.

Example 6.8(c): Examples for range()


range (1,30,1) will start the range of values from 1 and end at 29
range (2,30,2) will start the range of values from 2 and end at 28
range (30,3,-3) - will start the range of values from 30 and end at 6
range (20) will consider this value 20 as the end value(or upper limit) and starts the
range count from 0 to 19 (remember always range() will work till stop -1
value only)

77 Control Structures

12th Computer Science_EM Chapter 6.indd 77 26-12-2022 16:44:46


for each item
in sequence

Yes
Last item
reached?

No
Body of for

Exit loop
Fig 6.5 for loop execution

Example 6.9: #program to illustrate the use of for loop - to print single
digit even number
for i in range (2,10,2):
print (i, end=' ')

Output:
2468

Following is an illustration using else part in for loop


Example 6.10 : #program to illustrate the use of for loop - to print single
digit even number with else part
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
End of the loop

Note
In Python, indentation is important in loop and other control statements. Indentation
only creates blocks and sub-blocks like how we create blocks within a set of { } in languages
like C, C++ etc.

Here is another program which illustrates the use of range() to find the sum of numbers
1 to 100

XII Std Computer Science 78

12th Computer Science_EM Chapter 6.indd 78 26-12-2022 16:44:46


Example 6.11: # program to calculate the sum of numbers 1 to 100
n = 100
sum = 0
for counter in range(1,n+1):
sum = sum + counter
print("Sum of 1 until %d: %d" % (n,sum))
Output:
Sum of 1 until 100: 5050
In the above code, n is initialized to 100, sum is initialized to 0, the for loop
starts executing from 1, for every iteration the value of sum is added with the value
of counter variable and stored in sum. Note that the for loop will iterate from 1 till
the upper limit -1 (ie. Value of n is set as 100, so this loop will iterate for values from
1 to 99 only, that is the reason why we have set the upper limit as n+1)

Note
for loop can also take values from string, list, dictionary etc. which will be dealt
in the later chapters.

Following is an example to illustrate the use of string in range()


Example 6.12: program to illustrate the use of string in range() of for loop
for word in 'Computer':
print (word,end=' ')
else:
print ("\nEnd of the loop")
Output
Computer
End of the loop

(iii) Nested loop structure


A loop placed within another loop is called as nested loop structure. One can place a
while within another while; for within another for; for within while and while within for to
construct such nested loops.
Following is an example to illustrate the use of for loop to print the following pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

79 Control Structures

12th Computer Science_EM Chapter 6.indd 79 26-12-2022 16:44:46


Example 6.13: program to illustrate the use nested loop -for within while loop
i=1
while (i<=6):
for j in range (1,i):
print (j,end='\t')
print (end='\n')
i +=1

Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

6.2.4 Jump Statements in Python


The jump statement in Python, is used to unconditionally transfer the control from one
part of the program to another. There are three keywords to achieve jump statements in Python
: break, continue, pass. The following flowchart illustrates the use of break and continue.

False
Condition

True else
Statement 1
Statement 1 Statement 2
... ...
break Statementn
...
continue Further
... Statements
Statementn of Program

Fig 6.6 Use of break, continue statement in loop structure

XII Std Computer Science 80

12th Computer Science_EM Chapter 6.indd 80 26-12-2022 16:44:46


(i) break statement
The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
A while or for loop will iterate till the condition is tested false, but one can even transfer
the control out of the loop (terminate) with help of break statement. When the break statement
is executed, the control flow of the program comes out of the loop and starts executing the
segment of code after the loop structure.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax:
break

Enter loop

false
Condition

true

break?
yes
Exit loop
no
Remaining body of loop

Fig 6.7 Working of break statement


The working of break statement in for loop and while loop is shown below.
for var in sequence:
if condition:
break
#code inside for loop
#code outside for loop
while test expression:
#code inside while loop
if condition:
break
#code inside while loop
#code outside while loop

81 Control Structures

12th Computer Science_EM Chapter 6.indd 81 26-12-2022 16:44:46


Example 6.14: Program to illustrate the use of break statement inside
for loop
for word in “Jump Statement”:
if word = = “e”:
break
print (word, end= ' ')
Output:
Jump Stat

The above program will repeat the iteration with the given “Jump Statement” as string.
Each letter of the given string sequence is tested till the letter ‘e’ is encountered, when it is
encountered the control is transferred outside the loop block or it terminates. As shown in the
output, it is displayed till the letter ‘e’ is checked after which the loop gets terminated.
One has to note an important point here is that ‘if a loop is left by break, the else part
is not executed’. To explain this lets us enhance the previous program with an ‘else’ part and
see what output will be:

Example 6.15: Program to illustrate the use of break statement inside


for loop
for word in “Jump Statement”:
if word = = “e”:
break
print (word, end=' ')
else:
print (“End of the loop”)
print (“\n End of the program”)
Output:
Jump Stat
End of the program

Note that the break statement has even skipped the ‘else’ part of the loop and has
transferred the control to the next line following the loop block.
(ii) continue statement
Continue statement unlike the break statement is used to skip the remaining part of a
loop and start with next iteration.

Syntax:
continue

XII Std Computer Science 82

12th Computer Science_EM Chapter 6.indd 82 26-12-2022 16:44:46

You might also like