Python Module1 Notes
Python Module1 Notes
MODULE 1
• C++
• PHP
• Pascal
• C#
• Java
Computers cannot directly understand high-level languages. They only understand low-level languages
(machine language or assembly language).
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
Example:
>>> 5 * 3
15
2. Script Mode
Example:
a=5
b = 10
print(a + b)
Output:
15
2
Mysore College Of Engineering And Management Prepared By Kamakshi M R
• 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.
Although programming languages look different from each other, they all share a few basic kinds of
instructions:
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
Definition:
Example:
Runtime Errors
Definition:
Example:
4
Mysore College Of Engineering And Management Prepared By Kamakshi M R
x = 10 / 0 # Division by zero
Semantic Errors
Definition:
Example:
This way, you avoid being overwhelmed by too many errors at once.
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.
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
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:
Here, the tokens are valid but placed in the wrong order, making the structure illegal
• Python code:
print("Hello, World!")
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.
Example:
• # This is a comment
1️ Single-Line Comments
Example:
8
Mysore College Of Engineering And Management Prepared By Kamakshi M R
2️ Multi-Line Comments
Python does not have a special multi-line comment symbol, but we can write multi-line comments in two
ways:
# This is a comment
# written in
# multiple lines
So it gets ignored
'''
This is a
multi-line comment
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.
1️ Integer (int)
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)
True
False
Examples:
"Hello"
'Python'
"123"
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 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.
Example:
x = 10 # int
y = 2.5 # float
13
Mysore College Of Engineering And Management Prepared By Kamakshi M R
1. int()
The int() function is used to convert a given value into an integer (whole number) data type.
Working
🔹 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)
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.
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
15
Mysore College Of Engineering And Management Prepared By Kamakshi M R
🔹 Triple-Quoted Strings
16
Mysore College Of Engineering And Management Prepared By Kamakshi M R
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"
>>> 17 = n
SyntaxError: can't assign to literal
'Friday'
>>> day = 21
>>> day
21
Code:
my_name
price_of_tea_in_china
Code:
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
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
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.
Division Operator
Example:
minutes = 645
hours = minutes / 60 # 10.75
hours = minutes // 60 # 10
• 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
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
1. Parentheses
Have the highest precedence and can be used to force an expression to evaluate in the order you want.
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
2 ** 1 + 1 # 3 (not 4)
3 * 1 ** 3 # 3 (not 27)
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)
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
It is right-associative.
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
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):
1. Concatenation (+)
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 (*)
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:
• 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
• The first two lines and the last two lines can be composed:
• 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
Exercises
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.
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:
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.
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
Syntax:
example:
print(num)
Example:
text = "HELLO"
for ch in text:
print(ch)
statements
30
Mysore College Of Engineering And Management Prepared By Kamakshi M R
How it works:
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
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:
• 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:
• 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
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
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")
Initial setup:
We start with n = 6.
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
35
Mysore College Of Engineering And Management Prepared By Kamakshi M R
Step 6:
Step 7:
Step 8:
Step 9:
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.
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)
Tables
A table is a structured arrangement of data in the form of rows and columns, used to display values clearly
and systematically.
Definition
A 1D table is a table where data is displayed in only one row or one column.
Output is linear
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
Number of Loops
print()
output:
123
246
369
• 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 is used to skip the current iteration and continue with the next iteration of
the loop.
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
Statement Effect
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:
print(people)
print(people)
print(len(people))
Definition
Explanation
Nested Data Example: Nested data means data inside another data structure.
students = [
41
Mysore College Of Engineering And Management Prepared By Kamakshi M R
Nested Loops
• 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()
Parameters vs Arguments:
Example:
print(a + b)
add(2, 3)
example:
result = multiply(4, 5)
print(result)
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.
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()
44