Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 140

1

Computer
B.Tech. Science and
3rd Semester
Engineering

Computational Thinking with Python(21CSXXX)

3RD SEM CSE


Module 1: Introduction to Computational Thinking and Python 5Hrs
  2
Introduction to computational thinking:

3RD SEM CSE


Stages of Computational thinking, Design using Flowcharts, Implementation, Testing
Python Basics: Values, expressions and statements, Conditional execution, Functions Iterations.

 
Module 2: Python Data Structures 6Hrs
 
Python Data Structures: Strings, Arrays, Lists, Tuples, Sets and Dictionaries

Module 3: Python Objects 5Hrs


 
Classes and Objects: Creating classes, Using Objects, Accessing attributes, Classes as Types, Introduction to Multiple
Instances, Inheritance.
Module 4: Exception Handling 5Hrs 3
 
Exception Handling: Try-Except, Exception syntax, examples, Types of exception with except, multiple exceptions with

3RD SEM CSE


except, Try-Finally, Raise exceptions with arguments, Python built-in exceptions, User-defined exceptions, Assertions.

 
Module 5: PYTHON FILES & LIBRARIES 5Hrs
Files: File types, modes, File functions, File attributes, File positions, Looping over file.
Basics of NumPy and Pandas 
Text Books:
► 1. “Python for Everybody-Exploring Data Using Python 3”, Dr. Charles R. Severance, 4
Shroff Publishers; First edition (10 October 2017)

3RD SEM CSE


► 2. “Introduction to Computing & Problem Solving with Python”,Jeeva Jose, P.Sojan Lal,
Khanna Book Publishing; First edition (2019).

Reference Books:
► 1. “Computer Science Using Python: A Computational Problem- Solving Focus”,
Charles Dierbach, Introduction John Wiley, 2012.
► 2. “Introduction to Computation and Programming Using Python”, John V Guttag,
Prentice Hall of India, 2015.
► 3."How to think like a Computer Scientist, Learning with Python", Allen Downey,
Jeffrey Elkner and Chris Meyers, Green Tea Press, 2014.
► 4. “Learning to Program with Python”, Richard L. Halterman, 2011.
Mark Distribution – Integrated Courses (Theory 5
+ Lab)

3RD SEM CSE


Course subject
(100 Marks)

CIA SEE
(60 Marks) (40 Marks)

Criteria Weightage of Marks


Internal Test – I 15
Internal Test – II 15 Exam Total Converted
Computer-Based Test 05
“Or” Mini Project
AAT 05
CIA 60 60
Lab Record 05
Lab Test 10
Attendance 95% – 100% = 05 marks SEE 100 40
90% – 94% = 04 marks
85% – 89% = 03 marks
80% – 84% = 02 marks
75% – 79% = 01 mark
Total 60 marks Passing mark = CIA + SEE = 40
Module 1 6

3RD SEM CSE


Introduction to Computational Thinking and Python:          
Introduction to computational thinking: Stages of Computational thinking, Design
using Flowcharts, Implementation, Testing      
Python Basics: Values, expressions and statements, Conditional execution, Functions
Iterations
Introduction to computational thinking 7

What is computational thinking?


► -Process of approaching a problem in a systematic
manner and creating and expressing a solution such
that it can be carried out by a computer.
4 Stages of computational thinking  8

3RD SEM CSE


► 1. Decomposition
► 2. Pattern recognition 
► 3. Abstraction 
► 4. Algorithms
Decomposition 9

3RD SEM CSE


► Computational thinking involves taking that complex
problem and breaking it down into a series of small, more
manageable problems.
Pattern Recognition 10

3RD SEM CSE


• Each of these smaller problems can then be looked at individually,
considering how similar problems have been solved previously.

• Pattern may exist between sub problems or between different problems.

• Finding similarities or shared characteristics within or between


problems.        

• Same solution can be used for each occurrence of the pattern.


Abstraction 11

3RD SEM CSE


• Focusing only on the important details, while ignoring irrelevant
information.

• Determining what characteristics of problem are important and


filtering out those that are not.
Algorithms 12

3RD SEM CSE


• Simple steps or rules to solve each of the smaller problems can be
designed.

• A step-by-step instructions for performing some task.

• Flowcharts offer a perfect way to represent algorithms


Expressing and Analyzing the Algorithm 13

3RD SEM CSE


► Identifying a general approach to develop algorithm.

► Useful when looking for best solution to a problem

► Evaluate an algorithm and analyse the how its  performance is affected by the size of the input
so that we can choose the best algorithm for problem.
What is Python? 14

3RD SEM CSE


• Python is a general purpose, high level interpreted language with
easy syntax and dynamic semantics.

• Created by Guido Van Rossum in 1989.


Why is Python popular? 15

3RD SEM CSE


► Easy.
► Free.
► Application.
► Library and module for support.
Features of Python 16

3RD SEM CSE


Where is the Python is Used in Industry?
17

3RD SEM CSE


18

3RD SEM CSE


19

3RD SEM CSE


20

3RD SEM CSE


21

3RD SEM CSE


22

3RD SEM CSE


Learning Path 23

3RD SEM CSE


Career Opportunities 24

3RD SEM CSE


► Problem 1: Finding the Largest value in the list of values. 25

Algorithm

3RD SEM CSE


1.At first, largest is the first element in the list
2.Look at each value in the list .if it is greater than current largest, then that value becomes largest
3.After going through entire list, current max is the maximum value in the list.
► Finding a larger value has same pattern as finding the smaller value-Pattern Recognition.
26
► -Finding larger value is a computational problem or it can be a sub problem of a larger

3RD SEM CSE


computational problem.

- Same way we can solve many problems using similar algorithms when we are able to
recognize patterns.
27
► Problem 2: A Client wants to schedule a meeting with  ABC company on Friday 3:00 p.m. So
the client specified time should be checked with meeting scheduled list if not available in the
list the meeting gets scheduled otherwise display message slot not available.

3RD SEM CSE



-Write an algorithm
► -Draw a Flowchart
► Determine the list contains a particular value or not- Scheduling meeting
► To schedule a meeting we have to check with all elements in the list.
28

3RD SEM CSE


► Algorithm: searching for a value
29
► Problem statement: Determine whether a list of values contains a target value.
1.Check each value in the list. if it is equal to the target, then we have to found the value and we

3RD SEM CSE


can stop looking.
2.If we go through entire list and have not found the target, then it is not in the list.

Draw a flowchart
► Issues:
► If the list is longer then, it will take long time for searching. how to solve it?
30
Algorithmic complexity

3RD SEM CSE


► Is expressing number of steps or operations in an algorithm it gives an idea how long it will take to
execute.
► Complexity is expressed as number of elements in the input data
► Measure the comparisons:
► Finding max value in the list
► No of comparisons=7
► No of comparisons=no of elements 1
► Searching for a value
► Target: wen 3 PM
► No of comparisons:8
► If you increase the input size then no of comparisons increases.
► Thus efficiency of algorithm can be increased if the list is ordered.
31
► So instead of linear search we can go for Binary search.

3RD SEM CSE


► Target:25
► No of comparisons:3
► As the no of comparisons are less when the list is ordered than unordered list
Verifying the Algorithm 32

3RD SEM CSE


► Testing means verifying that the algorithm does what we expect it to do.
► Read through each step of the algorithm to check for ambiguity and if there is any
information missing. 
► To ensure that the algorithm is correct, terminates and is general for any input we
devise ‘test cases’ for the algorithm.
Implementation 33

3RD SEM CSE


► Writing a program is the last step of the computational thinking process. 
► It’s the act of expressing an algorithm using a syntax that the computer can
understand. 
► Python programs are used to express the algorithms to a computer as part of a
problem-solving process based on computational thinking.
Testing 34

3RD SEM CSE


► A test case is a set of inputs, conditions, and expected results developed for a
particular computational problem to be solved.
►  A test case is really just a question that you ask of the algorithm.
► The point of executing the test is to make sure the algorithm is correct, that it
terminates and is general for any input.
► Example: Finding the maximum value in the list.
Good (effective) test cases: 35

3RD SEM CSE


► 1) are easy to understand and execute
► 2) are created with the user in mind (what input mistakes will be made? what are
the preconditions?)
► 3) make no assumptions (you already know what it is supposed to do)
► 4) consider the boundaries for a specified range of values.
36

3RD SEM CSE


Test Case # Input Values Expected Result

1 List: 42.3,81.2,56.3,90.6 90.6

2 List: 18, 4, 72, *, 31 Error (or no result)

3 List: 22, -9, 52 Error (or no result)


37

3RD SEM CSE


Python Basics
Values, Expressions
and Statements
Variables and Constants 38
► Fixed values such as numbers, letters and string are called as Constants.

3RD SEM CSE


► As you know that values of constant never change and therefore they are
called as constants.
► Sting constants are always enclosed within single(‘’) or double quotes(“”).
Example:
>>> print(123)
123
>>> print(98.6)
98.6
>>> print('Hello world')
Hello world
►A variable is a named place in the memory where a 39
programmer can store data and later retrieve the data
using the variable name.
100

3RD SEM CSE


Example: X=100 X
90.88
Y=90.88 Y
Python Variable Name Rules :
►Must start with a letter or underscore _
►Must consist of letters, numbers, and underscores
►Case Sensitive
Good: spam, abc, spam23, _speed
Bad: 23spam, #sign, var.12
Different: spam, Spam, SPAM
►Reserved words cannot be used as a variables. 40

and del from None True

3RD SEM CSE


as elif global nonlocal try
whil
assert else If not e
break except import or with
class false In pass yield
continu
e finally Is raise def
for lambda return
Sentences or lines 41

3RD SEM CSE


Assignment statement
x=2
x=x+2 Assignment with
print(x) expression
Print statement
Assignment Statements 42

3RD SEM CSE


► We assign a value to a variable using the assignment
statement (=)
► An assignment statement consists of an expression on the
right-hand side and a variable to store the result.
Example: X 10
X=10
X
X=X+20 10+20
print(X) print statement

► The right hand side is an expression. Once the expression


is evaluated, the result is placed in (assigned to) X.
Expressions 43

►Operators are special symbols that represent computations

3RD SEM CSE


like addition and multiplication.
►The values the operator is applied to are called operands.
►The combination of operators and operands are nothing but
an expression.
►Because of the lack of mathematical symbols on computer
keyboards - we use “computer-speak” to express the classic
math operations
►Asterisk is multiplication
►Exponentiation (raise to a power) looks different than in
math.
Operator Operation 44

+ Addition

3RD SEM CSE


Subtractio
-
n
Multiplicat
*
ion
/ Division
** Power
% Remainder
► Examples
>>> xx = 2 45
>>> xx = xx + 2

3RD SEM CSE


>>> print(xx)
4
>>> yy = 440 * 12
>>> print(yy)
5280
>>> zz = yy / 1000
>>> print(zz)
5.28
What does ‘type’ Mean? 46

3RD SEM CSE


► In Python variables, literals, and constants have a “type”.
► Python knows the difference between an integer number and a string
► For example “+” means “addition” if something is a number and
“concatenate” if something is a string.
>>> ddd = 1 + 4
>>> print(ddd)
5
>>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
► Python knows what “type” everything is 47
► Some operations are prohibited, you cannot add a to a string
► We can ask Python what type something is by using the type()

3RD SEM CSE


function
►>>> eee = 'hello ' + 'there'
►>>> eee = eee + 1
►Traceback (most recent call last): File "<stdin>", line 1, in
<module>TypeError: Can't convert 'int' object to str implicitly
►>>> type(eee)
►<class'str'>
►>>> type('hello')
►<class'str'>
►>>> type(1)
►<class'int'>
Several Types of Numbers
48
► Numbers have two main types

3RD SEM CSE


-Integers: Integers are whole numbers:
-14, -2, 0, 1, 100, 401233
- Floating Point Numbers have decimal parts: -2.5 , 0.0, 98.6, 14.0
>>> xx = 1
>>> type (xx)
<class 'int'>
>>> temp = 98.6
>>> type(temp)
<class'float'>
>>> type(1)
<class 'int'>
>>> type(1.0)
<class'float'>
Type Conversion 49

3RD SEM CSE


► When you put an integer and floating point in an expression,
the integer is implicitly converted to a float.
► You can control this with the built-in functions int() and float()
>>> print(float(99) + 100)
199.0
>>> i = 42
>>> type(i)
<class'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class'float‘>
String Conversion 50

►You can also use int() and float() to convert between

3RD SEM CSE


strings and integers.
►You will get an error if the string does not contain
numeric characters.
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last): File "<stdin>", line 1,
in <module>
TypeError: Can't convert 'int' object to str implicitly
51

3RD SEM CSE


>>> ival = int(sval)
>>> type(ival)
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'x’
User Input 52

3RD SEM CSE


►We can instruct Python to pause and read data from the
user using the input() function.
►The input()
nam function returns
= input('Who area you?
string.')
print('Welcome', nam)

Who are you? Chuck


Welcome Chuck
Converting User Input 53

3RD SEM CSE


►If we want to read a number from the user, we must
convert it from a string to a number using a type
conversion function
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)
Europe floor? 0
US floor 1
54
User Input

3RD SEM CSE


• We can instruct Python
to pause and read data
from the user using the nam = raw_input(‘Who are you?’)
raw_input function print 'Welcome', nam
• The raw_input function
returns a string Who are you? Chuck
Welcome Chuck
55
Converting User Input

3RD SEM CSE


• If we want to read a
number from the user,
we must convert it from inp = raw_input(‘Europe floor?’)
a string to a number usf = int(inp) + 1
using a type conversion print 'US floor', usf
function
• Later we will deal with Europe floor? 0
bad input data US floor 1
Accepting User Input
&
Type Conversion
Accepting User Input
❖ TO ACCEPT AN INPUT FROM A USER WE HAVE TO USE INPUT() FUNCTION.

❖ THE INPUT() FUNCTION PAUSES YOUR PROGRAM AND WAITS FOR THE USER TO


ENTER SOME TEXT. ONCE PYTHON RECEIVES THE USER’S INPUT, IT ASSIGNS
THAT INPUT TO A VARIABLE TO MAKE IT CONVENIENT FOR YOU TO WORK WITH.

❖ TO MAKE THE PROGRAM MORE FLEXIBLE OR DYNAMIC, WE SHOULD MAKE USE


OF THE INPUT() FUNCTION. 
Accepting User Input
When you want to retrieve text from the user, you use the
input function.
Example

NAME = INPUT("WHAT IS YOUR NAME: ")


PRINT(NAME)
This is the prompt that the user sees before they start typing.

That variable can then be printed just like any other variable.

Whatever the user types is then stored in a variable called


name.
Accepting User Input

Example

NAME = INPUT("WHAT IS YOUR NAME: ")


PRINT(NAME)

Output
Activity

Write a program to display the result of a student. You should get the name of the student,
marks obtained in programming, English, and Mathematics from the user. Finally, display
the result. The sample output is attached below.

Example
Your name : Sonam Dorji
Marks in Dzongkha:98
Marks in English :88
Marks in Mathematics:100
--------------------------
-
Name : Dorji Dema
Dzongkha: 98
English: 88
Mathematics: 100
Type Conversion
• When we use the input() function, python interprets everything the user enters as a string.
• But we can also accept the input type based on program requirements. If we are writing a
program to do the simple mathematical calculation, our program should accept only numbers,
i.E. Either integer or float. 
• Similarly, if we are writing a program to collect the name of the students, our program should
accept input as a string type.
Type Conversion
• WE CAN ACHIEVE THIS BY CONVERTING THE TYPE OF DATA USING A
BUILT-IN DATA TYPE FUNCTIONS SUCH AS INT(), FLOAT(), AND STRING(),
AND IT SHOULD BE PLACED BEFORE THE INPUT() FUNCTION.
Converts user input into integer data type
Example
age = int(input("Enter your age:"))
print(f"Your age is {age}")

Output
Enter your age:30
Your age is 30
Type Conversion
• SIMILARLY, WE CAN DO THE SAME WITH OTHER DATA TYPES USING
ITS BUILT-IN FUNCTIONS.

Example
height= float(input("Enter your height:"))
print(f"Your height is {height}")

Output
Enter your height:30
Your height is 30.0
Checking the type of data
TO CHECK THE TYPE OF A DATA, USE BUILT-IN FUNCTION TYPE().

Example

name = input("What is your name: ")


print("Your name is", name, "And it's data type is", type(name))

Output String
What is your name: Dawa
Your name is Dawa And it's data type is <class 'str'>
Activity
Write a program that accepts data from a user. Your program should accept your name, age,
and height. A name should be a string, age should be an integer and the height should be
float.

Example
Activity

Write a program that accepts your name and five subjects mark.
Print an output where you will see your name and five subjects
mark including your average mark.
67
Comments in Python

3RD SEM CSE


• Anything after a # is ignored by Python

• Why comment?

• Describe what is going to happen in a sequence of code

• Document who wrote the code or other ancillary information

• Turn off a line of code - perhaps temporarily


# Get the name of the file and open it
name = raw_input('Enter file:')
handle = open(name, 'r') 68
text = handle.read()
words = text.split()

3RD SEM CSE


# Count word frequency
counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1

# Find the most common word


bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count

# All done
print bigword, bigcount
69
Multi – Line Comments in Python

3RD SEM CSE


To have a multi-line comment in Python, we use triple single quotes at the
beginning and at the end of the comment, as shown below.

'''This is a

multi-line

comment

'''
Exercise
70

3RD SEM CSE


Write a program to prompt the user for hours and rate
per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Output Formatting in Python
outline

Four Ways of Output Formatting


►Manual string formatting
►Formatted string literals or f-strings
►The string format() method
►printf() style in C
What is mean by
Output formatting?
The fancier way of printing an output is called as output formatting.
It gives more control while printing an output.
The four ways to print an output in python are;
1. Manual String Formatting
2. Formatted string literals or f-strings
3. The String format() Method
4. Old string formatting or printf() style in C
1. Manual string formatting

To display objects to the output console, pass them as a comma-separated


list of argument to print() function.
Example:

Main.py
Output
lang = “ Python" Welcome to Python Programming
print("Welcome to", lang, "Programming") Printing lang three times:
print("Printing lang three times:", lang*3) Python Python Python
1. Manual string formatting
Cont.

The print() function takes two optional arguments that provide control over


the output we actually want, i.e. sep and end keyword; sep keyword
argument causes objects to be separated by a string passed as a value to it.
The end keyword argument causes output to be terminated by a string passed
as a value to it instead of the default newline.

Main.py
print("ENG", "MATH", "DZO", "GEO", sep="|", end="***")

Output

ENG|MATH|DZO|GEO***
2. Formatted string literals or f-strings
Formatted string literals (also called f-strings for short) let you include the value
of Python expressions inside a string by prefixing the string with f or F and writing
expressions as {expression}.
It works only in python version 3.6 and above.
Example:

Output
Main.py
Dawa you are 23 years old
name = "Dawa“
age = 23
print(f"{name} you are {age} years old")
3. The string format() method

Basic usage of the format() method looks like this;


Main.py
name= "Dawa"
age = "23"
print ("{} you are {} years old".format(name, age))

Output

Dawa you are 23 years old


Cont. 3. The string format() method

We can also pass a number inside a bracket. A number in the brackets can
be used to refer to the position of the object passed into the format()
method.
Main.py

print('{0} {2} {3} {1}'.format(5,4,3,7))

Output

5 3 7 4
Cont. 3. The string format() method

The additional feature of the format() method is to control the floating-


point in the number;

Main.py

PI = 3.14159265
print('The value of PI is {:.2f}'.format(PI))

Output
The value of PI is 3.14
4. Old string formatting or printf() style in C

String objects have one unique built-in operation: the % operator (modulo). This
is also known as the string formatting or interpolation operator. Given format %
values (where the format is a string), % conversion specifications in format are
replaced with zero or more elements of values.
Example:

Main.py
print('%d %s cost Nu.%.2f' % (6, 'bananas', 60))

Output
6 bananas cost Nu.60.00
1. Write a maximum of 5 lines of the python program describing yourself. Your program should
have three variables declared (Ex. name, age, and height). 
The expected output:
Conditional Statement 82

3RD SEM CSE


1. if - else statement
2. Nested if statement
3. elif statement
4. Multiple condition in if and elif statement
5. pass statement.
Introduction 83

1. The conditional statements in programming languages decide the direction of the flow

3RD SEM CSE


of program execution. It is used for decision-making.
2. The decision is made based on the condition provided to the if and elif
statement(conditional statements).
3. However, if none of the conditions gets fulfilled, else part will be executed.
if-else statement 84

3RD SEM CSE


► An if statement is used for conditional execution. It is used to decide whether a certain
statement or block of statements will be executed or not i.e.
► if a certain condition is true then a block of statement is executed otherwise else
statement is executed if present.

Syntax:

if condition:
Statement
***else statement will not take any condition. Else
else:
statement will be executed only if the if statement
Statement
condition fails.
You should know comparison operators to write condition 85

3RD SEM CSE


if - else Example 86

3RD SEM CSE


age = int(input("Enter your age: "))
if age <= 12:
print("You are a kid!")
else:
print("You are an adult!")

Output: # Output sample 1


Enter your age: 10
You are a kid!
=================
# Output sample 2
Enter your age: 15
You are an adult!
Activity 87

3RD SEM CSE


Write a python program to check whether you are eligible to vote or not?

Your program should get the age of the voter from the user and if their age is 18 and above let them vote
otherwise deny them from voting.
elif statement 88
► The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation and used when there

3RD SEM CSE


are multiple conditions to be checked.

► If the condition is not true, it will check for elif condition. Otherwise, it will directly execute the else
statement.
Syntax:

if condition 1:
Statement
elif condition 2:
Statement
elif condition 3:
Statement
elif condition can continue………
Example 89

age = int(input("Enter your age:"))

3RD SEM CSE


Output:
if age <= 12:
print("You are a kid!")
# Possible output
elif age == 18:
print("you are 18 and in adulthood.") Enter your age:10
You are a kid!
elif age >= 19: =================
print("You are above 18.") Enter your age:18
you are 18 and in
adulthood.
=================
Enter your age:20
You are above 18.
Activity 90

3RD SEM CSE


1. Traffic light:
Write a python program that will check for the
following conditions:
● If the light is green – Car is allowed to go
● If the light is yellow – Car has to wait
● If the light is red – Car has to stop
● Other signal - unrecognized signal. Example black,
blue, etc...
Activity 91
► 2. Students Grade
Write a program to check students' grades. Your program should fulfill the following conditions:

3RD SEM CSE


1. Grade A - Outstanding
2. Grade B - Excellent
3. Grade C - Very Good
4. Grade D - Good
5. Grade E – Satisfactory
►6. Others - Unrecognized
A program should also ask to enter the student's name, class, and section. The expected output is
attached below.
Expected output:
Multiple condition in if and elif statement 92

The if and elif statement can execute multiple conditions at the same time. Multiple conditions can be

3RD SEM CSE


used using logical operators.

You should know logical operators to write multiple condition


Example 93
age = int(input("Enter your age:"))

3RD SEM CSE


if age < 12 and age > 0:
print("You are a kid!")
elif age > 12 and age < 25:
print("you are a youth!") Output:
elif age > 25 and age < 54:
print("you are a man!")
else:
print("You are an old man!") # Output
Enter your age:8
You are a kid!
=================
Enter your age:23
you are a youth!
=================
Enter your age:45
you are a man!
=================
Enter your age:70
You are an old man!
Activity 94
Student result with grade
►Modify the earlier program students’ grades in such a way that they should

3RD SEM CSE


take in five subject marks. Find the total mark and their percentage. Your
program should check for the following conditions:
• If the percentage falls below 45, they are considered fail. Expected output:

• If the percentage is between 45 and 60, grade them as pass.


• If the percentage is between 60 and 75, grade them as good.
• If the percentage is between 75 and 85, grade them as very good.
• If the percentage is between 85 and 100, grade them excellent.
• If the percentage is below zero or above 100, it’s an error.
Nested if statement 95

3RD SEM CSE


Nested if statements mean an if statement inside another if statement.
Syntax:

if condition 1:
Statements
if condition 1.1:
Statement
else:
Statement
else:
Statement
Example 96
age = int(input("Enter your age:"))

3RD SEM CSE


if age <= 12:
Output:
print("You are a kid!")
if age < 5: #nested if condition
# Three possible output
print("and also below 5!") Enter your age:3
You are a kid!
else: and also below 5!
print("but not below 5.") =================
Enter your age:7
else: You are a kid!
but not below 5.
print("you are above 12!") =================
Enter your age:20
you are above 12!
Activity 97
►Write a program to trace your subject mark. Your program should fulfill the following conditions:

3RD SEM CSE


• If the subject mark is below 0 and above 100, print “error: mark should be between 0 and 100 only”
• Students will fail in the subject if their mark is below 50.
• Students will pass in the subject if they score 50 and above.
• If subject mark is between 50 and 60, grade student as good.
• If subject mark is between 60 and 80, grade student as very good.
• If subject mark is between 80 and 100, grade student as outstanding.
►Make sure to print their mark in every statement to prove that the condition is fulfilled. Moreover, name,
class, and section should be also displayed along with the marks and their grade.
Pass statement 98

► The pass statement does nothing. It can be used when a statement is required syntactically correct but

3RD SEM CSE


the program requires no action.

► The pass can be also used as a placeholder for a function or conditional body when you are working on a
new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored.
Example
age = 13 Output:
if age <= 12:
In the above example, nothing will be printed and it
pass won’t generate any error.
Loops in python programming 99

3RD SEM CSE


➔ For
➔ while
100
Outline

3RD SEM CSE


❖ For loop
❖ Range function
❖ Break, continue, and Pass statement
❖ Booleans
❖ While loop
❖ Nested loop
for Loop 101

3RD SEM CSE


The for loop in python iterates over the items of any sequence be it a list or a string.
Moreover, using for loop in the program will minimize the line of code.
Points to keep in mind while using for loop in python:
➔ It should always start with for keyword and should end with a colon(:).
➔ The statements inside the loop should be indented(four spacebars).

Syntax:
For iterator_variable in sequence:
statement(s)
102
Example

3RD SEM CSE


This is actually a temporary
variable which store the
number of iteration
Code:
for i in range(6):
print(“Hello World!”)
Number of times you want to
execute the statement
Output:
print(“Hello World!”)
print(“Hello World!”)
print(“Hello World!”)
print(“Hello World!”)
print(“Hello World!”)
Range function 103

3RD SEM CSE


To iterate over a sequence of numbers, the built-in function range() comes in handy.
It generates arithmetic progressions. For example, if we want to print a whole number
from 0 to 10, it can be done using a range(11) function in a for loop.
In a range() function we can also define an optional start and the endpoint to the
sequence. The start is always included while the endpoint is always excluded.
Example:
for i in range(1, 6):
print("Hello World!")

Output: Prints Hello World! five times


Range function 104
The range() function also takes in another optional parameter i.e. step size. Passing step

3RD SEM CSE


size in a range() function is important when you want to print the value uniformly with a
certain interval.
Step size is always passed as a third parameter where the first parameter is the starting
point and the second parameter is the ending point. And if the step_size is not provided it
will take 1 as a default step_size.
Example:
for i in range(0,20, 2):
print(i)
Output: prints all the even numbers till 20
Activity 105
Sum of numbers

3RD SEM CSE


-Write a program to find the sum of all the numbers less than a number entered by the user.
Display the sum.
Expected Output:
Break, Continue, & Pass Statement 106
(Loop control statement)

3RD SEM CSE


➔ A break statement is used to immediately terminate a loop.
➔ A continue statement is used to skip out future commands inside a loop and return to
the top of the loop.
➔ A Pass is a null operation — when it is executed, nothing happens. It is useful as a
placeholder when a statement is required syntactically when no code needs to be
executed.
➔ These statements can be used with for or while loops.
107
Break, Continue, & Pass Statement (Loop control statement)

3RD SEM CSE


Example:

Continue Pass
Break
for i in range(5): for i in range(10):
for i in range(10):
if i == 3: Pass
if i == 3:
continue
break
print(i)
print(i)
Output:
0
Output:
1
0
1 2 Output:
2 4 Nothing will be printed
Activity 108

3RD SEM CSE


Magic Number
Write a program that makes the user guess a particular number between 1 and 100.
Save the number to be guessed in a variable called magic_number.
If the user guesses a number higher than the secret number, you should say Too
high!. Similarly, you should say Too low! if they guess a number lower than the
secret number. Once they guess the number, say Correct!
Expected Output:
Boolean 109

3RD SEM CSE


A boolean is a value that can be either True or False.
Example:
brought_food = True
brought_drink = False

- Boolean variables don't have quotation marks.


- The values must start with capital letters.
While Loop 110

➔ while loop repeatedly carries out a target statement while the condition is true. The loop

3RD SEM CSE


iterates as long as the defined condition is True.
➔ When the condition becomes false, program control passes to the line immediately
following the loop.
Example:
while True:
print("I am a programmer")
break
while False:
print("Not printed because while the condition is already False")
break
Output:
I am a programmer
While Loop 111
Example:

3RD SEM CSE


x = 1
while x > 0:
print ("Hello!")
x = x - 1
print ("I like Python.")

Output:
Hello!
I like Python.
Activity 112

3RD SEM CSE


Guess the number
Write a program where the user enters a number. If the number matches the number,
acknowledge the user and stop the program. If the number does not match, keep asking for
the next number.
Expected Output:
Nested Loop 113
Loop within a loop is called a nested loop.

3RD SEM CSE


➔ For loop within for loop is called a nested for loop.
➔ While loop within while loop is called as nested while loop.

Example: Nested while loop


Example: Nested for loop i = 1
for i in range(4): j = 5
for j in range(3): while i < 4:
print ("Hello!") while j < 8:
print(i,",", j)
j = j + 1
i = i + 1
Nested Loop(Example) 114
Output:
for i in range(4): 5

3RD SEM CSE


4
x = 5 3
while x > 1: 2
5
print (x) 4
3
x = x - 1 2
5
4
3
2
5
4
3
2
Activity 115
Rolling a dice

3RD SEM CSE


Write a program that will print out all combinations that can be made when 2 dice are
rolled. And should continue until all values up to 6, and 6 are printed. (Hint: You should
have a space after each comma!)
Expected Output:
Coding Challenge 116
Multiplication Table:

3RD SEM CSE


Write a program to print a multiplication table to 12 of a given number.
Expected Output:
117
Coding Challenge

3RD SEM CSE


Printing pattern:
Write a program to print the following two patterns implementing the nested loop
concept.
Functions 118

3RD SEM CSE


► What is Function?
► Why we need Functions?
► What is Function call?
► How python gives different way to write function?
We have already used several functions 119

3RD SEM CSE


► When we have written first program of python we have used function.
print(“Hello World”) here print is function and Hello World is arguments we will
see it later part.
► Python gives huge set of library function and very easy to use.
Stored (and reused) Steps 120

3RD SEM CSE


def
hello(): Program:
print 'Hello' Output:
def thing():
print 'Fun' print 'Hello’
print 'Fun’ Hello
hello() Fun
thing()
print 'Zip’ Zip
print “Zip” thing()
Hello
Fun
hello()
We call these reusable pieces of code “functions”.
Python Functions 121

3RD SEM CSE


• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python - input(), type(), float(), int() ...
• Functions that we define ourselves and then use
• We treat the built-in function names as "new" reserved words (i.e. we avoid
them as variable names)
Function Definition 122

3RD SEM CSE


• In Python a function is some reusable code that takes arguments(s) as input
does some computation and then returns a result or results
• We define a function using the def reserved word
• We call/invoke the function by using the function name, parenthesis and
arguments in an expression
Argument 123

big = max('Hello world')

3RD SEM CSE


Assignment
'w'
Result
>>> big = max('Hello world')
>>> print big
w
>>> tiny = min('Hello world')
>>> print tiny
>>>
Max Function 124

3RD SEM CSE


A function is some stored
>>> big = max('Hello world') code that we use. A
>>> print big'w' function takes some input
and produces an output.

“Hello world” max() ‘w’


(a string)
(a string) function

Guido wrote this code


Max Function 125

3RD SEM CSE


A function is some stored
>>> big = max('Hello world') code that we use. A
>>> print big'w' function takes some input
and produces an output.

def max(inp):
blah
“Hello world” blah ‘w’
(a string) for x in y: (a string)
blah
blah

Guido wrote this code


Type Conversions 126
>>> print float(99) / 100
0.99

3RD SEM CSE


>>> i = 42
• When you put an integer and floating point
in an expression the integer is implicitly >>> type(i)
converted to a float <type 'int'>
• You can control this with the built in >>> f = float(i)
functions int() and float() >>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
>>>
String Conversions >>> sval = '123'
127
>>> type(sval)
<type 'str'>

3RD SEM CSE


>>> print sval + 1
• You can also use int() and float() to Traceback (most recent call last):
convert between strings and integers File "<stdin>", line 1, in <module>
• You will get an error if the string TypeError: cannot concatenate 'str' and 'int'
does not contain numeric characters >>> ival = int(sval)
>>> type(ival)
<type 'int'>
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Building our Own Functions 128

3RD SEM CSE


• We create a new function using the def keyword followed by optional parameters in
parenthesis.
• We indent the body of the function
• This defines the function but does not execute the body of the function

def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'
print "I'm a lumberjack, and I'm 129
okay."
print_lyrics():
x=5 print 'I sleep all night and I work all day.'
print 'Hello'

3RD SEM CSE


def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.' Hello
Yo
print 'Yo' 7
x=x+2
print x
Definitions and Uses 130

3RD SEM CSE


• Once we have defined a function, we can call (or invoke) it as many times as
we like
• This is the store and reuse pattern
x=5 131
print 'Hello'

3RD SEM CSE


def print_lyrics():
print "I'm a lumberjack, and I'm okay.”
print 'I sleep all night and I work all day.'

print 'Yo'
print_lyrics() Hello
x=x+2 Yo
print x I'm a lumberjack, and I'm okay.I
sleep all night and I work all day.
7
Arguments 132

3RD SEM CSE


• An argument is a value we pass into the function as its input when we call the function
• We use arguments so we can direct the function to do different kinds of work when we call it
at different times
• We put the arguments in parenthesis after the name of the function

big = max('Hello world')


Argument
Parameters 133
>>> def greet(lang):
... if lang == 'es':

3RD SEM CSE


► A parameter is a variable which we ... print 'Hola’
use in the function definition that is ... elif lang == 'fr':
a “handle” that allows the code in the ... print 'Bonjour’
function to access the arguments for
a particular function invocation. ... else:
... print 'Hello’
...
>>> greet('en')Hello
>>> greet('es')Hola
>>> greet('fr')Bonjour
>>>
Return Values 134

3RD SEM CSE


• Often a function will take its arguments, do some computation and return a value to be used as
the value of the function call in the calling expression. The return keyword is used for this.

def greet():
return "Hello” Hello Glenn
Hello Sally
print greet(), "Glenn”
print greet(), "Sally"
Return Value >>> def greet(lang): 135
... if lang == 'es':
... return 'Hola’

3RD SEM CSE


► A “fruitful” function is one that ... elif lang == 'fr':
produces a result (or return value) ... return 'Bonjour’
► The return statement ends the ... else:
function execution and “sends back” ... return 'Hello’
the result of the function
... >>> print greet('en'),'Glenn’
Hello Glenn
>>> print greet('es'),'Sally’
Hola Sally
>>> print greet('fr'),'Michael’
Bonjour Michael
>>>
Arguments, Parameters, and Results 136

3RD SEM CSE


>>> big = max('Hello world') Parameter
>>> print big'w'
def max(inp):
blah
“Hello world” blah ‘w’
for x in y:
Argument blah
Result
blah
return ‘w’
Multiple Parameters / Arguments 137

3RD SEM CSE


• We can define more than one
parameter in the function definition
• We simply add more arguments when
we call the function def addtwo(a, b):
• We match the number and order of added = a + b
arguments and parameters
return added
x = addtwo(3, 5)
print x
Void (non-fruitful) Functions 138

3RD SEM CSE


• When a function does not return a value, we call it a "void" function
• Functions that return values are "fruitful" functions
• Void functions are "not fruitful"
To function or not to function... 139

3RD SEM CSE


► Organize your code into “paragraphs” - capture a complete thought and “name
it”
► Don’t repeat yourself - make it work once and then reuse it
► If something gets too long or complex, break up logical chunks and put those
chunks in functions
► Make a library of common stuff that you do over and over - perhaps share this
with your friends...
Exercise
140

3RD SEM CSE


Rewrite your pay computation with time-and-a-half for
overtime and create a function called computepay
which takes two parameters ( hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0

475 = 40 * 10 + 5 * 15

You might also like