0% found this document useful (0 votes)
3 views44 pages

Python Module1 Notes

Uploaded by

manojgna2007
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)
3 views44 pages

Python Module1 Notes

Uploaded by

manojgna2007
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

Mysore College Of Engineering And Management Prepared By Kamakshi M R

MODULE 1

The Python Programming Language

1.1 Introduction to Python

Python is a high-level programming language.


Other examples of high-level languages include:

• C++
• PHP
• Pascal
• C#
• Java

Computers cannot directly understand high-level languages. They only understand low-level languages
(machine language or assembly language).

Therefore, programs written in high-level languages must be translated before execution.


In Python, this translation is done using an Interpreter.

Advantages of High-Level Languages

High-level languages are widely used because:

• They are easier and faster to program


• Programs are shorter and easier to read
• Programs are more likely to be correct
• They are portable (can run on different computers with little or no changes)

1.2 Python Interpreter

The Python Interpreter is the engine that translates and executes Python code.

Example:

>>> 2 + 2
4
1
Mysore College Of Engineering And Management Prepared By Kamakshi M R

The interpreter can be used in two modes:

1. Prompt Mode (Immediate Mode)

• Code is typed directly into the interpreter.


• Results are shown immediately.
• Useful for testing small pieces of code.

Example:

>>> 5 * 3
15

2. Script Mode

• Code is written in a file (called a script).


• The file is saved and then executed.
• Suitable for longer programs.
• Scripts can be saved, printed, and reused.

The file is saved with extension .py

Example:

File name: [Link]

a=5
b = 10
print(a + b)

Output:

15

Development Environments (IDEs)

2
Mysore College Of Engineering And Management Prepared By Kamakshi M R

An Integrated Development Environment (IDE) combines:

• A text editor
• Tools to run programs
• Debugging features

Examples:

• Spyder
• Thonny
• Jupyter Notebook

What is Programming?

Definition:

A program is a sequence of instructions that tells the computer how to perform a computation.

Computation can be:

• Mathematical (e.g., solving equations)


• Symbolic (e.g., searching text in a file)

Although programming languages look different from each other, they all share a few basic kinds of
instructions:

Basic Types of Instructions in All Programming Languages

1. Input
o Getting data from keyboard, file, or device.
2. Output
o Displaying data on screen or sending to file/device.
3. Mathematical Operations
o Addition, subtraction, multiplication, division.
4. Conditional Execution
o Performing actions based on conditions.
5. Repetition (Loops)

3
Mysore College Of Engineering And Management Prepared By Kamakshi M R

o Repeating actions multiple times.

1.3 What is Debugging?

Programming is done by humans, so mistakes are common.

• These mistakes are called bugs


• The process of finding and fixing bugs is called debugging

The term “bug” was used as early as 1889 by Thomas Edison

Types of Errors in Python

1.4 Syntax Errors

Definition:

Errors in the structure (grammar) of the program.

Python follows strict syntax rules. If rules are violated:

• The program stops immediately


• An error message is displayed

Example:

print("Hello" # Missing closing parenthesis

 Program will NOT run  Even a small mistake causes an error

Runtime Errors

Definition:

Errors that occur while the program is running.

Also called Exceptions.

Example:
4
Mysore College Of Engineering And Management Prepared By Kamakshi M R

x = 10 / 0 # Division by zero

• Program starts running


• Stops when error occurs
• More common in complex programs

Semantic Errors

Definition:

Errors in the logic or meaning of the program.

• Program runs without crashing


• Output is incorrect

Example:

# Wrong formula for average


Average = total * count # Should be total / count

The program runs successfully but gives the wrong result.

• Hardest type of error to detect


• Requires checking output carefully
• Need logical thinking to fix

• Debug each step so the program remains in a working state.

This way, you avoid being overwhelmed by too many errors at once.

Formal and Natural Languages

Natural Languages

5
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Natural languages are the languages that humans speak in everyday life, such as English, Spanish, French,
Hindi, and many others. These languages were not carefully designed; instead, they evolved naturally over
centuries. Although people try to organize them with grammar rules, exceptions are common. Natural
languages are often flexible, rich in meaning, and sometimes ambiguous.

Formal Languages

Formal languages, on the other hand, are created by people for specific purposes.

• Example: The notation used by mathematicians to express equations, or the symbols chemists use
to represent molecules (like H₂O).
• Most importantly, programming languages such as Python, C, and Java are formal languages
designed to express computations clearly and precisely.

Formal languages have strict rules of syntax (rules that define what is valid and what is not). Unlike natural
languages, there is no room for ambiguity.

Formal and Natural Languages

Natural Languages

Natural languages are the languages that humans speak in everyday life, such as English, Spanish, French,
Hindi, and many others. These languages were not carefully designed; instead, they evolved naturally over
centuries. Although people try to organize them with grammar rules, exceptions are common. Natural
languages are often flexible, rich in meaning, and sometimes ambiguous

Formal Languages

Formal languages, on the other hand, are created by people for specific purposes.

• Example: The notation used by mathematicians to express equations, or the symbols chemists use
to represent molecules (like H₂O).
• Most importantly, programming languages such as Python, C, and Java are formal languages
designed to express computations clearly and precisely.

Formal languages have strict rules of syntax (rules that define what is valid and what is not). Unlike natural
languages, there is no room for ambiguity.

6
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Syntax Rules

Syntax rules in formal languages come in two forms:

1. Tokens – The smallest building blocks of the language (like words in English). Tokens can be:
o Words
o Numbers
o Symbols (like +, =, ,, (, ))

Example in Python:

print("Happy New Year for ", 2013)

This has 6 tokens:

• print (function name)


• ( (open parenthesis)
• "Happy New Year for " (string)
• , (comma)
• 2013 (number)
• ) (close parenthesis)

Errors can happen when you use an illegal token:

o 3 = + 6 $ → $ is not a valid mathematical token.


o 2Zz in chemistry → invalid because no element has the symbol "Zz".
2. Structure – The way tokens are arranged together. Even if the tokens themselves are valid, the
structure may be incorrect.
o Example: 3=+6$ is wrong because + cannot directly follow =.
o Example in Python:
o print)"Happy New Year for ",2013(

Here, the tokens are valid but placed in the wrong order, making the structure illegal

The First Program – Hello, World!

• Tradition: First program in any language → displays Hello, World!


7
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• Python code:

print("Hello, World!")

• print() function: Displays output on the screen (not on paper).


• Quotation marks: Mark beginning and end of the string (not shown in output).

Output:

Hello, World!

Comments in Python

A comment is a line or part of a line in a program that is ignored by the Python interpreter.

Comments are used to:

• Explain the code


• Make programs easier to understand
• Add notes for other programmers
• Improve readability

Example:

• # This is a comment

print("Hello, World!") # Inline comment

Types of Comments in Python

1️ Single-Line Comments

• Begin with the # (hash) symbol


• Everything after # on that line is ignored

Example:

8
Mysore College Of Engineering And Management Prepared By Kamakshi M R

# This is a single-line comment


print("Hello World") # This prints output

2️ Multi-Line Comments

Python does not have a special multi-line comment symbol, but we can write multi-line comments in two
ways:

Method 1: Multiple # Symbols

# This is a comment
# written in
# multiple lines

Method 2: Triple Quotes (''' or """)

Triple quotes for multi-line strings

''' or """ are mainly used to create multi-line strings.

Python executes the program normally and ignores that block.


But technically, this is not a real comment.

 Python treats it as a string literal

 Since it is not assigned to any variable, it is unused

 So it gets ignored

'''
This is a
multi-line comment
in Python
'''

Proper way to write comments in Python

9
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Single-line comment:

# This is a comment
print("Hello")

Multiple lines:

# This is line 1
# This is line 2
# This is line 3

Values

A value is any data or information that a program works with, such as numbers, text, or logical
resultsValues can be:

Types of Values

1. Numeric Values
Represent numbers.
Examples:

10
3.14
-5

2. String Values
Represent text (written inside quotes).
Examples:

"Hello"
'Kavya'

10
Mysore College Of Engineering And Management Prepared By Kamakshi M R

3. Boolean Values
Represent logical values.
Examples:

True
False

Examples of Values

10
3.14
"Hello"
True

Data Types

A data type specifies the kind of value a variable can store and determines the operations that can be
performed on it.

Every value in Python belongs to a specific data type.

• Values are classified into different classes, or data types:

Main Built-in Data Types

1️ Integer (int)

• Whole numbers (positive or negative)


• No decimal point

Examples:

10
-5
0

2️ Float (float)

11
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• Decimal numbers
• Numbers with fractional part

Examples:

3.14
-2.5
0.0

3️ String (str)

• Sequence of characters
• Written inside single (' ') or double (" ") quotes

4 Boolean (bool)

• Represents truth values


• Only two possible values:

True
False

Examples:

"Hello"
'Python'
"123"

• Strings are enclosed in quotation marks.

Checking Data Type

We use the type() function to check the data type of a value.

Example:

12
Mysore College Of Engineering And Management Prepared By Kamakshi M R

type(10) # int
type(3.14) # float
type("Hi") # str
type(True) # bool

Type Conversion in Python

Strings That Look Like Numbers

Type Conversion is the process of converting a value from one data type to another.

In Python, this is important because different data types behave differently, and sometimes we need to
convert data to perform correct operations.

why Type Conversion is Needed

Type conversion is required when:

• Performing operations on different data types


• Taking input from the user (input is always string)
• Ensuring correct calculations
• Avoiding errors in programs

Types of Type Conversion

1 Implicit Type Conversion (Automatic)

• Done automatically by Python


• No need for programmer intervention
• Usually happens when mixing data types

Example:

x = 10 # int
y = 2.5 # float

13
Mysore College Of Engineering And Management Prepared By Kamakshi M R

result = x + y # int is converted to float automatically


print(result) # 12.5

• Python converts smaller type → larger type (int → float)


• No data loss usually

2️ Explicit Type Conversion (Type Casting)

• Done manually by the programmer


• Uses built-in functions

Common Type Conversion Functions

1. int()

The int() function is used to convert a given value into an integer (whole number) data type.

Working

• Removes the decimal part when converting from float


• Converts numeric strings into integers
• Returns an integer value

🔹 Syntax

int(value) Examples

int("5") #5
int(3.9) #3
int(True) #1

2. float()

Definition

14
Mysore College Of Engineering And Management Prepared By Kamakshi M R

The float() function is used to convert a value into a floating-point number (decimal number)

• Converts integers to decimal form


• Converts numeric strings into floating-point numbers
• Returns a float value

Syntax

float(value)

Examples

float(10) # 10.0
float("3.14") # 3.14
float(5) # 5.0

3. str()

The str() function is used to convert a value into a string (text) data type.

• Converts numbers, booleans, or other data into string format


• Used for displaying output or combining text

Syntax

str(value)

Examples

str(100) # "100"
str(3.5) # "3.5"
str(True) # "True"

• Values like "17" or "3.2" are strings, not numbers, because they are in quotes:

String Formats

• Strings can be enclosed in:

15
Mysore College Of Engineering And Management Prepared By Kamakshi M R

o Single quotes → 'This is a string.'


o Double quotes → "And so is this."
o Triple quotes → '''and even this...''' or """and this."""
• Examples:
• >>> type('This is a string.')
• <class 'str'>
• >>> type("And so is this.")
• <class 'str'>
• >>> type("""and this.""")
• <class 'str'>
• >>> type('''and even this...''')
• <class 'str'>
• Single vs double quotes inside strings:
o Double quotes can include single quotes: "Bruce's beard"
o Single quotes can include double quotes: 'The knights who say "Ni!"'

🔹 Triple-Quoted Strings

• Triple-quoted strings can contain both single and double quotes:


• >>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
• "Oh no", she exclaimed, "Ben's bike is broken!"

They can also span multiple lines:

• >>> message = """This message will


• ... span several
• ... lines."""

🔹 Numbers and Commas

• Large integers should not have commas:


• >>> 42000
• 42000
• >>> 42,000
• (42, 0)

16
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• 42,000 is not an integer, Python interprets it as a tuple (42, 0).


• Rule: No commas or spaces in numbers.

Variables

• A variable is a named location used to store a value in memory, and the value can change during
program execution.
• The assignment statement gives a value to a variable:

Example

x = 10
name = "Kavya"

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159

• message → "What's up, Doc?"


• n → 17
• pi → 3.14159

= assigns a value; == checks equality.

>>> 17 = n
SyntaxError: can't assign to literal

Variables are changeable:

>>> day = "Thursday"


>>> day
'Thursday'
>>> day = "Friday"
>>> day
17
Mysore College Of Engineering And Management Prepared By Kamakshi M R

'Friday'
>>> day = 21
>>> day
21

Variables can change value and type.

Rules for Variable Names

• Variable names can be arbitrarily long.


• They can contain letters, digits, and underscores, but must start with a letter or underscore.
• Case matters: Bruce and bruce are different variables.
• Underscores are often used in multi-word names:

Code:
my_name
price_of_tea_in_china

Beginners should start names with a letter to avoid confusion.

Illegal names cause syntax errors:

Code:

>>> 76trombones = "big parade"


SyntaxError: invalid syntax

>>> more$ = 1000000


SyntaxError: invalid syntax

>>> class = "Computer Science 101"


SyntaxError: invalid syntax

o 76trombones → starts with a digit


o more$ → contains illegal character $
o class → keyword, cannot be used as variable name

18
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Python Keywords

• Keywords are reserved words that have predefined meanings and are used to define the syntax and
structure of a program. They cannot be used as identifiers such as variable names, function names, or
class names.
• Common keywords:

and, as, assert, break, class, def, del, elif, else, continue,
except, finally, for, from, global, if, import, in, is, lambda,
nonlocal, not, or, pass, raise, return, try, while, with, yield,
True, False, None

Statements

• A statement is an instruction the Python interpreter can execute.


• Examples of statements:
o Assignment → x = 10
o Conditional → if x > 0:
o Loop → for i in range(5):
o Import → import math
• Statements perform an action but do not produce a value

Expressions

• An expression is a combination of values, variables, operators, and function calls that produces a
result.
• Examples:
o 1 + 1 → evaluates to 2
o len("hello") → evaluates to 5
o x + y, a * b, 3 ** 2
• Expressions can appear on the right-hand side of assignment statements.
• x = len("hello")
• y = 3.14

Operators and Operands

19
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Def: Operators are special symbols used to perform operations such as addition, subtraction,
multiplication, and division.

Operands

The values or variables on which operators perform operations are called operands.

• Operator → symbol that represents a computation.


• Operands → values on which the operator acts.
• Examples:
o + addition → 2 + 3 = 5
o - subtraction → 5 - 2 = 3
o * multiplication → 4 * 2 = 8
o / division (float result)
o // floor division (integer result)
o ** exponentiation (power)
o () → used for grouping

Division Operator

Operator Description Example Result


/ True (float) division 7/4 1.75
// Floor division (whole number) 7 // 4 1

Example:

minutes = 645
hours = minutes / 60 # 10.75
hours = minutes // 60 # 10

• / gives fractional result


• // gives whole number result

Type Converter Functions

• Type converter functions are built-in Python functions that convert one data type into another.

20
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• Common type converters:


o int() → converts to integer
o float() → converts to floating-point number
o str() → converts to string

Order of Operations
the order of operations is a fundamental rule that defines the sequence in which operations must be
performed in an expression.
Without this rule, the same expression could give different answers, leading to confusion.

• When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence.
• Python follows the same precedence rules as mathematics.
• The acronym PEMDAS helps to remember the order of operations.

PEMDAS Rule

PEMDAS specifies the priority of operations:

• P (Parentheses): Solve expressions inside brackets first


• E (Exponents): Evaluate powers and roots
• MD (Multiplication & Division): Perform from left to right
• AS (Addition & Subtraction): Perform from left to right

1. Parentheses

Have the highest precedence and can be used to force an expression to evaluate in the order you want.

Expressions in parentheses are evaluated first.

2 * (3 - 1) # 4
(1 + 1) ** (5 - 2) # 8

Parentheses can also make expressions easier to read, e.g. (minute * 100) / 60.

2. Exponentiation

21
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Has the next highest precedence.

2 ** 1 + 1 # 3 (not 4)
3 * 1 ** 3 # 3 (not 27)

3. Multiplication and Division

Both Multiplication and Division operators have the same precedence, which is higher than Addition and
Subtraction.

2 * 3 - 1 # 5 (not 4)
5 - 2 * 2 # 1 (not 6)

4. Addition and Subtraction

Left-to-Right Evaluation

Operators with the same precedence are evaluated from left to right (left-associative).

6 - 3 + 2 # subtraction first → 5

Addition and Subtraction have the same precedence, and the left-to-right rule applies.

Exception – Exponentiation

The exponentiation operator ** is an exception to the left-to-right rule.

It is right-associative.

2 ** 3 ** 2 # right-most ** done first → 512


(2 ** 3) ** 2 # use parentheses to force order → 64

Operations on Strings
A string is a sequence of characters enclosed in quotes (single ' ', double " ", or triple quotes).
Strings are used to store and manipulate text data.

22
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• Strings are immutable → cannot be changed after creation


• Each character has an index
• Index starts from 0 (forward) and -1 (backward)

Example:
str = "Hello"
H(0), e(1), l(2), l(3), o(4)

• In general, you cannot perform mathematical operations on strings, even if the strings look like
numbers.
• The following are illegal (assuming that message has type string):

>>> message - 1 # Error


>>> "Hello" / 123 # Error
>>> message * "Hello" # Error
>>> "15" + 2 # Error

3. Basic Operations on Strings

1. Concatenation (+)

• The + operator does work with strings.


• For strings, + means concatenation, not addition.
• Concatenation means joining two strings end-to-end.

Example:

a = "Hello"

b = "World"

print(a + b)

Output:

• Helloworld
23
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• The space before "nut" is part of the string and creates a space between the words.

2. Repetition (*)

• The * operator performs repetition on strings.


• One operand must be a string, and the other must be an integer.

Example:

'Fun' * 3

Result:

'FunFunFun'

Note

• String concatenation (+) and repetition (*) are different from integer addition and multiplication.
• They do not have the same mathematical properties as numbers.

Input

• There is a built-in function in Python for getting input from the user:

name = input("Please enter your name: ")

• The user of the program can enter the name and click OK, and when this happens, the text that has
been entered is returned from the input function, and in this case assigned to the variable name.
• Even if you asked the user to enter their age, you would get back a string like "17".
• It would be your job, as the programmer, to convert that string into an int or a float, using the int
or float converter functions seen earlier.

Composition

• So far we have seen variables, expressions, statements, and function calls separately.
• Programming allows combining small building blocks into larger chunks.

24
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• For example, we know how to get the user to enter some input, we know how to convert the string
we get into a float, we know how to write a complex expression, and we know how to print values.
Let’s put these together in a small four-step program that asks the user to input a value for the radius
of a circle, and then computes the area of the circle from the formula

Area = R2

response = input("What is your radius? ")


r = float(response)
area = 3.14159 * r**2
print("The area is ", area)

• The first two lines and the last two lines can be composed:

r = float(input("What is your radius? "))


print("The area is ", 3.14159 * r**2)

• It can also be written in one line:

print("The area is ", 3.14159 * float(input("What is your radius? ")) ** 2)

The Modulus Operator

• The modulus operator (%) works on integers and gives the remainder when the first number is
divided by the second.
• It has the same precedence as the multiplication operator.

q = 7 // 3
print(q) # 2 → integer division
r=7%3
print(r) # 1 → remainder

• So, 7 divided by 3 is 2 with a remainder of 1.


• Uses of modulus operator:
o To check divisibility → if x % y == 0, then x is divisible by y.
o To extract right-most digits:
▪ x % 10 → last digit
25
Mysore College Of Engineering And Management Prepared By Kamakshi M R

▪ x % 100 → last two digits

Exercises

1. Take the sentence:


“All work and no play makes Jack a dull boy.”
Store each word in a separate variable, then print out the sentence on one line using print ().

Program:
word1 = "All"
word2 = "work"
word3 = "and"
word4 = "no"
word5 = "play"
word6 = "makes"
word7 = "Jack"
word8 = "a"
word9 = "dull"
word10 = "boy."

print(word1, word2, word3, word4, word5, word6, word7, word8, word9, word10)
Output:
All work and no play makes Jack a dull boy.

2. Add parentheses to the expression 6 * 1 - 2 to change its value from 4 to -6.

Program:
print(6 * (1 - 2))
Output:
-6

3️ Place a comment before a line of code that previously worked, and record what happens when you
rerun the program.

26
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Program:
# print("This line is commented out and won't run")
print("This line will run")
Output:
This line will run
Explanation:

The line starting with # is ignored by Python (it is a comment).

4️ Start the Python interpreter and enter bruce + 4.


You will get an error:
NameError: name 'bruce' is not defined
Assign a value to bruce so that bruce + 4 evaluates to 10.

Program:
bruce = 6
print(bruce + 4)
Output:
10

5. The formula for computing the final amount if one is earning compound interest is given on
Wikipedia as

Where:

• P → Principal amount
• r → Interest rate (in decimal)
• n → Number of times interest is compounded per year
• t → Time in years

Write a Python program to calculate the final amount. Ask the user to input values.

27
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Program:
P = float(input("Enter principal amount: "))
r = float(input("Enter annual interest rate (in %): ")) / 100
n = int(input("Enter number of times interest applied per year: "))
t = float(input("Enter number of years: "))

A = P * (1 + r/n)**(n*t)
print("Final amount after interest =", round(A, 2))
Example Output:
Enter principal amount: 1000
Enter annual interest rate (in %): 1
Enter number of times interest applied per year: 1
Enter number of years: 5
Final amount after interest = 1050.1

6️. Evaluate the following numerical expressions in your head, then use the Python interpreter to check
your results:

1. >>> 5 % 2

2. >>> 9 % 5

3. >>> 15 % 12

4. >>> 12 % 15

5. >>> 6 % 6

6. >>> 0 % 7

7. >>> 7 % 0

Program:
print(5 % 2)
print(9 % 5)

28
Mysore College Of Engineering And Management Prepared By Kamakshi M R

print(15 % 12)
print(12 % 15)
print(6 % 6)
print(0 % 7)
# print(7 % 0) # This will cause an error
Output:
1
4
3
12
0
0
Explanation:

• The last example (7 % 0) causes a ZeroDivisionError because you cannot divide by zero.

Chapter 3:
Iteration

Definition:
Iteration means repeating a set of instructions in a program. It is used to automate tasks that computers
can do accurately, while humans may make mistakes if they repeat the same task many times.

Why Use Iteration?

• To repeat tasks automatically.


• To avoid errors in repetitive work.
• To make programs efficient.

Types of Iteration in Python:

1. for loop
o Used when you know how many times you want to repeat.(iteration is known)

29
Mysore College Of Engineering And Management Prepared By Kamakshi M R

o Works with sequences like lists, strings, or ranges.

Syntax:

for variable in sequence:


statements

example:

numbers = [10, 20, 30, 40]

for num in numbers:

print(num)

Example:

text = "HELLO"

for ch in text:

print(ch)

 take each value from sequence


 Assign to variable
 Execute statements
 Repeat until sequence ends

syntax for for loop with range ;

for variable in range(start, stop, step):

statements

 variable → Loop control variable (stores values one by one)


 range() → Generates sequence of numbers
 start → Starting value (optional, default = 0)

30
Mysore College Of Engineering And Management Prepared By Kamakshi M R

 stop → Ending value (not included)


 step → Increment/Decrement (optional, default = 1)

 statements → Code that runs in each iteration

How it works:

 range() generates numbers


 First value assigned to variable
 Statements executed
 Next value assigned

 Continues until stop value is reached

Example:

for i in range(5):
print(i)

O/p:
0
1
2
3
4
for i in range(1, 6):
print(i)

2. while loop
o Used when you want to repeat until a condition is met.
o Runs the instructions as long as the condition is True.

2. Syntax

31
Mysore College Of Engineering And Management Prepared By Kamakshi M R

while condition:
statements
 condition → A Boolean expression (True/False)
 statements → Code executed repeatedly
 Loop runs only while condition is True

 When condition becomes False → loop stops

Working (Step-by-Step)

1. Check condition
2. If True → execute statements
3. Return to condition
4. Repeat
Feature for Loop while Loop
When the number of iterations is When the number of iterations is unknown (depends
Use case
known. on a condition).
Automatically increments through a Requires manual initialization and
Control
sequence. increment/decrement.
Syntax More compact and easier for fixed More flexible but requires explicit control of
simplicity ranges. condition.
Example for i in range(1, 11): while i <= 10:
5. Stop when condition becomes False

Example:

o count = 0
o while count < 5:
o print(count)
o count += 1

O/p:
0
1

32
Mysore College Of Engineering And Management Prepared By Kamakshi M R

2
3
4

Note:

Iteration helps a program do repetitive tasks automatically.

Use for loop → when number of repeats is known.

Use while loop → when repeating depends on a condition.

The Collatz 3n + 1 Sequence

• The Collatz sequence is a number sequence made by repeatedly changing a number using simple
rules.
• It was introduced by a German mathematician Lothar Collatz.
• It’s also called:
o 3n + 1 sequence
o Hailstone sequence
o Wondrous numbers

The Rule:

Start with any positive integer n, and then:

• If n is even, divide it by 2 → n = n // 2
• If n is odd, multiply it by 3 and add 1 → n = 3 * n + 1
• Keep repeating these steps until n becomes 1

Example

If we start with n = 6, we get:


6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1

The sequence stops when it reaches 1

Python Program Example


33
Mysore College Of Engineering And Management Prepared By Kamakshi M R

n=6
while n != 1:
print(n, end=", ")
if n % 2 == 0:
n = n // 2
else:
n=n*3+1
print(n, end=".\n")
What Is Tracing?
Tracing means manually following how a program runs, step by step.
You act like the computer:
1. Read each line in order
2. Keep track of variable values
3. Write down what gets printed

Why We Trace a Program

Tracing helps you:

• Understand how your program works internally


• See the flow of control (which statements run and when)
• Find logical errors (bugs)
• Build a mental model of how computers execute instructions

Example — Tracing the Collatz Program

We’ll trace this program (from the previous section):

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

34
Mysore College Of Engineering And Management Prepared By Kamakshi M R

print(n, end=".\n")

Tracing Collatz for n = 6

Initial setup:
We start with n = 6.

Step 1:

• Check n != 1 → True (6 is not 1)


• Print 6 → Output so far: 6,
• 6 is even → divide by 2 → n = 3

Step 2:

• Check n != 1 → True (3 is not 1)


• Print 3 → Output so far: 6, 3,
• 3 is odd → multiply by 3 and add 1 → n = 10

Step 3:

• Check n != 1 → True (10 is not 1)


• Print 10 → Output so far: 6, 3, 10,
• 10 is even → divide by 2 → n = 5

Step 4:

• Check n != 1 → True (5 is not 1)


• Print 5 → Output so far: 6, 3, 10, 5,
• 5 is odd → multiply by 3 and add 1 → n = 16

Step 5:

• Check n != 1 → True (16 is not 1)


• Print 16 → Output so far: 6, 3, 10, 5, 16,
• 16 is even → divide by 2 → n = 8

35
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Step 6:

• Check n != 1 → True (8 is not 1)


• Print 8 → Output so far: 6, 3, 10, 5, 16, 8,
• 8 is even → divide by 2 → n = 4

Step 7:

• Check n != 1 → True (4 is not 1)


• Print 4 → Output so far: 6, 3, 10, 5, 16, 8, 4,
• 4 is even → divide by 2 → n = 2

Step 8:

• Check n != 1 → True (2 is not 1)


• Print 2 → Output so far: 6, 3, 10, 5, 16, 8, 4, 2,
• 2 is even → divide by 2 → n = 1

Step 9:

• Check n != 1 → False (n = 1, loop ends)


• Print final 1 using print(n, end=".\n") → Output: 6, 3, 10, 5, 16, 8, 4, 2, 1.

Final Output

6, 3, 10, 5, 16, 8, 4, 2, 1.

Counting Digits

• Counter Pattern: Initialize a variable (count = 0) and increment it each time the loop executes.

Example: Count all digits

n = 3029
count = 0
while n != 0:
count = count + 1

36
Mysore College Of Engineering And Management Prepared By Kamakshi M R

n = n // 10
print(count)

• Works because each division by 10 removes the last digit.

Tables

A table is a structured arrangement of data in the form of rows and columns, used to display values clearly
and systematically.

• Generated using loops


• Helps in better readability and comparison

1-D TABLE (One-Dimensional Table)

Definition

A 1D table is a table where data is displayed in only one row or one column.

 Contains single line of data


 Uses only one loop

 Output is linear

Example: Powers of 2 Table

for x in range(13): # Generate numbers 0 to 12


print(x, "\t", 2**x)

for i in range(1, 6):


print(i * 2)

Two-Dimensional Tables:

A 2D table is a table where data is arranged in rows and columns (matrix form).

37
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• Tables with rows and columns; values read at intersection.

Number of Loops

2 loops (nested loops)

• Outer loop → rows


• Inner loop → columns

for i in range(1, 4):

for j in range(1, 4):

print(i * j, end=" ")

print()

output:

123

246

369

 Outer loop controls rows


 Inner loop controls columns

 print() moves to next row

The break statement

• The break statement is used to terminate (stop) the loop immediately, even if the loop condition
is still true.

Syntax

38
Mysore College Of Engineering And Management Prepared By Kamakshi M R

for/while condition:
if condition:
break

Example:

for i in [12,16,17]:
if i % 2 == 1:
break
print(i)
print("done")

Output:

12
16
done

The continue statement

• The continue statement is used to skip the current iteration and continue with the next iteration of
the loop.

 Does not stop the loop


 Skips only the current iteration
• Loop continues normally

Syntax

for/while condition:
if condition:
continue

39
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Example:

for i in range(1,6):
if i == 3:
continue
print(i)

Output:

1
2
4
5

Useful for ignoring certain cases without exiting the loop.

Statement Effect

break Exit loop immediately

continue Skip current iteration, continue next

Paired Data: n Python, paired data means storing and working with two related values together, where
each pair represents one

Definition: A pair in Python is a simple way to group two related items using parentheses(tuple)
It is actually a tuple with 2 elements.

Examples:

year_born = ("Paris Hilton", 1981)

student =(“kavya”, 089)


year_born = ("Paris Hilton", 1981)

List of Pairs: Multiple pairs can be stored in a list:

people = [("Ravi", 2002), ("Anu", 2003), ("Kiran", 2001)]


40
Mysore College Of Engineering And Management Prepared By Kamakshi M R

print(people)

3. Operations on List of Pairs

(a) Print List

print(people)

(b) Length of List

print(len(people))

Gives number of pairs

(c) Access Using Unpacking

Definition

Unpacking means taking values from tuple directly into variables.

for name, year in people:


print(name, year)

Explanation

• name gets first value


• year gets second value

3.3.16 Nested Loops for Nested Data

Nested Data Example: Nested data means data inside another data structure.

Each student has a name and a list of subjects:

students = [

("John", ["CompSci", "Physics"]),

41
Mysore College Of Engineering And Management Prepared By Kamakshi M R

("Vusi", ["Maths", "CompSci", "Stats"]),

("Jess", ["CompSci", "Accounting", "Economics", "Management"]),

("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),

("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])

Print each student and number of subjects:

for name, subjects in students:

print(name, "takes", len(subjects), "courses")

Nested Loops

A loop inside another loop is called a nested loop.

for name, subjects in students:

for sub in subjects:

print(“subjects are:”, sub)

Functions That Require Aguments

• Definition: A function is a block of code that performs a specific task and can be reused whenever
needed.
• Reduces code repetition
• Makes program modular
• Easy to debug and maintain

42
Mysore College Of Engineering And Management Prepared By Kamakshi M R

Syntax of Function
def function_name(parameters):
# statements (function body)
return value # optional
function_call()

• def → keyword to define a function


• function_name → name given to function
• parameters → inputs to function (optional)
• : → start of function body
• indentation → required for body
• return → sends value back (optional)

Parameters vs Arguments:

o Parameter: Variable in the function definition that receives a value.


o Argument: Actual value passed to the function when called.

Example:

def add(a, b):

print(a + b)

add(2, 3)

example:

def multiply(x, y):


return x * y

result = multiply(4, 5)
print(result)

Functions That Return Values (Fruitful Functions)

43
Mysore College Of Engineering And Management Prepared By Kamakshi M R

• Fruitful function: These are the functions that return a value after their completion. A fruitful
function must always return a value to where it is called from.

def add(a, b):

return a + b

result = add(3, 4)

print(result)

• Void function: Void functions are those that do not return any value after their calculation is
complete. These types of functions are used when the calculations of the functions are not needed
in the actual program.

def greet():

print("Hello")

greet()

o Return value is independent of variable names in the caller.


o Function calls can be composed with other functions (float (input (...))).
o Clear and meaningful parameter names improve readability.
o Multiple versions of the same function may differ in variable naming or intermediate
assignments but produce the same result.

44

You might also like