0% found this document useful (0 votes)
9 views

Python Module-1 Notes (21EC646)

Uploaded by

kgaddigoudar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Module-1 Notes (21EC646)

Uploaded by

kgaddigoudar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Module -1

Python Basics
Syllabus:
Python Basics:
• Python Language Features,
• History ,
• Entering Expressions into the Interactive Shell,
• The Integer, Floating-Point, and String Data Types,
• String Concatenation and Replication,
• Storing Values in Variables,
• Your First Program,
• Dissecting Your Program,
• Flow control,
• Boolean Values,
• Comparison Operators,
• Boolean Operators,
• Mixing Boolean and Comparison Operators,
• Elements of Flow Control,
• Program Execution,
• Flow Control Statements,
• Importing Modules,
• Ending a Program Early with sys.exit(),
• Functions
• def Statements with Parameters,
• Return Values and return Statements,
• The None Value,
• Keyword Arguments and print(),
• Local and Global Scope,
• The global Statement,
• Exception Handling,
• A Short Program: Guess the Number
PYTHON APPLICATION PROGRAMMING

Python Programming Basics


Python’s History

• Python is created by Guido van Rossum in Netherlands in 1990.


• Python is open source.
• Open-source software is a type of computer software in which source code is released
under a license in which the copyright holder grants users the rights to study, change, and
distribute the software to anyone and for any purpose

Features of python:
1. Python is free and open-source programming. The software can be downloaded and used
freely.
2. It high level programming language.
3. Easy Syntax: Python uses easy-to-read syntax and easy to learn.
4. It is portable. That means python programs can be executed on various platforms without
altering them.
5. Indentation: Python uses indentation to define code blocks, like loops and functions,
instead of curly braces or keywords like "end". This enforces clean and readable code.
6. Interpreted: Python is an interpreted language, meaning that code is executed line by line.
The Python programs do not require compilation. Python converts the source code into an
intermediate form called bytecodes and then translates this into the native language of your
computer and then runs it.
7. It is an object oriented programming language
8. It can be embedded within your C or C++ programs.
9. It has very rich set libraries and library functions
10. It has very powerful built in data types.
11. Dynamic Typing: You don't need to declare the type of a variable explicitly. Python
automatically determines the data type during execution.
12. Dynamic Memory Management: Python automatically handles memory allocation and
deallocation. You don't need to worry about memory management like in languages such
as C or C++.
13. Cross-Platform: Python is available on multiple platforms, including Windows, macOS,
and Linux, making it easy to write code that works across different operating systems

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Entering Expressions into the Interactive Shell

Enter 2 + 2 at the Python prompt

• In Python, 2 + 2 is called an expression, kind of programming instruction


• Expressions consist of values (such as 2) and operators (such as +), and they evaluated to
single value.
• Here, 2 + 2 is evaluated down to a single value, 4.
• A single value with no operators is also considered an expression, though it evaluates only
to itself.

Parts of the Program Programming


Variables:
• Variable is name given to the memory location which is used to store value. This means
when we create the variables, we reserve some space in the memory.
• A value can be assigned to a variable using assignment operator (=).
• Value of the Variable can be modified wherever required in the program.
• Assigning the values to variable
# An integer assignment
Roll_number = 45

# A floating point
height = 5.8

# A string
name = "Sachin Tendulkar"

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

# Assigning a single value to multiple variables:


a = b = c = 10

# Assigning different values to multiple variables:


a, b, c = 1, 20.2, "ECE SGBIT"

Rules for Variable names


• The keywords (reserved words) cannot be used for naming the variable.
• A variable name can only contain alphabets (lowercase and uppercase) and numbers,
but should not start with a number
• A variable name must start with a letter or the underscore character
• Variable names are case-sensitive (Sachin, sachin and SACHIN are three different
variables).
• No other special characters like @, $ etc. are allowed

Invalid Variable Names


2a=15 #starting with a number
SyntaxError: invalid syntax

x$=4 #contains $
SyntaxError: invalid syntax

if=10 # if is a keyword
SyntaxError: invalid syntax

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Values & Data Types

• A value is one of the most basic things in any program.


• A value may be
o Characters or strings i.e. ‘Hello’ or
o Or number like 1, 2.2 etc.

• Values belong to different types: integer, float, string etc.

Example :
# An integer assignment
x= 45

• Here the 45 is called as the value and it is assigned to the variable x.

Data Types
• A data type indicates the type of data (value), such as integer, string, float, etc.
• The most common data types in Python are integers, floating-point numbers, and strings.
• To find the type of the value, we have to use the inbuilt function type()

Integers
Definition: Whole numbers without a decimal point.
Examples: -2, -1, 0, 1, 2, 3, 4, 5

Floating-Point Numbers
Definition: Numbers with a decimal point.
Examples: -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25
Note: The number 42.0 is a floating-point number, not an integer.

Strings

• Definition: Text values, which are sequences of characters.


• Examples: 'a', 'aa', 'aaa', 'Hello!', '11 cats', “25”
• Usage: Surround text with single quote (') characters to define a string.
• Blank String: A string with no characters, represented as ''.

Identifiers:
• An identifier is a name given to a variable, function, class or module.
• Identifiers may be one or more characters in the following format:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

o Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to


Z) or digits (0 to 9) or an underscore (_). Names like myCountry, other_1 and
good_ morning, all are valid examples.
o A Python identifier can begin with an alphabet (A – Z and a – z and _).
o An identifier cannot start with a digit but is allowed everywhere else. 1plus is
invalid, but plus1 is perfectly fine

Input from User or Keyboard (input () function)


Inbuilt function input() is used to receive the input from keyboard.
Note: By default input() function returns value as string.
So, if we want to receive the int/float values, then we have to convert the returned value
from input() with the help of inbuilt function
# To receive the string value
name = input( )

# To receive the string value


name = input(“Enter your name : ”)

# To receive the int value


roll_no =int( input(“ Enter your Roll number : ”))

# To receive the int value


weight= float (input(“ Enter your Roll number : ”))

Output using print() function


Inbuilt function print() is used to print the message on the screen

print(" Welcome to SGBIT")


Output: Welcome to SGBIT

x = 5
y= 10
z= x + y

print(z)
Output: 15

print("The sum is =", z)


Output: The sum is =15

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

print("The sum of x and y =", z)


Output: The sum of x and y =15

print("The sum of”, x, “and”, y, “=", z)


Output: The sum of 5 and 10 =15

Keywords [Words]
• Every programming language has its own constructs to form syntax of the language.
• Basic constructs of a programming language include set of characters and keywords
• Keywords are reserved words. Each keyword has a specific meaning and they are meant to
perform specific task.
.

Note: The names of the keywords cannot be used as variables

An expression

• An expression is a combination of values, variables, and operators. A single value itself is


considered an expression, and similarly a variable:
>>> 42 #single value expression

>>> y= x + 25
>>>print(y)

Operators and operands


• Operators are special symbols used to represent arithmetic & logical operations.
• The data values on which operator operates are called operands
• An operator may work on single operand (unary operator) or two operands (binary
operator).
• Python language supports a wide range of operators. They are

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o Logical Operators
o Bitwise Operators

Arithmetic Operators
Operator Description Example
+ Addition y=a +b
- Subtraction y=a -b
* Multiplication y= a * b
/ Division (always results into float) y= a/ b
y=a % b
% Modulus (Remainder of the division)
(Remainder of a/b)
Floor division (returns whole number)
The division of operands where the output
// is the quotient in which the digits after the y=a // b
decimal point are removed.

** Exponent y=a**b (a to the power b)

Relational or Comparison Operators

Operator Description Example


Equal to
== True if a is equal to b a == b
False otherwise
!= Not equal to a != b
True if a is not equal to b
False otherwise
< Less than a < b
True if a is less than b
False otherwise
<= Less than or equal to
True if a is less than or equal to b a <= b
False otherwise
> Greater than a > b
True if a is greater than b
False otherwise
>= Greater than or equal to
True if a is greater than or equal to b; a >= b
False otherwise

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Logical (Boolean) operators or Expressions


Operator Description Example
Not Logically reverses the sense of x not x
Or True if either x or y is True x or y
False otherwise
And True if both x and y are True x and y
False otherwise

Bitwise operators
Operator Description Example
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Modulus operator
• The modulus operator works on integers and yields the remainder of the division
• In Python, percent sign (%) represents the modulus operator.
The syntax:
a=7
b=3
y= a%b => output =1
Here 7 divided by 3, so quotient is 2 and remainder is 1.
• The modulus operator is very useful.
o For example, we can check whether one number is divisible by another:
if x % y =0, then x is divisible by y.
o Modulus operator can be used to extract the right-most digit or digits from a number.
For example: 197 % 10 = 7 => here from 197 the right most digit 7 is extracted
1083%100= 83 => here from 1083 the 2 right most digits 83 are extracted
o The modulus can be used to find the even and odd numbers etc
• In python the value of the modulus is calculated using this expression.
y=a%b
= a- (a//b) * b
[Note: here a//b is floor division]

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example : -11% 9
= -11- (-11//9) * 9
=-11-(-1.22) *9
=-11-(-2) *9
=-11-(-18)
=7

Example : -5% 4
= -5- (-5//4) * 4
= -5 -(-1.25) * 4
=-11-(-2) *4
=-11-(-8)
=3

Precedence Rule or Order of operations


• When an expression contains more than one operator, the order of evaluation depends on
the rules of precedence.
• For mathematical operators, Python follows mathematical convention.
1. Parentheses
2. Exponentiation
3. Multiplication & Division
4. Addition and Subtraction
The acronym PEMDAS is a used to remember rules:

• Parentheses: have the highest precedence in any expression. The operations within
parenthesis will be evaluated first.
Examples: 2 * (3-1) => Output= 4
(1+1)**(5-2) => Output= 8
The addition has to be done first and then the sum is multiplied with c

• Exponentiation: it has the 2nd precedence. But it is right associative. That is, if there are
two exponentiation operations continuously, it will be evaluated from right to left (unlike
most of other operators which are evaluated from left to right).
Examples: 2**1+1 => Output= 3

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

3*1**3 => Output= 3


2**3**2 => Output= 512

• Multiplication and division: Multiplication and Division are the next priority. Both
same precedence. Operators with the same precedence are evaluated from left-to-right.
Examples: 2*3-1 => Output= 5
5-2*2 => Output= 1
5*2/4 => Output= 2.5
• Addition and Subtraction are the least priority. Both same precedence. Operators with
the same precedence are evaluated from left-to-right.
Examples: 5-3-1 => Output= 1
5-2+2 => Output= 5
6-(3+2) => Output= 1

String Concatenation and Replication


Operators and Data Types
The meaning of an operator can change based on the data types of the values it operates on.

String Concatenation
+ Operator: Joins two strings together.

>>> first = 10
>>> second = 15
>>> print(first+second) #Here + operator performs the addition
Output = 25

>>> first = '100'


>>> second = '150'
>>> print(first + second) #Here + operator performs the concatenation of strings
Output = 100150

>>> first = 'Sachin'


>>> second = 'Tendulkar'
>>> print(first + second) #Here + operator performs the concatenation of strings
Output = SachinTendulkar

Error with Mixed Types:


Using + with a string and an integer causes an error.

Example: 'Alice' + 42

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Output: TypeError: Can't convert 'int' object to str implicitly

Solution: Convert the integer to a string before concatenation.

Example:
'Alice' + str(42)
Output : 'Alice42'.

String Replication
* Operator: Repeats a string a specified number of times.

Example: 'Alice' * 5
Output: 'AliceAliceAliceAliceAlice'.

Error with Invalid Types:


Using * with two strings or a string and a float causes an error.

Example: 'Alice' * 'Bob'


Result : TypeError: can't multiply sequence by non-int of type 'str'

Example: 'Alice' * 5.0


TypeError: can't multiply sequence by non-int of type 'float'

Comments
• Comments are used to improve the readability of the program.
• Comments are not executed by the interpreter
• It is a good programming practice to add comments to the program wherever required.
• This will help someone to understand the logic of the program.
• Comments are used primarily to document the meaning and purpose of source code
• For large and complex software, programmers work in teams and sometimes, a program
written by one programmer may be used or maintained by another programmer. In such
situations, documentations (comments) help to understand the working of the program.
• Comment may be in a single line or spread into multiple lines.
• A single-line comment in Python starts with the symbol #.
• Multiline comments are enclosed within a pair of 3-single quotes.
• Example1:

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

#This is a single-line comment


Example 2:
''' This is a
multiline
comment '''

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()

or
myName = input('What is your name?') # in single statement

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.')

The str(), int(), and float() Functions

Purpose of the Functions

str(): Converts a value to its string form.


int(): Converts a value to its integer form.
float(): Converts a value to its floating-point form.

Using str() for Concatenation


To concatenate an integer with a string, convert the integer to a string using str().
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
Output : I am 29 years old.

Examples of Conversion Functions


str() Examples:
>>> str(0)
'0'

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

>>> str(-3.14)
'-3.14'

int() Examples:
>>> int('42')
42

>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1

float() Examples:
>>> float('3.14')
3.14
>>> float(10)
10.0

Practical Use of int() with input()


The input() function returns a string. Convert it to an integer to perform mathematical
operations.

>>> spam = input()


Output : '101'
>>> spam = int(spam)
>>> spam
101

Performing math with the converted integer:


>>> spam * 10 / 5
202.0

Handling Errors with int()


Converting non-integer strings to an integer causes an error.
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>

int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'

>>> int('twelve')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int('twelve')

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

ValueError: invalid literal for int() with base 10: 'twelve'

Using int() to Round Down Floats


int() rounds down floating-point numbers.
>>> int(7.7)
7
>>> int(7.7) + 1
8

Example Program Explained


print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')

Explanation of the program :

input() : takes the user's input as a string.


int(myAge) : converts the input string to an integer.
int(myAge) + 1: adds one to the integer.
str(int(myAge) + 1) : converts the result back to a string.
Concatenate and print the final message.

Output
If the user enters '4':
myAge is '4'.
int(myAge) converts '4' to 4.
int(myAge) + 1 results in 5.
str(5) converts 5 back to '5'.
The final message is: "You will be 5 in a year."

Flow Control
• Programming allows instructions to be executed based on conditions.
• Programs rarely execute straight through from start to finish.
• Flow control statements decide which instructions to run under specific conditions.

Boolean values, comparison operators, and Boolean operators help determine the outcome of
flow control statements.

Boolean Values:
• Boolean values, which can be either True or False, are used in expressions and stored in
variables.
• They help in flow control by determining the outcome of conditional statements, such as if
statements,

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Comparison operators
• Comparison operators return Boolean values by comparing two values.
• Essential for making decisions in flow control statements (if, while).
• Used widely beyond flow control, such as in loops and conditions.

Operator Description Example


Equal to
== True if a is equal to b a == b
False otherwise
!= Not equal to a != b
True if a is not equal to b
False otherwise
< Less than a < b
True if a is less than b
False otherwise
<= Less than or equal to
True if a is less than or equal to b a <= b
False otherwise
> Greater than a > b
True if a is greater than b
False otherwise
>= Greater than or equal to
True if a is greater than or equal to b; a >= b
False otherwise

Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare Boolean values.
• Used in conditional statements (if, elif, else), loops (while, for), and other decision-
making contexts.

Operator Description Example


Not Logically reverses the sense of x not x
Or True if either x or y is True x or y
False otherwise
And True if both x and y are True x and y
False otherwise

Flow Control Statements


Conditional execution
• Conditional statements are also called decision-making statements. We use these statements,
when we want to execute a block of code, if the given condition is met (true or false).

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

1. if statements
2. Alternative Execution (if else)
3. Chained Conditionals: if elif else
4. Nested Conditionals

if statements

• The boolean expression in the if header is called the condition.


• Header of if statement ends with a colon character (:) and then set (block) of statements after
the if-header statement are indented.
• If the logical condition is true, then the indented statements get executed. If the logical
condition is false, the indented statement is skipped
Example 1
age=int(input(“Enter your age”)
if age>= 18: #colon at the end of if header
print(“Eligible for voting”) #Indentation (part of if block)

Example 2
mark=int(input(“Enter your marks”)
if mark>=35: #colon at the end of if header
print(“Pass”) #Indentation (part of if block)
Print(“Congratulations”) #indentation (part of if block)
print(“Hello it is not part of if block”) #No indentation (Not a part of if block)

• There is no limit for, the number of statements in the if body, but there must be at least
one.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• But in some occasions, the program should not do anything when the condition is true, in
such cases, the statement block can be skipped by just using pass statement as shown
below
if x < 0 :
pass # do nothing, if number is negative

Alternative Execution (if else)


• A second form of the if statement is alternative execution (if else), in which there are two
possibilities
• Here, when the condition is true, one set of statements will be executed and when the
condition is false, another set of statements will be executed.
• The syntax and flowchart are as given below

• Example: Program to Find If a Given Number Is Odd or Even


num = int(input("Enter a number"))
if num % 2 == 0:
print(num, “is Even number")
else:
print(num, “is Odd number")

• Example: Program to find the Greater of two numbers

num1= int(input(“Enter the first number”)


num2=int(input(“ Enter the second number”)
if num1> num2:
print(num1, “is greater than”, num2)
else:
print(num2, “is greater than”, num1)
• Example: Program to print the positive difference of two numbers.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

else:
diff = num2 - num1
print("The difference of",num1,"and",num2,"is",diff)

Example: Program to check the divisibility of the number


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
rem=num1%num2
if rem==0:
print(“First number is divisible by second number”)
else:
print(“First number is not divisible by second number”)

Chained Conditionals: if elif else


• In some situations, more than one possibility or conditions have to be checked to execute a
set of statements.
• That means, we may have more than one branch. This is solved with the help of chained
conditionals.
• The syntax and flowchart is given below

Example: Program to check whether the given number is positive or negative


num = int(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Number is Zero")
else:
print("Negative number")

Example: Program to calculate the tax


salary= float(input(“ Enter the salary”)
if salary<=500000: # No tax
print(“ Exempted from tax”)
elif salary>500000 and salary<=1000000: #10% tax

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

tax= 0.1*salary
print(“ Tax amount to be paid is :”, tax)
else salary>100000
tax= 0.3*salary #30% tax
print(“ Tax amount to be paid is :”, tax)

Example: Program to check the class (grade) of the student

marks=float(input("Enter marks:"))
if marks >= 80:
print("First Class with Distinction")
elif marks >= 60 and marks < 80:
print("First Class")
elif marks >= 50 and marks < 60:
print("Second Class")
elif marks >= 35 and marks < 50:
print("Third Class")

Nested Conditionals
• One conditional statement can be nested within another conditional statement.
• Nesting can be done in many ways as per the requirement in the program.
• In nested conditionals, even though indentation of the statements makes the inner and
outer structure visible, but still it is difficult to read the nested conditionals very quickly
Example 1:
gender=input("Enter gender:")
age=int(input("Enter age:"))
if gender ==’M’
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F" :
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")

Example 2:
x=int(input(“ Enter the first number”)
y=int(input(“ Enter the first number”)
if x == y:
print('x and y are equal')

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')

Programs based on if else :


Example : Program to find the largest among 3 numbers

num1=int(input(“ Enter the first number”)


num2=int(input(“ Enter the second number”)
num3=int(input(“ Enter the third number”)

if(num1>=num2) and (num1>num3):


max=num1
if(num2>=num1) and (num2>num3):
max=num2
else :
max=num3
print(“ the maximum number is”, max)

Another method
num1=int(input(“ Enter the first number”)
num2=int(input(“ Enter the second number”)
num3=int(input(“ Enter the third number”)

max=num1
if num2>max:
max=num2
if num3 > max:
max=num3
print(“ the maximum number is”, max)

Example: Write a program to create a simple calculator performing any four basic operations.
Program has to ask the choice (mathematical operation) from user and that particular operation
has to be executed

val1 = float(input("Enter value 1: "))


val2 = float(input("Enter value 2: "))
op = input("Enter any one of the operator (+,-,*,/): ")

result = 0

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

if op == "+":
result = val1 + val2
elif op == "-":
if val1 > val2:
result = val1 - val2
else:
result = val2 - val1
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Error! Division by zero is not allowed. Program terminated")
else:
result = val1/val2
else:
print("Wrong input, program terminated")
print("The result is ",result)

ITERATION
• Iteration is a process of repeating some tasks. In programming, iteration is often referred to
as 'looping'
• In programming, many times, we require a set of statements to be repeated certain number
of times and/or till a condition is met.
• Every programming language provides certain constructs to achieve the repetition of tasks.
• Python offers two kinds of loop:
o while loop. (Indefinite loop)
o for loop (definite loop)

while loop (Indefinite Loop)

• while loop is used to repeat block of code till condition is true/met. This is condition-
controlled loop.
• The while loop iterates till the condition is met and hence, the number of iterations are
usually unknown prior to the loop. Hence, it is sometimes called as indefinite loop

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• Syntax of the while loop

Example 1: Write program to Print “Hi how are you” 10 times


count = 0
while count <= 10:
print(“Hi, how are you”)
count = count +1

Example 2: Write program to Print first 5 natural numbers using while loop
count = 1
while count <= 5:
print(count)
count = count +1
Output:
1
2
3
4
5

Example 2: Write program to Print even numbers from 0 to 10 using while loop.
i=0
while i <= 10:
print(i)
i = i +2

Example 4: Write program to print Odd numbers from 1 to 19 using while loop.
i=1
while i <= 19:
print(i)
i = i +2

Example 5 : Write program to find the sum of all the numbers from 0 to 20
i=0
sum=0

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

while i <= 20:


sum=sum+i
print(sum)
i = i +1

Example 6 : Write program to find the sum of all even the numbers from 0 to 20
i=0
sum=0
while i <= 20:
if i%2= =0 :
sum=sum+i
print(sum)
i = i +1

Infinite Loops, break and continue

• Infinite Loop is loop, in which condition never becomes false, hence block of code will be
executed infinite number of times.
• An infinite loop is useful in client/server programming, where the server should be
running continuously, so that client can communicate with server, anytime (whenever
required).

• Example 1
n = 10
while True:
print(n)
n = n -1
Here, in this example, the condition specified is the constant value True, so all the time it
is true, no way to make it false, so once it gets into infinite loop, it will never get
terminated.

• Example 2
n = 10
while n>0:
print(n)
n = n +1

In this example, because of the improper condition or wrong counter value, the condition
never becomes false, so loop will never get terminated.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Here initially n=10, condition is true, so loop body statement gets executed, also value of n
is incremented (n=11). Now, again condition is checked, condition is true, again loop body
gets executed. Here no chance of condition becoming true, so loop gets executed infinite
number of times.

While, break
• Sometimes we don’t know, when to end a loop until we get half way through the loop
body. In that case we can write an infinite loop and then use the break statement to jump
out of the loop.
• The break statement terminates the current loop and passes the control to the next
statement, which is immediately after the body of loop

• Example: Let us consider above infinite loop using break statement


n = 10
while True:
print(n)
n = n -1
if n= =5:
break

Here break statement is placed within loop, after the if statement & break statement
provides chance to exit the loop, when external condition is generated.

Example:
n=1
while n>0:
print(n)
n = n +1
if n==8:
break

.
Example: Program to take input data from the user until they type done.
while True:
data = input('Enter the data')
if data == 'done':

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

break
print(data)
print('Done!')

while, continue, break


• The continue statement in Python returns the control to the beginning of the while loop.
• The continue statement rejects or skips all the remaining statements in the current loop and
moves the control back to the top of the loop (expression or condition)

Example:
Program to generate the natural numbers from 1 to 5 except 3
Hint : Skip the iteration if the variable i is 3, but continue with the next iteration

i=0
while i<=5
i=i+1
if i == 3:
continue
print(i)
Example: Program to accept the input string “India” 5 times from the user, if the entered string is
other than India, do not accept it and again ask the user to enter the input.
i=0
while i<=5
str=input(“ Enter the name of your country”)
if str != “India”:
continue
elif str==”India”
print(str)
i=i+1

• Example: Program to find the sum of 5 even numbers taken from the keyboard, if the user
enters odd number do nothing and again ask the user to enter number.
sum=0
count=0

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

while True:
x=input("Enter a number:")
if x%2!=0:
continue
else:
sum=sum+1
count=count+1
if count==5:
break
print("Sum= ", sum)

While loop with else


• The else block is only executed, if while condition becomes false.
• Note: The else block just after for/while is executed only when the loop is NOT
terminated by a break statement.
• Example
# while-else loop

i = 0
while i < 4:
i =i+1
print(i)
else: # Executed because no break in
print("Bye bye")

• Example
i = 0

while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("Bye Bye")

range ( ) function

• range() : range() is in-built function, which is used to generate a series of numbers within a
given range.
• The most common use of range () function is to iterate or to index sequence type (List,
tuple, dictionary, string, etc.) with for and while loop.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Syntax:
range(start, stop, step)
range(start, stop) # By default step size is one
range(stop) # By default start is zero and step size is one.

• This function does not store values in the memory, it only remembers start, step and step
size on the go. To force this, it has to be used with sequence type or for and while loop.

Exercises

for loop (definite loop)


• for loops are used to repeat the block of code for fixed number of times. This is count
controlled loop.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• In case of for loop, we know number of times the block of code to be executed or repeated
in prior, so this is called as a definite loop.
• But in case of while loop, it repeats, until some condition becomes False, so it is called as
indefinite loop
• The for-loop is always used in combination with an iterable object, like range or sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
• for loop, iterates over each item of a sequence in order & executes body of loop each time.
• In for loop, it is not required to set the indexing variable beforehand.
• With each iteration, Python automatically increments the index of variable.

Syntax:

Here for and in are keywords.

Loop patterns: (different way of writing the for loops)


General procedure to construct the loops
• Initialize one or more variables before the loop starts
• For each element of list, loop body gets executed. Loop body may conation some
computations, possibly changing the variables in the body of the loop
• When the loop completes, look at the resulting variables

for loop using range function


Example: To generate first 5 natural numbers
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example:
for i in range(1, 6, 2):
print(i)

Output:
0
2
4

# Iterating over a list


seq= [2,5,8,18,10] #List is created with name seq
for i in seq:
print(i)

Output:
2
5
8
18
10

#List is part of the for header

for i in [3,6,18]: # List is part of for header.


print(i)

Output:
3
6
18

# Iterating over a list (Heterogeneous list)


seq= [“Virat”, 10.5, 6, “Dhoni”, 5+10j] #Heteregeneous list
for i in seq:
print(i)

Output:
Virat
10.5
6
Dhoni
(5+10j)

# Program to iterate through a list using indexing


seq= [“Virat”, 10.5, 6, “Dhoni”, 5+10j] #Heteregeneous list
l=len(seq)
for i in range(l):
print(i, seq[i])

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Output:
0 Virat
1 10.5
2 6
3 Dhoni
4 (5+10j)

Note: Similarly for loop can be used to iterate through the tuples,
dictionary, sets, strings etc

Counting and Summing Loops:


Counting Loop
We can use the for loop to count number of items in the list, for example:

count = 0
for i in [3, 41, 12.5, -9, 21, 15]:
count = count + 1
print ('Count: ', count)

Output:
Count: 6

• Here, the variable count is initialized to zero before the loop starts.
• for loop runs over each element of the list.
• The iteration variable ‘i’ controls the loop, it causes the loop body to be executed
once for each element in the list.
• For each element of the list, loop body gets executed, so for each element of list,
the 1 is added to value of the count variable. Thus, after completion of all
executions of loop body or iterations, the variable count will hold count of the total
number of elements in the list.

Summing Loop
We can use the for loop to sum up the all-List elements or List items
total = 0
for i in [3, 41, 12.5, -9, 21, 15]:
total = total + i
print ('Total of all the elements in list: ', total)

Output:
Total of all the elements in list: 83.5

• Here, in each iteration, iteration variable ‘i’ contains one particular value of List, for
example, in the 1st iteration, it contains value 3, and in the second iteration, it contains
the 41 and so on.
• For each element of the list, loop body gets executed, so in each iteration, value of the
iteration variable ‘i’ is added to the total variable.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• Thus, after completion of all the iterations, the variable total contains the sum of all
the elements of List
• As the loop is being executed, the variable total, accumulates the sum of the elements;
so, this total variable is sometimes called an accumulator.

• Note: In practise, neither the counting loop nor the summing loop are particularly
useful, because there are built-in functions len() and sum() that compute the number of
items in a list and the total of the items in the list respectively.

Maximum and Minimum Loops:


Maximum Loops
• We can use the for loop, to find the maximum valued element of List.
Example program

largest =0
for i in [3, 41, 12, 9, 74, 15]:
if i > largest:
largest = i
print(' Iteration variable value:', i, ‘largest:’ largest)
print('Largest:', largest)

Output
Iteration variable value: 3 largest: 3
Iteration variable value: 41 largest: 41
Iteration variable value: 12 largest: 41
Iteration variable value: 9 largest: 41
Iteration variable value: 74.5 largest: 74.5
Iteration variable value: 15 largest: 74.5
Largest: 74.5

• Here, we initialize the variable largest to 0.


• For each iteration, iteration variable i contains current element of the list and now it is
compared with value of largest, if value of the list element is greater than the largest
value, then largest value is replaced by greater value (Value of the list element).
• This process is repeated for all the values of the List

Minimum Loops
• We can use the for loop, to find the minimum valued element of List.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

smallest =10000000
for i in [-3, 41, -12, 9, 74, 15]:
if i < smallest:
smallest=i
print(' Iteration variable value:', i, 'smallest:', smallest)
print('smallest:', smallest)

• Here, we initialize the variable smallest to maximum value


• For each iteration, iteration variable i contains current element of the list and now it is
compared with value of smallest, if value of the list element is smaller than the smallest
value, then smallest value is replaced by smaller value (Value of the list element).
• This process is repeated for all the values of the List

• Example : Program to find the sum of all numbers stored in a list


# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for i in numbers:
sum = sum+i
print("The sum is", sum)

Exception Handling [Catching Exceptions using try and except]


Exception:
• When a Python program encounters a situation which it cannot handle, it raises an
exception. In python, an exception represents an error.
• Errors that occur at runtime (after passing the syntax test) are called exceptions
Handling an exception
Python can handle exceptions using try & except statements
• If the code is suspicious or prone to runtime error, then put this code within the try block.
• In except block, put the remedy code or information about what went wrong and what is
possible way to come of it.
During the execution, if something goes wrong with code within try block, then except block
will be executed. Otherwise, the except-block will be skipped.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Example 1:
• For example, consider the following code segment
a=int(input("Enter value for a:"))
b=int(input("Enter the value for b:"))
c=a/b
print(c)
• Let us run the above code, and see output
Output :
Enter value for a:5
Enter the value for b:0
-------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call
last)
ZeroDivisionError: division by zero

• Here because of the wrong input, during runtime error has occurred and error message is
generated, but for the end-user, it is difficult to understand the such type of system-generated
error messages and handle the errors.
• By using try and except statements, we can display our own messages or solution to the user
so that problem can be handled or solved easily.
Consider the example
a=int(input("Enter value for a:"))
b=int(input("Enter the value for b:"))
try:
c=a/b
print(c)
except:
print ("Division by zero is not possible, enter non zero value for b")

Output:
Enter value for a:5
Enter the value for b:0
Division by zero is not possible, enter non zero value for b

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Ending a Program Early with sys.exit()


To terminate a program early in Python, you can use the sys.exit() function. This function is
part of the sys module, so you'll need to import sys before using it. Here's a step-by-step guide on
how to use it:

1. Import the sys Module: To use sys.exit(), you need to import the sys module at the
beginning of your script.
2. Infinite Loop Example:
o Create a loop that runs indefinitely using while True:.
o Prompt the user for input inside the loop.
3. Check User Input:
o If the user types 'exit', call sys.exit() to terminate the program.
o Otherwise, print the user's input.

Here's a simplified example:

python
Copy code
import sys

while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
Explanation of the Example

• Infinite Loop: The while True: line creates an infinite loop.


• Prompting User: The input() function asks the user to type something.
• Exit Condition: If the user types 'exit', the program calls sys.exit() to stop.
• Print Input: If the user types anything else, the program prints that input and continues the loop.

Running the Program

• Save the code in a file named exitExample.py.


• Run the program.
• The program will repeatedly ask for input until the user types 'exit'.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Functions
• As program grows larger and larger, it becomes very complicated to handle & debug, so
bigger block of code is broken into many small blocks of code (small chunks), where each
small block of code contains the group of statements & performs specific task. This small
block of code is called as function.
• Furthermore, it avoids repetition and makes the code reusable.
• Function is a group of statements or block of code that performs a specific task.
Function runs only when it is called.
• Functions can be either
• built-in or predefined
• user-defined.
• Lamba function

User-defined functions:
• Function is a group of statements or block of code that performs a specific task. Function
runs only when it is called.
• Syntax:
Note: The first line of the function is called function header and remaining part of function
(which is indented) is called body of function

Steps to define and write the used defined functions


• def: Use the def keyword followed by function name to declare a function
• parameter list: Pass the inputs to function through parameter list (should be within
the parentheses & end with colon). Its optional. Function can be without parameters
( ). If function does not require any inputs, it can be empty.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• Function body: Next to define function body: add set of statements that the function
should perform or execute.
• Return statement (optional): End the function with a return statement if the function
has some output. It is optional, if the function does not have any output, it can be
skipped.
• Finally, function is called with its name (fun_name)

Types of user defined functions:


Void Functions (Does not return o/p)
1. Without parameters and without return statement
2. With parameters and without return statement
Fruitful functions (returns o/p)
3. With parameters and with return statement
4. Without parameters and with return statement

Void Functions:
• If function does not return any value (result) to the calling function after performing
some tasks, then such function is known as void function.
• 2 types of void functions
1. Without parameters and without return statement
2. With parameters and without return statement

1. Without parameters and without return statement

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• Here we have defined function with name cricket using def keyword.
• Aim of function is to print, set of statements, so function does not require any inputs, so
parameter list is empty (without parameters)
• Function body: here function body contains only print statements, function does not output
anything, so return statement is not required, so it skipped.
• Execution: To execute the function, the function has to be called with its name and
arguments to be passed if required. So, here function is called with its name cricket () without
any arguments.

Another example:
Write a user defined function to add 2 numbers and display their sum
#function definition
def fun_add():
num 1= int(input("Enter first number: "))
num2= int(input("Enter second number: "))
y = num1 + num2
print("The sum of 2 numbers is : ", y)

# Call the function


fun_add()

Output:
Enter first number: 5
Enter second number: 6
The sum of 2 numbers is: 11
• Here we have defined function with name fun_add using def keyword.
• Here, addition operation requires the 2 input values, but these values have been accepted from
user within function itself (local variables), so no need to pass the parameters into function
externally. Hence the parameters list is empty
• Function body: here function body contains
Two input statements which accepts two values for num1 & num2.
Addition operation(sum) between num1 & num2
Print statement to print the output.
• In this case, the print statement to display the output, so the optional return statement is skipped.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• To execute the function, the function is called with name fun_add without arguments. In this
case, function uses the local variables for the computation, it does not depend on the external
values, so any arguments are passed into the function call.

Arguments and Parameters


• In the above example, the values were accepted from the user within the function body
itself, but it is also possible to accept values at the time of function call. An argument is a
value, which is passed into the function call and it is received to function body through
the parameters defined in function header.
• Note: The variable names given in the function definition are called parameters and values
given to functional call are called arguments.

2. Function with parameter and No Return value


def fun_add(x, y): # x and y are parameters
z=x+y
print("The sum of 2 numbers is : ", z)

num 1= int(input("Enter first number: "))


num2= int(input("Enter second number: "))

fun_add(num1, num2) # function call, here num1 and num2 are arguments
Output:
Enter first number: 5
Enter second number: 6
The sum of 2 numbers is: 11

• In the above program, x and y are called as parameters and num1 & num2 are called as
arguments.
• At the time of function call, the arguments num1 and num2 are passed to this function call.
fun_add(num1, num2)
• The parameter of the function header receives the argument as an input and statements
inside the function body are executed.
• Since python variables are not of specific data type, so we can pass any type of value to
the function as an argument.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Fruitful functions:
• If function returns some result to the calling function after performing some tasks, then
such function is known as Fruitful function

3. Function with Parameter and Return value


def fun_add(x, y): # x and y are parameters
z=x+y
return z

num 1= int(input("Enter first number: "))


num2= int(input("Enter second number: "))
s= fun_add(num1, num2) # function call, here num1 and num2 are
arguments
print("The sum of 2 numbers is : ", s)
Output:
Enter first number: 5
Enter second number: 6
The sum of 2 numbers is: 11

• In the above example, the function fun_add () takes two arguments and returns the result
to the calling function. Here returned value to calling function is stored in the variable s.
• When a function returns something and if it is not stored using the variable, then the return
value will vanish and not be available for the future use.
• Here in case, if we just use the statement fun_add(num1, num2) instead of
s= fun_add(num1, num2), then the value returned from the function is of no use.

4. Function without Parameter and Return value


def fun_add( ): # x and y are parameters
num 1= int(input("Enter first number: "))
num2= int(input("Enter second number: "))
z=x+y
return z

s= fun_add(num1, num2) # function call, here num1 and num2 are


arguments
print("The sum of 2 numbers is : ", s)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

• Even, the built-in mathematical functions, random number generating functions etc. are
examples for fruitful functions
import math
math.sqrt(4)
Output: 16

Built in functions
• Built-in functions are the ones, whose functionality is predefined. Here, just function
has to be called whenever the particular task has to be carried out.
• Python has huge collection of built-in functions, this is one of the reasons, why python
is preferred over other languages.

Examples:
max( ) : This function is used to find largest (maximum) value in the object or list. It can be
used for numeric values or even to strings.
1. max('Hello world')
output : 'w' # here w character is having maximum ASCII code
2. max(1, 5 ,21, 17, -8)
output : 21
min( ) : This function is used to find smallest (minimum) value in the list
1. min("hello world")
output : ‘ ‘ #space has least ASCII code here
2. min("helloworld")
output : ‘d ‘ #Character d is having minimum ASCII code
3. min(0.5, -1.2, -4.9, 1.3, 9)
output : -4.9

len(): This function is to find the length of the object. The object can be list, string , tuple
etc.
1. len(“hello how are you?”)
output : 18

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Type Conversion:
We can convert the type of the variable/value using functions int(), float(), str() etc.

Function Example
Floating point, string→ integer
• int('20') #integer enclosed within single quotes
Output:20 #converted to integer type

• int('10.22') # float enclosed within single quotes


Output: ValueError: invalid literal for int() with base 10: '10.22'

• int(‘ Hi ‘) #actual string cannot be converted to int


int() Output: ValueError: invalid literal for int() with base 10: 'Hi'

• int(-45)
Output:45

• int(3.141592) #float value being converted to integer


Output:3 #round-off will not happen, fraction is ignored

Integer, String → floating point


• float('1.99') #float enclosed within single quotes
Output:1.99 #converted to float type
float()
• float(5)
Output:5.0 #integer is converted to float 5.0
Integer, Float, List, Tuple, → string
• str(25)
Output:’25’

• str(3.14)
Output:'3.14'

str() • str([1,2,3,4])
Output:'[1, 2, 3, 4]'

• str((1,2,3,4))
Output:'(1, 2, 3, 4)'

String, tuple, set, dictionary → list


• list('Mary') # list of characters in 'Mary'
Output: ['M', 'a', 'r', 'y']
list()
• list((1,2,3,4)) # (1,2,3,4) is a tuple

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Output: [1, 2, 3, 4]

• list({1, 2, 3}) # {1, 2, 3} is a set


Output: [1, 2, 3]

string, list, set → tuple


• tuple('Mary') #string to tuple
Output: ('M', 'a', 'r', 'y')
tuple()
• tuple([1,2,3,4]) # list to tuple
Output: (1, 2, 3, 4)

string, list, tuple → set

• set('alabama')# unique character set from a string


Output:{'b', 'm', 'l', 'a'}

set() • set([1, 2, 3, 3, 3, 2])


Output:{1, 2, 3}
# handy for removing duplicates from list

Math Functions
• Python provides a set of predefined(inbuilt) mathematical functions through the package
(module) math.
• To use these inbuilt functions, we have to import the math module in our code.
• Few examples of mathematical inbuilt functions are as given below

Function Example
This function is used to find the square root of given number.
import math #importing math package
sqrt() math.sqrt(5)
Output: 2.2360

This function is used to find the power of x to y. Here it takes 2 input values x and y, then
it finds power of x to y
pow() import math
math.pow(2,4)
Output : 8

It is used to find the GCD of two integers


import math
gcd() math.gcd(2,4)
Output: 2

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Rounds off the number upward to its nearest integer.


import math
math.ceil(1.6) =>2
ceil() math.ceil(5.3) =>6
math.ceil(-5.8) =>-5
math.ceil(10.0) =>10

Rounds off the number downward to its nearest integer.


import math
math. floor(1.6) =>1
floor() math. floor(5.3) =>5
math. floor(-5.3) =>-6
math. floor(10.0) =>10

This function is used to find logarithm of the given number, to the base 10.
import math
log10() math.log10(2)
Output:0.30102

This is used to compute natural logarithm (base e) of a given number.


import math
log() math.log(2)
Output:0.693

It is used to find sine value of a given number.


Note : The valuet must be in radians (not degrees).
We can convert the degrees into radians by multiplying pi/180 as shown
import math
sin()
math.sin(90*math.pi/180)
Output : 1.0

It is Used to find cosine value


import math
cos(): math.cos(60*math.pi/180)
output : 0.50

Math constants

The constant value pi can be used directly whenever we require.


import math
print (math.pi)
Output: 3.2403

pi r=2
import math
Area =math.pi * r*r #Area of circle
print(Area)
Output: 12.56

The mathematical constant ‘e’ called Euler's number


E import math
math.e

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON APPLICATION PROGRAMMING

Output: 2.71828

Prof. Sujay Gejji ECE, SGBIT, Belagavi

You might also like