[Go to site: main page, start]

0% found this document useful (0 votes)
8 views42 pages

Python Module 1 Notes

The document outlines a Python programming module covering fundamental concepts such as variables, data types, operators, and debugging techniques. It explains the structure of a program, types of errors, and provides examples of various operators and their precedence. The content is aimed at students in the Computer Science and Engineering department at PES Institute of Technology and Management.

Uploaded by

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

Python Module 1 Notes

The document outlines a Python programming module covering fundamental concepts such as variables, data types, operators, and debugging techniques. It explains the structure of a program, types of errors, and provides examples of various operators and their precedence. The content is aimed at students in the Computer Science and Engineering department at PES Institute of Technology and Management.

Uploaded by

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

Prerana Educational and Social Trust®

PES Institute of Technology and


Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Module-1

The way of the program: The Python programming language, what is a


program? What is debugging? Syntaxerrors, Runtime errors, Semantic errors,
Experimental [Link],

Expressions and Statements: Values and data types, Variables, Variable names
and keywords, Statements, Evaluating expressions, Operators and operands,
Type converter functions, Order of operations, Operations on strings, Input,
Composition, The modulus operator.

Iteration: Assignment, Updating variables, the for loop, the while statement, The
Collatz 3n + 1 sequence, tables, two-dimensional tables, break statement,
continue statement, paired data, Nested Loops for Nested Data.

Functions: Functions with arguments and return values.

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 1
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

The Way of the Program

The Python Programming Language

 Python is a high-level, interpreted, general-purpose programming


language.
 It emphasizes code readability with simple syntax.
 Programs are written in .py files and executed by the Python interpreter.

Features:

 Easy to learn and use


 Portable and platform-independent
 Object-oriented and dynamically typed
 Rich standard library

What is a Program?

 A program is a sequence of instructions that specifies how to perform a


computation.
 Computations can involve:
o Input
o Output
o Math calculations
o Logical decisions
o Repetition (loops)

What is Debugging?

 Debugging is the process of finding and fixing errors in a program.

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 2
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Types of Errors:

Type Description Example


Syntax Mistake in grammar or structure print("Hello" (missing
Error bracket)
Runtime Error that occurs during 10 / 0 (division by zero)
Error execution
Semantic Logic error — program runs but Using + instead of *
Error gives wrong output

Experimental Debugging

 The process of testing parts of your code step-by-step.


 Add print statements or use a debugger to trace variable values.
 Helps identify which part of code behaves unexpectedly.

Variables: Definition

 A variable in Python is a named location in memory used to store data.


 It acts as a container that holds a value which can be changed during
program execution.

Example:

x = 10 # x → variable storing integer 10

name = "Alice" # name → variable storing string "Alice"

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 3
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Rules for Naming Variables


Rule Explanation Example
1. Must begin with a First character can’t be a digit ✅name, _age ❌
letter or underscore (_) 1name
2. Can contain letters, No special characters allowed ✅total_marks, ❌
digits, and underscores marks%
3. Case-sensitive Age and age are different ✅count, Count
4. Cannot use Python Reserved words like if, for, ❌for = 10
keywords class cannot be variable
names
5. Should be meaningful Improves code readability ✅student_name, ❌
x1

Examples of Variables

a) Integer Variable
a = 100
print(a)

Output:

100
b) Float Variable
pi = 3.1415
print(pi)

Output:

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 4
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

3.1415
c) String Variable
message = "Welcome to PESITM Shivamogga"
print(message)

Output:

Welcome to PESITM Shivamogga


d) Boolean Variable
flag = True
print(flag)

Output:

True
e) Multiple Assignments

Python allows assigning values to multiple variables in one line.

x, y, z = 10, 20, 30
print(x, y, z)

Output:

10 20 30
f) Same Value to Multiple Variables
a = b = c = 50
print(a, b, c)

Output:

50 50 50

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 5
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Data types: Python data types help define the nature of the data stored in variables.
They are automatically determined at runtime and categorized as: Numeric, Boolean,
String, Sequence, Set, Mapping, Binary, and None
Main Categories of Data Types

Numeric Types
Used to store numbers.

 int – Integer numbers like 10, -5, 0


 float – Decimal or real numbers like 3.14, -2.5
 complex – Numbers with real and imaginary parts like 2 + 3j

Boolean Type
Used for logical values.

 bool – Holds True or False

String Type
Used to store a sequence of characters.

 str – Example: "Python", 'Hello'

Sequence Types
Used to store collections of ordered data.

 list – Ordered and changeable collection → [1, 2, 3]


 tuple – Ordered and unchangeable collection → (10, 20, 30)
 range – Represents a sequence of numbers → range(5)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 6
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Example:
a = 10
b = 3.14
c = 2 + 3j
d = True
e = "Python"
f = [1, 2, 3]
g = (4, 5, 6)
h = {"name": "Rahul", "age": 20}
i = {1, 2, 3}
j = None

print(type(a), type(b), type(c))


print(type(d), type(e), type(f))
print(type(g), type(h), type(i))
print(type(j))
output:
<class 'int'> <class 'float'> <class 'complex'>
<class 'bool'> <class 'str'> <class 'list'>
<class 'tuple'> <class 'dict'> <class 'set'>
<class 'NoneType'>
Note: This program displays the data type of each variable using the type()
function

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 7
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Operators: Operators are symbols that perform operations on values or variables.


Python supports several types of operators grouped by functionality.

Operator Operators Description


Type
Arithmetic +, -, *, /, //, %, ** Addition, Subtraction, Multiplication,
Division, Floor Division, Modulus,
Exponentiation
Comparison ==, !=, >, <, >=, <= Equal, Not Equal, Greater, Less, Greater
or Equal, Less or Equal
Logical and, or, not Logical AND, Logical OR, Logical NOT
Assignment =, +=, -=, *=, /=, =, ^=, >>=, <<=`
//=, %=, **=, &=, `
Bitwise &, ` , ^, ~, <<, >>`
Membership in, not in Check membership in a sequence
Identity is, is not Check if objects are the same (identity)

Arithmetic Operators
# Arithmetic Operators Example
a = 10
b = 3
print("a + b =", a + b) # Addition
print("a - b =", a - b) # Subtraction
print("a * b =", a * b) # Multiplication
print("a / b =", a / b) # Division
print("a // b =", a // b) # Floor Division
print("a % b =", a % b) # Modulus
print("a ** b =", a ** b) # Exponentiation
Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 8
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Sample Output:

a + b = 13
a - b = 7
a * b = 30
a / b = 3.3333333333333335
a // b = 3
a % b = 1
a ** b = 1000

Comparison Operators

# Comparison Operators Example


a = 10
b = 3

print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
print("a >= b:", a >= b)
print("a <= b:", a <= b)

Sample Output:

a == b: False
a != b: True
a > b: True
a < b: False
a >= b: True
a <= b: False
Logical Operators
# Logical Operators Example
x = True
Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 9
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

y = False

print("x and y:", x and y)


print("x or y:", x or y)
print("not x:", not x)

Sample Output:

x and y: False
x or y: True
not x: False
Assignment Operators
# Assignment Operators Example
c = 5
print("c =", c)

c += 3
print("c += 3 ->", c)

c -= 2
print("c -= 2 ->", c)

c *= 4
print("c *= 4 ->", c)

c /= 3
print("c /= 3 ->", c)

c %= 2
print("c %= 2 ->", c)

c **= 3
print("c **= 3 ->", c)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 10
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

c //= 2
print("c //= 2 ->", c)

Sample Output:

c = 5
c += 3 -> 8
c -= 2 -> 6
c *= 4 -> 24
c /= 3 -> 8.0
c %= 2 -> 0.0
c **= 3 -> 0.0
c //= 2 -> 0.0

Bitwise Operators
# Bitwise Operators Example
p = 5 # 0101 in binary
q = 3 # 0011 in binary

print("p & q =", p & q)


print("p | q =", p | q)
print("p ^ q =", p ^ q)
print("~p =", ~p)
print("p << 1 =", p << 1)
print("p >> 1 =", p >> 1)

Sample Output:

p & q = 1
p | q = 7
p ^ q = 6
~p = -6
p << 1 = 10
p >> 1 = 2

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 11
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Membership Operators
# Membership Operators Example
list1 = [1, 2, 3, 4, 5]

print("3 in list1:", 3 in list1)


print("6 not in list1:", 6 not in list1)

Sample Output:

3 in list1: True
6 not in list1: True
Identity Operators
# Identity Operators Example
a1 = 10
b1 = 10

print("a1 is b1:", a1 is b1)


print("a1 is not b1:", a1 is not b1)

Sample Output:

a1 is b1: True
a1 is not b1: False

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 12
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Operator Precedence:

Level Operators Description


1 () Parentheses (do first)
2 ** Exponent / Power
3 +x, -x, ~x Unary plus, Unary minus, Bitwise NOT
4 *, /, //, %, +, - Multiply, Divide, Floor Div, Mod, Add,
Subtract
5 <<, >>, &, ^, ` `Shift Operator
6 ==, !=, >, <, >=, <=, Comparison & Logical operators
not, and, or
7 =, +=, -=, *=, /=, Assignment operators
//=, %= , **=

Python Operator Precedence – Examples

Question 1
result = -2 ** 3 ** 2

Answer: -512
Explanation: Exponentiation first (3 ** 2 = 9), then 2 ** 9 = 512, unary minus
applied → -512

Question 2
x + y * z ** 2 // y - z

Answer: 14
Explanation: z ** 2 = 16, y * 16 = 48, 48 // y = 16, x + 16 = 18, 18 - z = 14

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 13
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Question 3
a & b | c ^ a

Answer: 7
Explanation: a & b = 1, c ^ a = 7, 1 | 7 = 7

Question 4
x or y and not x or y

Answer: True
Explanation: not x = False, y and False = False, x or False = True, True or y =
True

Question 5
a << b >> c + 1

Answer: 64
Explanation: c + 1 = 3, a << b = 512, 512 >> 3 = 64

Question 6
not x < y and x + y > 12

Answer: False
Explanation: x < y = True, not True = False, x + y > 12 = True, False and True =
False

Question 7
x ** y % z * 2 + 1

Answer: 3
Explanation: x ** y = 81, 81 % z = 1, 1 * 2 = 2, 2 + 1 = 3

Question 8
a & ~b | b ^ a

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 14
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Answer: 5
Explanation: ~b = -3, a & -3 = 5, b ^ a = 5, 5 | 5 = 5

Question 9
x + y << z ** 2

Answer: 327680
Explanation: z ** 2 = 16, x + y = 5, 5 << 16 = 327680

Question 10
x and y or not z and x or y

Answer: 2
Explanation: not z = False, x and y = 2, False and x = False, 2 or False = 2, 2 or y
=2

Question 11
x in lst and lst[0] is not x or lst[-1] == x

Answer: True
Explanation: x in lst = True, lst[0] is not x = True, True and True = True, lst[-1]
== x = True, True or True

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 15
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Input and Output in Python:

Definition
The input() function in Python is used to take input from the user during
program execution. It allows the user to enter data through the keyboard.

Syntax
variable = input('Message for the user: ')

The message inside quotes is displayed as a prompt. The function always returns the
input as a string.

 Example 1: Reading a string input

name = input("Enter your name: ")


print("Hello", name)

 Example 2: Reading integer input

a = int(input("Enter a number: "))


print("You entered:", a)

 Example 3: Reading float input

radius = float(input("Enter radius of circle: "))


area = 3.14 * radius * radius
print("Area =", area)

Type Conversion with input()


Function Description Example Output Type
int() Converts string int(input()) Integer
to integer
float() Converts string float(input()) Float

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 16
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

to float
str() Converts input str(input()) String
to string

1. Write a Python program to input the marks of three subjects and print the
average.
sub1 = float(input("Enter marks of Subject 1: "))
sub2 = float(input("Enter marks of Subject 2: "))
sub3 = float(input("Enter marks of Subject 3: "))

average = (sub1 + sub2 + sub3) / 3


print("Average marks =", average)

2. Write a program to read name, age, and branch of a student and display them
neatly.

name = input("Enter your name: ")


age = int(input("Enter your age: "))
branch = input("Enter your branch: ")
print("Student Details")
print("Name :", name)
print("Age :", age)
print("Branch:", branch)

3. Python program to find the area of a circle


radius = float(input("Enter the radius of the circle: "))
area = 3.14 * radius * radius

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 17
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

print("Area of the circle =", area)

4. Python program to find the area of a triangle

base = float(input("Enter the base of the triangle: "))


height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print("Area of the triangle =", area)

Output Statement:

Definition
The print() function in Python is used to display information on the screen. It
can display text, numbers, variables, or expressions.

Syntax
print(value)

Examples
 Example 1: Printing text

print("Welcome to Python")

 Example 2: Printing numbers

print(10)

 Example 3: Printing variables

name = "Ananya"
age = 19

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 18
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

print(name)
print(age)

 Example 4: Printing multiple values

name = "Ananya"
age = 19
print("Name:", name, "Age:", age)

 Example 5: Printing expression

a = 10
b = 20
print("Sum =", a + b)

Type Conversion in Python

Type conversion (also called type casting) means converting a value from one data
type to another.

There are two types:

1. Implicit Type Conversion (Type Casting)


2. Explicit Type Conversion (Type Casting)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 19
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

1. Implicit Type Conversion

 Python automatically converts one data type to another in expressions to


prevent data loss.

Example:

x = 5 # int
y = 3.2 # float
z = x + y # int + float → float
print(z) # Output: 8.2
print(type(z)) # Output: <class 'float'>

Explanation:

 Python converts x to float automatically before adding it to y.

2. Explicit Type Conversion

 Done manually using type conversion functions.


 Converts variables from one type to another.

# Integer conversion
a = int(4.9)
print(a) # 4

# Float conversion
b = float("3.14")
print(b) # 3.14

# String conversion
c = str(100)
print(c) # '100'

# Boolean conversion
Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 20
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Looping Statements in Python


 Loops are used to repeat a block of code multiple times.
 Python has two main types of loops:
1. for loop – iterates over a sequence.
2. while loop – repeats as long as a condition is true.

The for Loop

The for loop is a control flow statement that allows you to iterate over a sequence
(like a list, tuple, string, or range) and execute a block of code for each item.
It is also called a definite loop because the number of iterations is usually known in
advance.

Syntax:

for variable in sequence:


# code block

 variable: Takes each value from the sequence one by one.


 sequence: Can be a list, tuple, string, or a range of numbers.
 code block: Indented statements executed for each value of the variable.

Example: Print numbers 1 to 5

for i in range(1, 6):


print(i)

Output:

1
2
3
4
5

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 21
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Execution Flow of a for Loop

1. Take the first element from the sequence and assign it to the loop variable.
2. Execute the loop body using this variable.
3. Move to the next element in the sequence.
4. Repeat steps 2–3 for all elements in the sequence.
5. When all elements are processed, the loop terminates and the program continues
with the next instructions.

The while Loop

The while loop is a control flow statement that allows code to be executed
repeatedly as long as a specified condition is True.

 Syntax:

while condition:
# code block
 Example: Print numbers 1 to 5

i = 1
while i <= 5:
print(i)
i += 1
Execution Flow of a while Loop

1. Check the condition at the start of the loop.


2. If the condition is True, the loop executes its statements.
3. After running the loop body, the condition is evaluated again.
4. This cycle continues until the condition becomes False.
5. Once the condition is False, the loop terminates, and the program continues
with the next instructions.

Examples on while loop:

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 22
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Q1. Print numbers from 1 to 50 using a while loop

i = 1
while i <= 50:
print(i, end=" ")
i += 1

Output:

1 2 3 ... 50

Q2. Sum of first N natural numbers

N = int(input("Enter N: "))
sum = 0
i = 1
while i <= N:
sum += i
i += 1
print("Sum of first", N, "numbers:", sum)

Example Input/Output:

Enter N: 5
Sum of first 5 numbers: 15

Q3. Factorial of a number

n = int(input("Enter a number: "))


fact = 1
i = 1
while i <= n:
fact *= i
i += 1
print("Factorial of", n, "is", fact)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 23
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Example:

Enter a number: 5
Factorial of 5 is 120

Q4. Collatz 3n + 1 Sequence

n = int(input("Enter a positive integer: "))


while n != 1:
print(n, end=" ")
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(1)

Input/Output:

Enter a positive integer: 6


6 3 10 5 16 8 4 2 1

Q5. Reverse a number

num = int(input("Enter a number: "))


rev = 0
while num > 0:
rev = rev * 10 + num % 10
num = num // 10
print("Reversed number:", rev)

Example:

Enter a number: 1234


Reversed number: 4321

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 24
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

For Loop Programs

Q1. Print numbers from 1 to 100

for i in range(1, 101):


print(i, end=" ")

Q2. Print squares of first N natural numbers

N = int(input("Enter N: "))
for i in range(1, N+1):
print(i, "squared is", i**2)

Input/Output:

Enter N: 5
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

Q3. Multiplication table for a number

num = int(input("Enter a number: "))


for i in range(1, 11):
print(num, "x", i, "=", num*i)

Input/Output:

Enter a number: 3
3 x 1 = 3
3 x 2 = 6
...
3 x 10 = 30

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 25
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

break and continue Statement


break Statement

Definition:

The break statement in Python is used to terminate the loop immediately, regardless
of the loop’s condition.
When the program encounters break, it exits the nearest enclosing loop (either for
or while).

Syntax:

for variable in sequence:


if condition:
break
# statements

or

while condition:
if condition2:
break
# statements

Example 1: Using break in a for loop

for i in range(1, 11):


if i == 6:
break
print(i)
print("Loop ended.")

Output:

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 26
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

1
2
3
4
5
Loop ended.

Example 2: Using break in a while loop

i = 1
while i <= 10:
if i == 5:
break
print(i)
i += 1
print("Exited from loop.")

Output:

1
2
3
4
Exited from loop.

Continue Statement: Definition:

The continue statement is used to skip the current iteration of the loop and
move directly to the next iteration.

It does not terminate the loop like break; it only skips certain parts of the loop
body based on a condition.

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 27
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Syntax:

for variable in sequence:


if condition:
continue
# rest of code

or

while condition:
if condition2:
continue
# rest of code

Explanation:

 When continue is encountered, Python immediately skips the remaining


statements in the current loop iteration.
 Control moves to the next iteration of the loop.

Example 1: Using continue in a for loop

for i in range(1, 6):


if i == 3:
continue
print(i)

Output:

1
2
4
5

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 28
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Explanation:

 The loop runs from 1 to 5.


 When i == 3, continue is executed → that iteration is skipped.
 Hence, 3 is not printed.

Example 2: Using continue in a while loop

i = 0
while i < 5:
i += 1
if i == 2:
continue
print(i)

Output:

1
3
4
5
Nested Loops:

 A nested loop is a loop inside another loop.


 Useful for tables, grids, or lists inside lists.

Simple Example: Print a 2D Table

# 2D list (table)
table = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 29
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

# Nested for loop


for row in table: # Outer loop → rows
for item in row: # Inner loop → items in
row
print(item, end=" ")
print() # Move to next line after
each row

Output:

1 2 3
4 5 6
7 8 9

Multiplication Table (Beginner Style)


for i in range(1, 4): # Rows
for j in range(1, 4): # Columns
print(i*j, end=" ")
print()

Output:

1 2 3
2 4 6
3 6 9

Functions: Functions with arguments and return values.


Definition:

A function is a block of reusable code that performs a specific task.


Instead of writing the same code multiple times, you can put it in a function and
call it whenever needed.

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 30
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Advantages of Using Functions:

1. Reducing Code Repetition:


o Instead of writing the same logic repeatedly, you can define it once
in a function and reuse it.
2. Improving Readability:
o Functions help to break a large program into smaller,
understandable parts.
3. Modular Programming:
o Functions make the program modular. Each function handles a
single task, making it easier to manage and debug.

Syntax of a Python Function:

def function_name(parameters):
# statements
return value

 def → keyword used to define a function


 function_name → name of the function (choose descriptive names)
 parameters → optional inputs passed to the function
 return → optional keyword used to return a value from the function

Example 1: Function without Parameters

def greet():
print("Hello, welcome to Python!")

greet() # Calling the function

Output:

Hello, welcome to Python!

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 31
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Example 2: Function with Parameters and Return Value

def add_numbers(a, b):


result = a + b
return result

sum1 = add_numbers(10, 5) # Passing arguments


to the function
print("Sum =", sum1)

Output:

Sum = 15
Write a function to calculate the addition of two no.

i)without parameters.
ii) with parameters.
iii) with return statements.

i) Function Without Parameters

 The function does not take any input, and the numbers are defined inside
the function.

def add_numbers():
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum:", sum)

# Call the function


add_numbers()

Example Input/Output:

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 32
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Enter first number: 5


Enter second number: 7
Sum: 12
ii) Function With Parameters

 The function takes numbers as parameters and prints the sum.

def add_numbers(a, b):


sum = a + b
print("Sum:", sum)

# Call the function with arguments


add_numbers(5, 7)

Output:

Sum: 12
iii) Function With Return Statement

 The function returns the sum, which can be stored in a variable or printed.

def add_numbers(a, b):


return a + b

# Call the function and store result


result = add_numbers(5, 7)
print("Sum:", result)

Output:

Sum: 12

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 33
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Scope of variables in Python: Local and Global Variables in


Python
Definition:

In Python, variables are used to store data values.


The scope of a variable defines where that variable can be accessed or modified in a
program.

Local Variables:

 A local variable is defined inside a function and can be used only within that
function.
 It is created when the function starts and destroyed when the function ends.
 Local variables cannot be accessed outside their function.

Example:

def test():
x = 10 # Local variable
print("Inside function:", x)

test()
print("Outside function:")
# print(x) # Error: x is not defined outside the
function

Explanation:

 x is local to the function display().


 It exists only while the function is executing.

Global Variables:

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 34
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

 A global variable is declared outside all functions.


 It can be accessed inside or outside any function in the program.
 If you want to modify a global variable inside a function, you must use the
global keyword.

Example:

y = 20 # Global variable

def show():
x=10 # Local variable
print("Inside function:", x,y)

show()
print("Outside function:", x)

Output:
Inside function: 10 20
Outside function: 10

Modifying Global Variables Inside a Function:

To change the value of a global variable inside a function, use the global keyword.

Example:

x = 5

def change():
global x
x = x + 10
print("Inside function:", x)

change()

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 35
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

print("Outside function:", x)

Output:

Inside function: 15
Outside function: 15

Difference Between Local and Global Variables

Feature Local Variable Global Variable


Declared in Inside a function Outside all
functions
Scope Within the function only Whole program
Lifetime Created when function starts, Exists till the
destroyed when it ends program ends
Access from other Not possible directly Possible in any
functions function

Example Showing Both Scopes:

x = 100 # Global variable

def test():
x = 50 # Local variable
print("Inside function:", x)

test()
print("Outside function:", x)

Output:

Inside function: 50
Outside function: 100

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 36
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

lambda function with an example.


Definition:

In Python, a lambda function is a small anonymous function — meaning it has


no specific name.
It is used to perform simple operations in a single line, usually where defining a
full function using def is not necessary.

Syntax:

lambda arguments : expression

 lambda → Keyword used to define the function.


 arguments → Inputs to the function (can be one or more).
 expression → A single statement that gets evaluated and
returned.

Example 1: Addition of Two Numbers

Program:

# Lambda function to add two numbers


add = lambda x, y: x + y

# Calling the lambda function


result = add(15, 25)
print("Sum of two numbers:", result)

Output:

Sum of two numbers: 40

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 37
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Example 2: Subtraction of Two Numbers

Program:
# Lambda function to subtract two numbers
sub = lambda a, b: a - b

# Calling the lambda function


result = sub(20, 8)

print("The difference is:", result)


Output:
The difference is: 12
Example 3 : Square of a Number

Program:
# Lambda function to find the square of a number
square = lambda x: x * x

# Calling the lambda function


result = square(6)

print("The square of the number is:", result)


Output:
The square of the number is: 36

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 38
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

Module 1: Question Bank

1.a) What is debugging? Explain the types of errors in Python with


examples. (5 Marks)
b) Write a Python program to demonstrate all three types of errors: Syntax,
Runtime, and Semantic errors. (5 Marks)

2.a) Define variables in Python. Explain the rules for naming variables with
examples. (5 Marks)
b) Write a Python program to demonstrate multiple assignment and type
checking using type() function. (5 Marks)

3.a) Explain different data types in Python with suitable examples. (5


Marks)
b) Write a Python program to display the data type of different variables
such as integer, float, string, list, tuple, dictionary, and set. (5 Marks)

4.a) What are operators in Python? Explain various types of operators with
suitable examples. (5 Marks)
b) Write a Python program to demonstrate arithmetic, comparison, logical,
and bitwise operators. (5 Marks)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 39
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

5.a) Explain operator precedence in Python with examples. (5 Marks)


b) Evaluate the following expressions according to operator precedence
and show step-by-step calculation:
i) result = -2 ** 3 ** 2
ii) x + y * z ** 2 // y - z
iii) a & ~b | b ^ a (5 Marks)

6.a) Explain type conversion in Python. Distinguish between implicit and


explicit type conversion with examples. (5 Marks)
b) Write a Python program to demonstrate all four conversion functions:
int(), float(), str(), and bool(). (5 Marks)

7.a) Explain the use of input() and print() functions in Python with
syntax and examples. (5 Marks)
b) Write a Python program to read the marks of three subjects, calculate
the average, and display the result. (5 Marks)

8.a) Explain the working of the for loop in Python. Give syntax and an
example. (5 Marks)
b) Write a Python program to print the multiplication table of a given
number using a for loop. (5 Marks)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 40
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

9.a) Explain the working of the while loop in Python. Compare it with the
for loop. (5 Marks)
b) Write a Python program to display the Collatz 3n + 1 sequence for a given
number. (5 Marks)

10.a) Explain the use of break and continue statements in loops with
examples. (5 Marks)
b) Write a Python program using a for loop that prints numbers from 1 to
10, but skips 5 and stops when the number is 8. (5 Marks)

11.a) What is a nested loop? Explain with a suitable example. (5 Marks)


b) Write a Python program using nested loops to print a 3×3 multiplication
table. (5 Marks)

12.a) Define a function in Python. Explain its syntax and advantages. (5


Marks)
b) Write Python programs to demonstrate:
i) Function without parameters
ii) Function with parameters
iii) Function with return value (5 Marks)

13.a) Explain local and global variables with examples. (5 Marks)


b) Write a Python program to demonstrate modifying a global variable
inside a function using the global keyword. (5 Marks)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 41
Prerana Educational and Social Trust®
PES Institute of Technology and
Management
NH-206,Sagar Road,Shivamogga-577204
Department Computer Science and Engineering (Data Science)

14.a) What is a lambda function? Write its syntax and advantages. (5


Marks)
b) Write lambda functions for the following operations:
i) Addition of two numbers
ii) Square of a number
iii) Find maximum of two numbers (5 Marks)

15.a) Explain experimental debugging. Why is it important for beginners?


(5 Marks)
b) Write a Python program that contains a logical error. Then, use print
statements to find and fix the bug. (5 Marks)

Dr. Sunitha Pramod , Prof and HOD CSE(DS), PESTIM, Shivamogga Page 42

You might also like