0% found this document useful (0 votes)
59 views185 pages

Python Basics: Introduction and Syntax

The document provides an introduction to Python, highlighting its versatility as a programming language suitable for various applications such as web and game development, AI, and automation. It covers fundamental concepts including Python's syntax, indentation, comments, variables, data types, and methods for outputting and formatting data. Additionally, it explains the importance of variable naming conventions and the use of global variables within functions.

Uploaded by

ajayishereaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views185 pages

Python Basics: Introduction and Syntax

The document provides an introduction to Python, highlighting its versatility as a programming language suitable for various applications such as web and game development, AI, and automation. It covers fundamental concepts including Python's syntax, indentation, comments, variables, data types, and methods for outputting and formatting data. Additionally, it explains the importance of variable naming conventions and the use of global variables within functions.

Uploaded by

ajayishereaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Python Basics

By:
Hithesh M
Asst. Professor
Dept. of. Mech
SMVITM - Bantakal

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/202 1


5
Python Introduction

What is Python? It is used for:


• Python is a popular programming language. • web development (server-side)
• Python is beginner friendly programming • software development
language. •game development
• mathematics
• It was created by Guido van Rossum, and • system scripting
released in 1991. •AI-ML/DS
•Automation
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 2
Why Python?

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 4


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 5
python3

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 6


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 7
IDLE
• Python IDLE (Integrated Development and Learning
Environment)
• IDLE offers features like syntax highlighting, code
completion, and easy access to Python
documentation.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 13


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 14
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 15
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 16


Python will give you an error if you
skip the indentation:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 17


The number of spaces is up to you as a programmer, the
most common use is four, but it has to be at least one.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 18


You have to use the same number of spaces in the same
block of code, otherwise Python will give you an error:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 19


Python Comments(#)

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing
code.

Creating a Comment
Comments starts with a #, and Python will ignore them:
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 20
Comments can be placed at the end of a line, and Python
will ignore the rest of the line:

A comment does not have to be text that


explains the code, it can also be used to
prevent Python from executing code:
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 21
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 22


you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable,
you can add a multiline string (triple quotes) in your code, and place your
comment inside it:

As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 23
Python Variables
Variables are containers for storing data values.

Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 24


Variables do not need to be declared with any
particular type, and can even change type after they have
been set.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 25


Casting

• If you want to specify the data type of a variable, this can


be done with casting.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 26


Get the Type

You can get the data type of a variable with the type() function.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 27


Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 28


Case-Sensitive
Variable names are case-sensitive.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 29


Python - Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for Python variables:


• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• A variable name cannot be any of the Python keywords.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 30
Legal variable names:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 31


• 2myvar = "OK"
• my-var = "YES"
• my var = "NO"

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 32


Illegal variable names:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 33


Multi Words Variable Names

Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:

• Camel Case: Each word, except the first, starts with a capital
letter
myVariableName = “Udupi"
• Pascal Case: Each word starts with a capital letter
MyVariableName = “Mangalore"
• Snake Case: Each word is separated by an underscore character
my_variable_name = “Bangalore"
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 34
Variables - Assign Multiple Values
Many Values to Multiple Variables:

Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

NOTE: Make sure the number of


variables matches the number of
values, or else you will get an error.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 35
One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

x = y = z = "Orange"
print(x)
print(y)
print(z)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 36


Output Variables

The Python print() function is often used to output variables.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 37


In the print() function, you output multiple variables, separated by a
comma:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 38


You can also use the + operator to output multiple variables:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 39


For numbers, the + character works as a mathematical operator:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 40


In the print() function, when you try to combine a string and
a number with the + operator, Python will give you an error:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 41


The best way to output multiple variables in the print() function is to
separate them with commas, which even support different data types:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 42


Output formatting

Sometimes we would like to format our output to make it look


attractive. This can be done by using the [Link]() method.
Here, the curly braces {} are used as placeholders. We can specify
the order in which they are printed by using numbers (tuple index).
x=5
y = 10
print('The value of x is {} and y is {}'.format(x,y))
OUTPUT>>The value of x is 5 and y is 10
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 43
Global Variables

• Variables that are created


outside of a function.
• Global variables can be
used by everyone, both
inside of functions and
outside.
• EX: Create a variable
outside of a function, and
use it inside the function
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 44
If you create a variable with the same name inside a function,
this variable will be local, and can only be used inside the
function. The global variable with the same name will remain
as it was, global and with the original value.
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 45
The global Keyword

when you create a variable inside


a function, that variable is local, def myfunc():
and can only be used inside that global x
x = "fantastic"
function.
To create a global variable inside myfunc()
a function, you can use
the global keyword. print("Python is " +
x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 46
If you use the global keyword, the variable belongs to the global scope

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 47


use the global keyword if you want to change a global variable inside
a function.

x = "awesome"
To change the value of a global
variable inside a function, refer
def myfunc():
to the variable by using
global x
the global keyword:
x = "fantastic"

myfunc()

Shri Madhwa Vadiraja Institute of Technology and Management print("Python is " + x)


11/07/2025 48
Python Data Types

Built-in Data Types


• Variables can store data of different types, and different
types can do different things.
• Python has the following data types built-in by default, in
these categories:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 49


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 50
Getting the Data Type
You can get the data type of any object by using the type() function:

Print the data type of the variable x:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 51


Setting the Specific Data Type

• If you want to specify


the data type, you can
use the following
constructor functions:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 52


Python Numbers
The integer, floating-Point, and String data types

• A data type is a category for values, and every value belongs to exactly
one data type.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 53


Python Numbers
The integer, floating-Point, and String data types

• The integer (or int) data type indicates values that are whole numbers.
• Numbers with a decimal point, such as 3.14, are called floating-point
numbers (or floats).
• Python programs can also have text values called strings.
• Always surround your string in single quote (') characters
(as in 'Hello' or 'Goodbye cruel world!') so Python knows where the
string begins and ends. You can even have a string with no characters in it,
‘’, called a blank string.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 54
(')
>>> 'Hello world!
SyntaxError: EOL while scanning string literal

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 55


Type Conversion

You can convert from one type to another with the int(), float(),
and str() methods: print(a)
x = 1 # int #convert from float to int: print(b)
y = 2.8 # float b = int(y) print(c)
z = 1j # complex
#convert from int to complex: print(type(a))
#convert from int to float: c = complex(x) print(type(b))
a = float(x) print(type(c))
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 56
Type Conversion

OUTPUT: 1.0
2
(1+0j)

<class 'float’>
<class 'int’>
<class
'complex'>
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 57
Python Strings
Strings in python are surrounded by either single quotation
marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 58


Assign String to a Variable

Assigning a string to a variable is done with the variable name


followed by an equal sign and the string:

a = "Hello"
print(a)

output: Hello
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 59
Multiline Strings
• You can assign a multiline string to a variable by using
three quotes: “ or ‘

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 60


String Concatenation and Replication
• String Concatenation:
To concatenate, or combine, two strings you can use the +
operator.

Merge variable a with variable b into variable c:


a = "Hello"
b = "World"
c=a+b
print(c)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 61
To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 62


Replication
• If you try to use the + operator on a string and an integer value, Python
will not know how to handle this, and it will display an error message.
>>> ‘Hello' + 42
The error message Can't convert 'int' object to str implicitly means that
Python thought you were trying to concatenate an integer to the string
’Hello’.
The * operator is used for multiplication when it operates on two inte-
ger or floating-point values. But when the * operator is used on one string
value and one integer value, it becomes the string replication operator.
'Hello' * 5
‘HelloHelloHelloHelloHello'

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 63


• The expression evaluates down to a single string value that repeats the
original a number of times equal to the integer value. String replication is
a useful trick, but it’s not used as often as string concatenation.

The * operator can be used with only two numeric values (for multipli-
cation) or one string value and one integer value (for string replication).
Otherwise, Python will just display an error message.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 64


Your First Program
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') #ask for their name

myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') #ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a
year.')

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 65


Output:

Hello world!
What is your name?
Al
It is good to meet you, Al
The length of your name is:
2
What is your age?
4
You will be 5 in a year.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 66
Dissecting your Program
Comments: The following line is called a comment.
# This program says hello and asks for my name.

The print() Function: The print() function displays the string value
inside the parentheses on the screen.
print('Hello world!')
print('What is your name?') # ask for their name
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 67
The print() Function

The line print('Hello world!') means Print out the text in the
string 'Hello world!’.
When Python executes this line, you say that Python is calling the
print()function and the string value is being passed to the function.
A value that is passed to a function call is an argument.
Notice that the quotes are not printed to the screen. They just mark where the
string begins and ends; they are not part of the string value.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 68


The input() Function
• The input() function waits for the user to type some text on the keyboard and
press enter.
• Ex: myName = input()

You can think of the input() function call as an expression that evalu-
ates to whatever string the user typed in. If the user entered 'Al', then the
expression would evaluate to myName = 'Al'

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 69


Printing the User’s Name
myName = input()
print('It is good to meet you, ' + myName)

Remember that expressions can always evaluate to a single value. If 'Al'


is the value stored in myName on the previous line, then this expression
evaluates to 'It is good to meet you, Al'. This single string value is then
passed to print(), which prints it on the screen.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 70
The len() Function
• You can pass the len() function a string value (or a variable containing
a string), and the function evaluates to the integer value of the number of
characters in that string.
print('The length of your name is:')
print(len(myName))
Ex:>>> len('hello')
5

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 71


The str(), int(), and float() Functions
• If you want to concatenate an integer such as 29 with a string to pass to
print(), you’ll need to get the value '29', which is the string form of
29.
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 72


>>> str(0)
'0’
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99’)
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
Shri Madhwa Vadiraja Institute of Technology and Management
>>> float(10) 11/07/2025 73
10.0
2
F l o w C o n t r ol
Flow control statements can decide which Python instructions to execute
under which conditions.
EX: In a flowchart, there is usually more than one way to go from the start
to the end. The same is true for lines of code in a computer program. Flow-
charts represent these branching points with diamonds, while the other
steps are represented with rectangles. The starting and ending steps are
represented with rounded rectangles.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 74


A flowchart to tell you what to do if it is raining

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 75


Python Conditions and If statements
(comparison operators)
Python supports the usual logical conditions from
mathematics:
Comparison operators compare two values and evaluate
• Equals: a == b down to a single Boolean value.
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 76
These conditions can be used in several ways, most commonly in
"if statements" and loops.

An "if statement" is written by using the if keyword.


a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as


part of the if statement to test whether b is greater than a.
As a is 33, and b is 200, we know that 200 is greater than 33, and
so we print to screen that "b is greater than a".
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 77
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 78
Indentation

• Python relies on indentation (whitespace at the beginning


of a line) to define scope in the code. Other programming
languages often use curly-brackets for this purpose.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 79


Elif
The elif keyword is Python's way of saying "if the previous
conditions were not true, then try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so
we print to screen that "a and b are equal".
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 80
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 81
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is greater than b, so the first condition is
else: not true, also the elif condition is not true, so we go to
print("a is greater than b") the else condition and print to screen that "a is greater
than b".
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 82
You can also have an else without the elif:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 83


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 84
Short Hand If
If you have only one statement to execute, you can put it on the
same line as the if statement.

One line if statement:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 85


Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you
can put it all on the same line:

One line if else statement:


a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 86


Boolean Values

Booleans represent one of two values: True or False.


In programming you often need to know if an expression
is True or False.
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and
Python returns the Boolean answer:
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 87
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 88
When you run a condition in an if statement, Python returns True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 89


These operators evaluate to True or False depending on the values you
give them. Let’s try some operators now, starting with == and !=.

>>> 42 == 42
True
>>> 42 == 99
False
>>> 2 != 3
True
>>> 2 != 2
False

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 90


>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello’
False
>>> 'dog' != 'cat'
True
>>> True == True
True
>>> True != False
True
>>> 42 == 42.0
True
>>> 42 == '42'
False
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 91
>>> 42 < 100
True
>>> 42 > 100
False
>>> 42 < 42
False
>>> coconutCount = 42
>>> coconutCount <= 42
True
>>> myAge = 32
>>> myAge >= 30
True
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 92
Boolean operators
The three Boolean operators (and, or, and not) are used to
compare Boolean values.
Like comparison operators, they evaluate these expressions down
to a Boolean value.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 93


Binary Boolean Operators
(AND) Returns True if both statements are true
The and and or operators always take two Boolean values (or
expressions), so they’re considered binary operators.

The and operator evaluates an expression to True if both Boolean values


are True; otherwise, it evaluates to False.
>>> True and True
True
>>> True and False
Shri Madhwa Vadiraja Institute of Technology and Management
False 11/07/2025 94
A truth table shows every possible result of a
Boolean operator.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 95


x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 96


(OR) Returns True if one of the statements is true

On the other hand, the or operator evaluates an expression to True if


either of the two Boolean values is True. If both are False, it evaluates to
False.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 97


You can see every possible outcome of the
or operator in its truth table:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 98


x=5
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater than
3, but 5 is not less than 4)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 99


The not Operator
Reverse the result, returns False if the result is true

Unlike and and or, the not operator operates on only one Boolean value (or
expression). The not operator simply evaluates to the opposite Boolean value.

x=5

print(not(x > 3 and x < 10))

# returns False because not is used to reverse


the result
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 100
The not Operator’s Truth Table

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 101


Mixing Boolean and comparison operators
• Since the comparison operators evaluate to Boolean values, you can
use them in expressions with the Boolean operators.
• Recall that the and, or, and not operators are called Boolean
operators because they always operate on the Boolean values True and
False.
• While expressions like 4 < 5 aren’t Boolean values, they are
expressions that evaluate down to Boolean values.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 102


>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 103


The computer will evaluate the left expression
first, and then it will evaluate the right
expression.

When it knows the Boolean value for each, it will


then evaluate the whole expression down to one
Boolean value.

You can think of the computer’s evaluation


process for(4 < 5) and (5 < 6)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 104


You can also use multiple Boolean operators in an expression, along
with the comparison operators.

2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2


True
NOTE: The Boolean operators have an order of operations just like the
math operators do.
After any math and comparison operators evaluate, Python evaluates the
not operators first, then the and operators, and then the or operators.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 105


Python While Loops

• Python has two primitive loop commands:


while loops
for loops

while loops: You can make a block of code execute over and over again with a
while statement.
The code in a while clause will be executed as long as the while statement’s
condition is True.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 106
With the while loop we can execute a set of
statements as long as a condition is true.

Print i as long as i is less than 6:


i = 1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will


continue forever.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 107
A while statement always consists of the following:

• The while keyword

• A condition (that is, an expression that evaluates to True or False)

• A colon

• Starting on the next line, an indented block of code (called the while
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 108

clause)
With the else statement we can run a block
of code once when the condition no longer is
true:
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 109


An annoying while Loop
Here’s a small example program that will keep asking you to type, literally,
your name.
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 110


First, the program sets the name variable to an empty string.
This is so that the name != 'your name' condition will evaluate to True and
the program execution will enter the while loop’s clause.
The code inside this clause asks the user to type their name, which
is assigned to the name variable.
Since this is the last line of the block, the execution moves back to the start of
the while loop and reevaluates the condition.
If the value in name is not equal to the string 'your name', then the condition is
True, and the execution enters the while clause again.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 111


But once the user types your name, the condition of the while loop will
be 'your name' != 'your name', which evaluates to False.
The condition is now False, and instead of the program execution
reentering the while loop’s clause, it skips past it and continues running
the rest of the program

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 112


If you never enter your name, then the while loop’s
Please type your name.
Al
condition will never be False, and the program will
just keep asking forever.
Please type your name.
Albert Here, the input() call lets the user enter the right
string to make the program move on.
Please type your name. In other programs, the condition might never
%#@#%*(^&!!! actually change, and that can be a problem.

Please type your name.


your name

Thank you!
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 113
The break Statement

• With the break statement we can stop the loop even if the
while condition is true:
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 114
There is a shortcut to getting the program execution to break out of a while
loop’s clause early.
If the execution reaches a break statement, it immediately exits the
while loop’s clause.
In code, a break statement simply contains the break keyword.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 115


The first line u creates an infinite loop; it is awhile True:
while loop whose condition is always True.
print('Please type your name.')
(The expression True, after all, always evaluates name = input()
down to the value True.) if name == 'your name’:
break
The program execution will always enter the print('Thank you!')
loop and will exit it only when a break
statement is executed.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 116
Just like before, this program asks the user to type your name.
Now, however, while the execution is still inside the while loop, an if
statement gets executed to check whether name is equal to your name.
If this condition is True, the break statement is run , and the execution
moves out of the loop to print('Thank you!’).
Otherwise, the if statement’s clause with the break statement is
skipped, which puts the execution at the end of the while loop.
At this point, the program execution jumps back to the start of the while
statement to recheck the condition.
Since this condition is merely the True Boolean value, the execution
enters the loop to ask the user to type your name again.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 117
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 118
The continue Statement

With
the continue statement we
can stop the current
iteration, and continue with
the next: i=0
while i < 6:
i += 1
if i == 3:
continue
Shri Madhwa Vadiraja Instituteprint(i)
of Technology and Management 11/07/2025 119
Like break statements, continue statements are used inside loops.
When the program execution reaches a continue statement, the program
execution immediately jumps back to the start of the loop and reevaluates
the loop’s condition.
(This is also what happens when the execution reaches the end of the loop.)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 120


With the else statement we can run a block of code once when the
condition no longer is true:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 121


• Figure 2-13: A flowchart for swordfish py. The X path will logically
never happen because the loop condition is always True.

Text book1 Page No:52

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 122


Run this program and give it some input. Until you claim to be Joe, it
shouldn’t ask for a password, and once you enter the correct password, it
should exit.
Who are you?
I'm fine, thanks.
Who are you?
Joe
Hello, Joe. What is the password? (It is a fish.)
Mariya
Who are you?
Joe
Hello, Joe. What is the password? (It is a fish.)
swordfish
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 123

Access granted.
For Loops and the range() Function
The while loop keeps looping while its condition is True (which
is the reason for its name),
but what if you want to execute a block of code only a certain
number of times?
You can do this with a for loop statement and the range()
function.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 124


In code, a for statement looks something like for i in range(5): and
always includes the following:

• The for keyword


• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)

print('My name is')


for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 125
The code in the for loop’s clause is run five times.
The first time it is run, the variable i is set to 0.
The print() call in the clause will print Jimmy Five Times (0).
After Python finishes an iteration through all the code inside the for loop’s
clause, the execution goes back to the top of the loop, and the for
statement increments i by one.
This is why range(5) results in five iterations through the clause, with i
being set to 0, then 1, then 2, then 3, and then 4.
The variable i will go up to, but will not include, the integer passed to
range()

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 126


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 127
When you run this program, it should print Jimmy Five Times
followed by the value of i five times before leaving the for loop.

My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 128


An Equivalent while Loop
print('My name is')
i=0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i=i+1 You can actually use a while loop to do the
same thing as a for loop; for loops are just more
concise.

Let’s rewrite [Link] to use a while loop


equivalent
Shri Madhwa Vadiraja Institute of Technology and Management of a for loop. 11/07/2025 129
The Starting, Stopping, and Stepping
arguments to range()
Some functions can be called with multiple arguments separated by a
comma, and range() is one of them.
This lets you change the integer passed to range() to follow any sequence of
integers, including starting at a number other than zero.
for i in range(12, 16):
print(i) The first argument will be where the for loop’s variable
Output: 12 13
starts, and the second argument will be up to, but not
14 including, the number to stop at.
15 Institute of Technology and Management
Shri Madhwa Vadiraja 11/07/2025 130
range()
• The range() function can also be called with three arguments.
• The first two arguments will be the start and stop values, and the third will
be the step argument.
• The step is the amount that the variable is increased by after each
iteration. for i in range(0, 10, 2): Output:0
2
print(i) 4
6
So calling range(0, 10, 2) will count from zero to eight by intervals of two. 8
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 131
for i in range(5, -1, -1):
print(i)

Running a for loop to print i with range(5, -1, -1) should print
from five down to zero.
5
4
3
2
1
0
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 132
Importing modules

All Python programs can call a basic set of functions called built-in
functions, including the print(), input(), and len() functions you’ve seen
before.

Python also comes with a set of modules called the standard library.

Each module is a Python program that contains a related group of functions


that canVadiraja
Shri Madhwa be embedded in and
Institute of Technology your programs.
Management 11/07/2025 133
For example: the math module has mathematics- related functions, the
random module has random number–related functions, and so on.

• Before you can use the functions in a module, you must import the
module with an import statement.

In code, an import statement consists of the following:


• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 134


Once you import a module, you can use all the functions
of that module.

• Import and use the platform module:

import platform
x = [Link]()
print(x)

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 135


Python Dates

A date in Python is not a data type of its own, but we can import a
module named datetime to work with dates as date objects.
Import the datetime module and display the current date:

import datetime

x = [Link]()
print(x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 136
Date Output

When we execute the code from the example above the result will be:
2023-06-07 15:49:33.547501

The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date
object.

Here are a few examples:


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 137
Return the year and name of
weekday:
import datetime

x = [Link]()

print([Link])
print([Link]("%A"))

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 138


The strftime() Method

The datetime object has a method for formatting date objects into readable strings.

The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string: EX: Display the name of the month:
import datetime

x = [Link](2018, 6, 1) OUTPUT: June

print([Link]("%B"))
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 139
A reference of all the legal format codes:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 140


Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 141
Ending a Program early with
[Link]()
The last flow control concept to cover is how to terminate the
program.
This always happens if the program execution reaches the bottom
of the instructions.
However, you can cause the program to terminate, or exit, by
calling the [Link]() function.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 142


Run this program in IDLE. This program has an
infinite loop with no break statement inside.

import sys The only way this program will end is if the user
enters exit, causing [Link]() to be called. When
while True: response is equal to exit, the program ends.
print('Type exit to exit.')
response = input() Since the response variable is set by the input()
function, the user must enter exit in order to stop
if response == 'exit': the program.
[Link]()
print('You typed ' + response + '.')
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 143
Chapter 3- f u n C t i o n S
You’re already familiar with the print(), input(), and len() functions from the
previous chapters.
Python provides several built-in functions like these, but you can also write
your own functions.
A function is like a mini program within a program.
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 144
Creating a Function

• In Python a function is defined using the def keyword:


def my_function():
print("Hello from a function")
Calling a Function:
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function() OUTPUT: Hello from a function

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 145


Arguments

• Information can be passed into functions as arguments.


• Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
• The following example has a function with one argument
(fname). When the function is called, we pass along a first
name, which is used inside the function to print the full name:
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 146
Arguments

def my_function(fname): OUTPUT:


print(fname + " SMVITM") Emil SMVITM
Place SMVITM
College SMVITM
my_function("Emil")
my_function("Place")
my_function("College")
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 147
Parameters or Arguments?

• The terms parameter and argument can be used for the same
thing: information that are passed into a function.
From a function's perspective:
• A parameter is the variable listed inside the parentheses in the
function definition.
• An argument is the value that is sent to the function when it is
called.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 148
Number of Arguments
• By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you have
to call the function with 2 arguments, not more, and not less.
• This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname) OUTPUT:
Emil Place
my_function("Emil", "Place")

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 149


If you try to call the function with 1 or 3 arguments, you will get an
error:

• This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 150


Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:

def my_function(*Topers):
print("The Class Toper is " + Topers[0])
my_function("A", "B", "C")
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 151
def my_function(*Topers):
print("The Class Toper is " + Topers[1]) OUTPUT
The Class Toper is B
my_function("A", "B", "C")

def my_function(*Topers):
print("The Class Toper is " + Topers[2]) OUTPUT
my_function("A", "B", "C") The Class Toper is C

NOTE: Arbitrary Arguments are often shortened to *args in


Python documentations.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 152
Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.

Example
def my_function(toper1, toper2, toper3):
print("2nd toper is " + toper2)
my_function(toper1 = "A", toper2 = "B", toper3 = "c")

2nd toper is B
OUTPUT:
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 153
Example
def hello(): OUTPUT:
Hiii!
print(‘Hiii!') Hiii!!!
print(‘Hiii!!!') Hello there.
print('Hello there.') Hiii!
Hiii!!!
hello() Hello there.
hello() Hiii!
Hiii!!!
hello()
Shri Madhwa Vadiraja Institute of Technology and Management Hello there. 11/07/2025 154
Return Values and return Statements

To let a function return a value, use the return statement:

def my_function(x):
return 5 * x OUTPUT:

15
print(my_function(3)) 25
print(my_function(5)) 45
print(my_function(9))
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 155
Return Values and return
Statements
• When you call the len() function and pass it an argument such
as 'Hello’, the function call evaluates to the integer value 5,
which is the length of the string you passed it.
In general, the value that a function call evaluates to is called the
return value of the function.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 156


When creating a function using the def statement, you can specify what
the return value should be with a return statement. A return statement
consists of the following:
• The return keyword
• The value or expression that the function should return
When an expression is used with a return statement, the return value
is what this expression evaluates to.

For example, the following program defines a function that returns


a different string depending on what number it is passed as an
argument.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 157
import random elif answerNumber == 7:
def getAnswer(answerNumber): return 'My reply is no'
if answerNumber == 1: elif answerNumber == 8:
return 'It is certain' return 'Outlook not so good'
elif answerNumber == 2: elif answerNumber == 9:
return 'It is decidedly so' return 'Very doubtful’
elif answerNumber == 3:
return 'Yes’ r = [Link](1, 9)
elif answerNumber == 4: fortune = getAnswer(r)
return 'Reply hazy try again' print(fortune)
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 158
When this program starts,
Python first imports the random module.
Then the getAnswer() function is defined.
Because the function is being defined (and not called), the execution
skips over the code in it.
Next, the [Link]() function is called with two arguments,
1 and 9.
It evaluates to a random integer between 1 and 9 (including 1 and 9
themselves), and this value is stored in a variable named r.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 159
The getAnswer() function is called with r as the argument.

The program execution moves to the top of the getAnswer() function, and the
value r is stored in a parameter named answerNumber.

Then, depending on this value in answerNumber, the function returns one of


many possible string values.

The program execution returns to the line at the bottom of the program that
originally called getAnswer().

The returned string is assigned to a variable named fortune, which then gets
passed to a print() call and is printed to the screen.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 160


Note that since you can pass return values as an argument to another
function call, you could shorten these three lines:

r = [Link](1, 9) to this single equivalent line:


fortune = getAnswer(r)
print(fortune) print(getAnswer([Link](1, 9)))

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 161


Passing a List as an Argument

• You can send any data types of argument to a function


(string, number, list, dictionary etc.), and it will be treated
as the same data type inside the function.
• E.g. if you send a List as an argument, it will still be a List
when it reaches the function:

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 162


def my_function(food):
for x in food: OUTPUT:
print(x) apple
banana
cherry
fruits = ["apple", "banana", "cherry"]

my_function(fruits)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 163
The none Value
The None keyword is used to define a null value, or no value at all.
Python None Keyword

• Assign the value None to a variable:


x = None Output: None
print(x)

None is not the same as 0, False, or an empty string. None is a data type
of its own (NoneType) and only None can be None.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 164
If you do a boolean if test, what will happen? Is None True or False:
x = None

if x:
print("Do you think None is True?")
elif x is False:
print ("Do you think None is False?")
else:
print("None is not True, or False,
None is just None...")
OUTPUT: None is not True, or False, None is just None...
Shri Madhwa Vadiraja Institute of Technology and Management
11/07/2025 165
local and global Scope
Local Scope
• A variable created inside a function belongs to the local
scope of that function, and can only be used inside that
function.
• A variable created inside a function is available inside that
function:
def myfunc():
x = 300
print(x) OUTPUT:300

myfunc()
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 166
Function Inside Function

The local variable can be accessed from a function within the


function:
def myfunc():
x = 300
def myinnerfunc(): Output: 300
print(x)
myinnerfunc()

myfunc()
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 167
Global Scope

• A variable created in the main body of x = 300


the Python code is a global variable
and belongs to the global scope.
def myfunc():
• Global variables are available from print(x)
within any scope, global and local. OUTPUT:
300
• A variable created outside of a function myfunc() 300
is global and can be used by anyone:
print(x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 168
Naming Variables

• If you operate with the same variable name inside and outside of a
function, Python will treat them as two separate variables, one available in
the global scope (outside the function) and one available in the local scope
(inside the function):
200
200
The function will print the local x, and then the code will print the global x:
300
x = 300

def myfunc():
OUTPUT: 200
x = 200 300
print(x)

myfunc()

print(x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 169
Global Keyword/the global Statement
If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.
The global keyword makes the variable global.

If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x OUTPUT: 300
x = 300

myfunc()

print(x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 170
To change the value of a global variable inside a function, refer to
the variable by using the global keyword:

x = 300
200
def myfunc():
global x OUTPUT: 200
x = 200

myfunc()

print(x)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 171
• If you need to modify a global variable from within a function, use the
global statement.
If you have a line such as global flower at the top of a function, it tells
Python, “In this function, flower refers to the global variable, so don’t create
a local variable with this name.”
def spam():
global flower When you run this program, the final print() call will
output this:
flower = 'spam’
flower = 'global' OUTPUT: spam
spam()
print(flower)
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 172
Local Variables Cannot Be Used in the
Global Scope
• Consider this program, which will cause an error
when you run it:
Can a local variable be used outside a
function?
def f():

s = "I love INDIA"


print("Inside Function:", s)

f() OUTPUT:
print(s) NameError: name 's' is not defined
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 173
Local Scopes Cannot Use Variables in Other Local Scopes

• A new local scope is created whenever a function is called, including when a


function is called from another function.
When the program starts, the fun1() function is called, and a local
def fun1(): scope is created.
Chocolates = 99 The local variable Chocolates is set to 99.
fun2()
print(Chocolates) Then the fun2() function is called, and a second local scope is created.
Multiple local scopes can exist at the same time.
def fun2():
Apple = 101 In this new local scope, the local variable apple is set to 101, and a
Chocolates = 0 local variable Chocolates which is different from the one in fun1()’s
local scop is also created and set to 0.
fun1()
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 174
• When fun2() returns, the local scope for that call is destroyed.
• The program execution continues in the fun1() function to print the value
of Chocolates and since the local scope for the call to fun1() still exists
here, the Chocolates variable is set to 99.
• This is what the program prints.
• The upshot is that local variables in one function are completely separate
from the local variables in another function

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 175


Exception handling
• Right now, getting an error, or exception, in your Python program means the
entire program will crash.
You don’t want this to happen in real-world programs.
Instead, you want the program to detect errors, handle them, and then continue to
run.
For example, consider the following program, which has a “divide-by-
zero” error.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 176
We’ve defined a function called spam, given it a parameter, and then printed the
value of that function with various parameters to see what happens. This is the
output you get when you run the code:

OUTPUT:
def spam(divideBy):
21.0
return 42 / divideBy 3.5
print(spam(2)) Traceback (most recent call last):
print(spam(12)) File "C:/[Link]", line 6, in <module>
print(spam(0)) print(spam(0))
print(spam(1)) File "C:/[Link]", line 2, in spam
return 42 / divideBy
ZeroDivisionError: division by zero
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 177
ZeroDivisionError happens whenever you try to divide a number by
zero. From the line number given in the error message, you know that the
return statement in spam() is causing an error.

• Errors can be handled with try and except statements.


• The code that could potentially have an error is put in a try clause.
• The program execution moves to the start of a following except clause if
an error happens.
• You can put the previous divide-by-zero code in a try clause and have
an except clause contain code to handle what happens when this error
occurs.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 178
When code in a try clause causes an error, the program execution immediately
moves to the code in the except clause. After running that code, the execution
continues as normal. The output of the previous program is as follows:

def spam(divideBy): OUTPUT:


try: 21.0
return 42 / divideBy 3.5
except ZeroDivisionError: Error: Invalid argument.
print('Error: Invalid argument.') 42.0
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 179
Note that any errors that occur in function calls in a try block will also
be caught. Consider the following program, which instead has the spam()
calls in the try block:

OUTPUT:
def spam(divideBy): print(spam(0)) 21.0
return 42 / divideBy 3.5
print(spam(1))
Error: Invalid
try:
except ZeroDivisionError: argument.
print(spam(2))
print('Error: Invalid argument.')
print(spam(12))

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 180


• The reason print(spam(1)) is never executed is because once the
execution jumps to the code in the except clause, it does not
return to the try clause. Instead, it just continues moving down
as normal.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 181


A Short Program: Guess the
Number
“Guess the Number” game. When you run this
program, the output will look something like this:
I am thinking of a number between 1 and 20. Take a guess.
Take a guess. 17
10 Your guess is too high.
Your guess is too low. Take a guess.
Take a guess. 16
15 Good job! You guessed my number in 4
Your guess is too low. guesses!
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 182
# This is a guess the number game.
import random
secretNumber = [Link](1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 183


elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + '
guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 184
Let’s look at this code line by line, starting at the top.

# This is a guess the number game.


import random
secretNumber = [Link](1, 20)

First, a comment at the top of the code explains what the program does.
Then, the program imports the random module so that it can use the [Link]() function
to generate a number for the user to guess.
The return value, a random integer between 1 and 20, is stored in the variable secretNumber.
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 185
The program tells the player that it has come up with a secret number
and will give the player six chances to guess it.

print('I am thinking of a
The code that lets the player enter a guess and checks
number between 1 and
that guess is in a for loop that will loop at most six times.
20.')
# Ask the player to guess 6 The first thing that happens in the loop is that the
player types in a guess.
times.
for guessesTaken in Since input() returns a string, its return value is passed
range(1, 7): straight into int(), which translates the string into an
integer value.
print('Take a guess.')
This gets stored in a variable named guess.
guess = int(input())
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 186
These few lines of code check to see whether the guess is less than or
greater than the secret number. In either case, a hint is printed to the
screen.

if guess < secretNumber:


print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 187


else:
break # This condition is the correct guess!

If the guess is neither higher nor lower than the secret number, then it
must be equal to the secret number, in which case you want the program
execution to break out of the for loop.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 188


After the for loop, the previous if...else statement checks whether the
player has correctly guessed the number and prints an appropriate message
to the screen.

if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + '
guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))

In both cases, the program displays a variable that contains an integer value
(guessesTaken and secretNumber).
Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 189
Since it must concatenate these integer values to strings, it passes these
variables to the str() function, which returns the string value form of
these integers.
Now these strings can be concatenated with the + operators before
finally being passed to the print() function call.

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 190


End of Module -1

Shri Madhwa Vadiraja Institute of Technology and Management 11/07/2025 191

You might also like