Python Module1 EC
Python Module1 EC
DEPARTMENT OF ECE
NOTES
PYTHON PROGRAMMING
1BPLC105B/205B
PYTHON PROGRAMMING
Module-1
PYTHON PROGRAMMING Dept. of ECE
2. Script Mode
P a g e 2 | 42
PYTHON PROGRAMMING Dept. of ECE
WHAT IS A PROGRAM?
A program is a set of instructions for the computer to carry out. These
instructions can solve problems, perform calculations, or manipulate data.
Common Types of Computations
Mathematical: solve equations, calculate averages.
Symbolic: replace words in text, compile another program.
Five Core Instructions in Any Program
Input – collecting data (from keyboard, file, or sensor).
Output – displaying results on screen or saving to file.
Math – performing calculations.
Conditionals – making decisions (if/else).
Repetition – repeating actions (loops).
Even complex software (games, apps, operating systems) is built from
these five building blocks.
Example:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = num1 + num2
print("The sum is:", sum)
P a g e 3 | 42
PYTHON PROGRAMMING Dept. of ECE
1. Detecting the presence of errors – Noticing that the program is not behaving
as expected.
2. Locating the source of the error – Finding exactly which part of the code is
causing the problem.
3. Understanding the cause – Figuring out why the error occurred (e.g., wrong
logic, typing mistake, misuse of syntax).
4. Fixing the error – Making changes to the code so that the program works
correctly.
5. Re-testing – Running the program again to ensure that the error is removed and
no new errors have been introduced.
Debugging is an essential skill for every programmer. It improves the quality of
programs and helps in understanding the behaviour of code better. Tools like
debuggers, print statements, and error messages are often used to trace and
fix issues.
TYPES OF ERRORS
Syntax Errors
A syntax error occurs when the rules of the programming language are not
followed. Every programming language has its own set of grammar rules
(called syntax) that determine how instructions should be written.
If the program contains spelling mistakes, missing punctuation, or incorrect
structure, the Python interpreter cannot understand it and stops execution.
These errors are usually detected when the program is being translated
(compiled or interpreted), before it actually runs.
Wrong structure, like a grammar mistake.
print("Hello" # Missing parenthesis
Python will not run until fixed.
if a > b # Missing colon
print("A is greater")
num = int(input("Enter a number: "))
if num % 2 = 0: # Using '=' instead of '=='
print("Even number")
Runtime Errors (Exceptions)
A runtime error occurs while the program is running, after all syntax errors
have been fixed. Even if the code is written correctly in terms of syntax,
certain problems may occur during execution — for example, dividing by
zero or trying to open a file that doesn’t exist.
These errors cause the program to stop abruptly and display an error
message, called an exception in Python.
P a g e 4 | 42
PYTHON PROGRAMMING Dept. of ECE
Semantic Errors
A semantic error occurs when the program runs without any syntax or runtime
errors, but produces incorrect results because the logic of the program is
wrong.
The Python interpreter does not give any error message, because the code is
syntactically correct and runs successfully — but the meaning (semantics) of
the code is not what the programmer intended.
These errors are often the hardest to find, because the program doesn’t stop or
show an error; instead, it gives wrong output.
Program runs but gives wrong output.
avg = (10 + 20 + 30) # Forgot division
print(avg) # Output: 60 (wrong)
# Example 1: Incorrect formula
# Program to find average of 3 numbers
a, b, c = 10, 20, 30
avg = a + b + c / 3 # Wrong: only c is divided by 3
print("Average =", avg) # Output is wrong, but no error occurs
# Example 2: Swapping values incorrectly
x, y = 5, 10
x=y
y=x
print(x, y) # Both become 10 – logic is wrong, but code runs fine
Why Debugging is Important
Debugging is a crucial part of the programming process. It is not just about
fixing mistakes — it also helps in understanding, analysing, and
improving the overall program.
P a g e 5 | 42
PYTHON PROGRAMMING Dept. of ECE
EXPERIMENTAL DEBUGGING
Debugging is like detective work: - Observe program output (clues). - Form a
guess (hypothesis). - Fix and test. - Repeat until correct.
Debugging Tips
Start with a small working program.
Add features step by step.
Test often.
Stepwise
Example:
o 1. Start: print("Hello") → works.
o 2. Add input: name = input("Enter your name: ")
o 3. Add output: print("Hello", name)
This process ensures the program always works.
P a g e 6 | 42
PYTHON PROGRAMMING Dept. of ECE
Python provides the built-in function type() to check the type of a value:
>>> type('Hello, World!')
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
Here, 'str' means string, 'int' means integer, and 'float' means floating-point
number. At this level, you can think of 'class' and 'type' as the same. Later in object-
oriented programming, we will see that every type is actually a class.
Strings
Strings represent sequences of characters. They are used for working with text
data. In Python, strings can be enclosed in single quotes (' '), double quotes (" "), or
triple quotes (three single or double quotes). All behave the same once the string is
stored.
Examples:
>>> type('This is a string.')
<class 'str'>
P a g e 7 | 42
PYTHON PROGRAMMING Dept. of ECE
Numbers
There are two main numeric types in Python:
- Integers (int): whole numbers, positive or negative, with no decimal point.
- Floating-point numbers (float): numbers with decimals, represented using
the IEEE 754 standard.
Examples:
>>> type(42)
<class 'int'>
>>> type(3.14)
<class 'float'>
Warning: Do not use commas in numbers. Writing 42,000 will not be
interpreted as forty-two thousand:
>>> 42000
42000
>>> 42,000
(42, 0)
Because of the comma, Python thinks you are creating a tuple (a collection of
values). Therefore, always write large numbers without commas.
P a g e 8 | 42
PYTHON PROGRAMMING Dept. of ECE
>>> type(None)
<class 'NoneType'>
In Automate the Boring Stuff, Sweigart explains that None is often used as a
placeholder value, for example when initializing variables before assigning
real values later.
TYPE CONVERSION
In Python, sometimes it is necessary to change the data type of a value from
one type to another. This process is called type conversion.
For example, if a number is entered as a string from the keyboard, it must be
converted into an integer before performing arithmetic operations.
1. Implicit Type Conversion (Automatic)
Performed automatically by Python, without the programmer’s
intervention.
Happens during expressions when operands of different types are
used together.
Python converts the smaller data type to a larger data type to
avoid data loss.
Example:
x = 10 # int
y = 2.5 # float
z = x + y # int is converted to float automatically
print(z) # 12.5
print(type(z)) # <class 'float'>
P a g e 9 | 42
PYTHON PROGRAMMING Dept. of ECE
Examples:
>>> int('42')
42
>>> float('3.14')
3.14
>>> str(100)
'100'
>>> bool(0)
False
>>> bool(5)
True
Type conversion is common when reading input (which always comes in as a
string) and converting it to numbers.
o Example 1: Adding numbers
>>> 2 + 3
5
o Example 2: String concatenation
>>> 'Hello' + ' ' + 'World'
'Hello World'
o Example 3: Boolean check
>>> 10 > 5
True
o Example 4: Using None
>>> result = print('Hello')
Hello
>>> print(result)
None
Explanation:
- In Example 1, Python performs arithmetic addition.
- In Example 2, the '+' operator joins strings together.
- In Example 3, a comparison returns a Boolean value.
- In Example 4, the print() function displays output but returns None.
P a g e 10 | 42
PYTHON PROGRAMMING Dept. of ECE
In Python, every value is an object, and each object has a specific data type.
A data type defines:
The kind of data stored (e.g., numbers, text, lists, etc.)
The operations that can be performed on that data
How much memory it uses internally
P a g e 11 | 42
PYTHON PROGRAMMING Dept. of ECE
# Easier to read:
print((minutes * 100) / 60)
Exponentiation ( ** )
Exponentiation comes next after parentheses.
But note: Python evaluates exponentiation right to left.
Examples:
print(2 ** 1 + 1) # 2**1 = 2; 2+1 = 3
print(3 * 1 ** 3) # 1**3 = 1; 3*1 = 3
Right-to-left behavior:
print(2 ** 3 ** 2) # 2 ** (3 ** 2) = 2 ** 9 = 512
print((2 ** 3) ** 2) # (2 ** 3) ** 2 = 8 ** 2 = 64
So always use parentheses when you have multiple exponents, to make sure
the order is what you expect.
P a g e 14 | 42
PYTHON PROGRAMMING Dept. of ECE
If you mistakenly think + happens before -, you may get the wrong answer.
Always remember: left to right for operators at the same level.
OPERATIONS ON STRINGS
In Python, strings are sequences of characters.
You can perform some special operations on strings using operators like +
and *.
P a g e 15 | 42
PYTHON PROGRAMMING Dept. of ECE
P a g e 16 | 42
PYTHON PROGRAMMING Dept. of ECE
James R
2*3=3*2
For strings:
"Hi" + "Bye" ≠ "Bye" + "Hi" (order matters)
"Hi" * 3 = 3 * "Hi" #(works either way)
"Hi" * "3" # Error (both cannot be strings)
🔸 Associative Property
(2 + 3) + 4 = 2 + (3 + 4) #for numbers
For strings: Concatenation is associative but not commutative.
Example:
a = "A"
b = "B"
c = "C"
print((a + b) + c) # ABC
print(a + (b + c)) # ABC
Both are the same. But if you change order, the result changes:
print(b + a + c) # BAC
INPUT IN PYTHON
In Python, we can get data from the user by using the built-in input() function.
This allows the program to interact with the user during execution.
Syntax:
variable_name = input("Prompt message")
When the program reaches the input() statement:
It displays the message inside the brackets.
It waits for the user to type some text and press Enter.
Whatever the user types is returned as a string.
That string is stored in the variable on the left side of =.
Example 1: Getting a Name
name = input("Please enter your name: ")
print("Hello", name)
Sample Run:
Please enter your name: James
Hello James
Whatever the user typed (e.g., James) is stored in the variable name.
P a g e 18 | 42
PYTHON PROGRAMMING Dept. of ECE
Common Errors
Forgetting to convert the input:
num = input("Enter a number: ")
print(num + 5) # Error: cannot add str and int
Correct way:
num = int(input("Enter a number: "))
print(num + 5)
P a g e 19 | 42
PYTHON PROGRAMMING Dept. of ECE
COMPOSITION
In Python, composition means combining smaller parts of a program (like
variables, expressions, statements, and function calls) to make larger and more
powerful statements.
So far, we have learned each part separately. But in real programs, we often
combine these building blocks to make the code shorter and more efficient.
Example: Calculating Area of a Circle
We will write a program to input the radius, convert it to a number,
calculate area, and display the result.
Step-by-step version (4 steps):
1. response = input("What is your radius? ")
2. r = float(response)
3. area = 3.14159 * r**2
4. print("The area is", area)
Each step does one clear task → easy to read and understand.
Checking Divisibility
The modulus operator is very useful to check if one number divides
another exactly:
x = 15
y=5
if x % y == 0:
print(x, "is divisible by", y)
else:
print(x, "is NOT divisible by", y)
Output:
15 is divisible by 5
If x % y == 0 → no remainder → divisible ✅
Extracting Digits
dulus can extract the right-most digit(s) of a number:
x = 347
print(x % 10) # 7 → last digit
print(x % 100) # 47 → last two digits
% 10 gives the last digit, % 100 gives the last two digits, etc.
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
P a g e 21 | 42
PYTHON PROGRAMMING Dept. of ECE
CHAPTER 3: CONDITIONALS
Boolean Expressions
A Boolean expression is an expression that evaluates to either True or False.
Example:
print(5 == (3 + 2)) # True
print(5 == 6) # False
j = "hel"
print(j + "lo" == "hello") # True
The result depends on whether the comparison is true or false.
Comparison Operators
Operator Meaning Example (x=5, y=3) Result
== Equal to x == y False
!= Not equal to x != y True
> Greater than x>y True
P a g e 22 | 42
PYTHON PROGRAMMING Dept. of ECE
LOGICAL OPERATORS
In Python, there are three logical operators used to combine Boolean
expressions:
1. and
2. or
3. not
Their meaning is similar to everyday English.
and Operator
Combines two Boolean expressions.
True only if both expressions are True.
Example:
x=5
print(x > 0 and x < 10) # True → because 5 > 0 and 5 < 10
Expr1 Expr2 Expr1 and Expr2
True True True
True False False
False True False
False False False
or Operator
P a g e 23 | 42
PYTHON PROGRAMMING Dept. of ECE
not Operator
Reverses the Boolean value.
not True → False
not False → True
Example:
x=3
y=5
print(not (x > y)) # True → because x > y is False
Short-Circuit Evaluation
Python evaluates left to right and stops early if the result is already known:
or → if left is True, right is not evaluated.
and → if left is False, right is not evaluated.
This avoids unnecessary evaluations.
Example:
a = True or (5/0) # Right side not evaluated → no error
b = False and (5/0) # Right side not evaluated → no error
P a g e 24 | 42
PYTHON PROGRAMMING Dept. of ECE
Similarly, Boolean algebra helps simplify logical expressions involving and, or,
and not.
Why Simplify?
Reduces unnecessary conditions.
Makes expressions easier to read and faster to evaluate.
Useful in writing efficient conditional statements.
Example
P a g e 25 | 42
PYTHON PROGRAMMING Dept. of ECE
# Original
if (not (not (x and True))):
print("Yes")
CONDITIONAL EXECUTION
In real programs, we often need to check conditions and control the flow of
execution based on those conditions.
Conditional statements (like if) allow us to make decisions in the program.
The if Statement
The basic structure of an if-else statement is:
if <BOOLEAN EXPRESSION>:
<STATEMENTS_1> # Executed if condition is True
else:
<STATEMENTS_2> # Executed if condition is False
Header line: Starts with if, followed by a Boolean expression, and ends with a
colon :.
Block (suite): One or more indented statements that run if the condition is
True.
else clause: Optional — runs when the condition is False.
Indentation is crucial in Python. Indented lines belong to the block; the first
unindented line ends the block.
P a g e 26 | 42
PYTHON PROGRAMMING Dept. of ECE
Condition: x % 2 == 0
If True → executes the “even” block
Else → executes the “odd” block
Flowchart
If condition is True → execute first block
If False → execute else block
pass Statement
Sometimes we need a block with no action, for placeholder code.
if True:
pass # Does nothing
else:
pass
pass allows the structure to remain valid without performing any operation.
Terminology
Block = group of indented statements under if or else.
Suite = Python documentation term for the same concept.
else is not a statement; it's an optional clause of if.
else: # x == y
<STATEMENTS_C>
elif = else if
Checked in order, top to bottom.
As soon as one condition is True, its block runs and the rest are skipped.
Only one branch executes, even if multiple conditions are true.
You can have multiple elif, but only one final else (optional).
Example
if choice == "a":
function_one()
elif choice == "b":
function_two()
elif choice == "c":
function_three()
else:
print("Invalid choice.")
Each condition is checked in sequence; only the first True branch runs.
Nested Conditionals
A nested conditional is when an if statement is placed inside another if.
This allows more complex decision structures, but can become hard to read
if overused.
if x < y:
<STATEMENTS_A>
else:
if x > y:
<STATEMENTS_B>
else:
<STATEMENTS_C>
Here, the outer if has two branches, and the else contains another if.
Too many nested conditionals can make code confusing, so avoid them when
possible.
P a g e 28 | 42
PYTHON PROGRAMMING Dept. of ECE
LOGICAL OPPOSITES
In Python, each relational operator has a logical opposite.
Understanding these opposites helps us simplify Boolean expressions and avoid
unnecessary not operators, which often make code harder to read.
Logical Opposites Table
Operator Logical Opposite
== !=
!= ==
< >=
<= >
> <=
>= <
Example:
“Can get a driving licence if age ≥ 18”
Opposite: “Cannot get a licence if age < 18”
P a g e 29 | 42
PYTHON PROGRAMMING Dept. of ECE
De Morgan’s Laws
Two important rules to simplify complex Boolean expressions:
ITERATION IN PYTHON
Iteration = Repeated execution of a set of statements.
Computers are great at doing repetitive tasks without errors, unlike humans.
Python provides multiple ways to perform iteration:
for loop → Most commonly used.
while loop → Useful when the number of iterations is not known in advance.
Assignment
Assignment is giving a value to a variable using the = operator.
You can assign new values to the same variable multiple times — this will
update what the variable refers to.
Example
airtime_remaining = 15
print(airtime_remaining) # Output: 15
airtime_remaining = 7
print(airtime_remaining) # Output: 7
First, the variable has value 15.
Then it's reassigned to 7, so the second print shows the updated value.
Updating Variables
Updating a variable = Assigning it a new value based on its current value.
General Pattern
variable = variable + expression
Example
n=5
n=3*n+1
print(n) # Output: 16
Step by step:
1. Take current n → 5
2. Multiply by 3 → 15
3. Add 1 → 16
4. Assign back to n → n now holds 16
Error if variable is not initialized
o w=x+1
Error: NameError: name 'x' is not defined
You must assign a variable before you can update it.
runs_scored -= 1 # Decrement by 1
o Increment → Adding 1
o Decrement → Subtracting 1
o Sometimes called “bumping” a variable.
P a g e 33 | 42
PYTHON PROGRAMMING Dept. of ECE
current_sum = 0
i=0
while i <= n:
current_sum += i
i += 1
print(current_sum)
Flow of execution:
Condition i <= n is checked
If True, loop body runs (adds i to sum, increments i)
Control goes back to check the condition again
When condition becomes False, loop exits
Step table:
i current_sum condition (i ≤ n) Action
0 0 True Add 0, i→1
1 1 True Add 1, i→2
2 3 True Add 2, i→3
… … … …
6 21 True Add 6, i→7
7 28 False Exit
Final output: 28
P a g e 34 | 42
PYTHON PROGRAMMING Dept. of ECE
print(current_sum)
range(n+1) gives values from 0 to n.
Remember: range() goes up to but not including the end value.
P a g e 35 | 42
PYTHON PROGRAMMING Dept. of ECE
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096
o \t → Tab escape sequence, used to align columns neatly
o \n → Newline escape sequence (moves cursor to new line)
o Tabs help align columns regardless of the number of digits in the first column.
TWO-DIMENSIONAL TABLES
A two-dimensional table is like a matrix where you read data at the
intersection of a row and column.
Example: Printing Multiples of 2
for i in range(1, 7): # i takes values from 1 to 6
print(2 * i, end=" ") # end=" " prevents moving to a new line
print()
Output
2 4 6 8 10 12
end=" " → Keeps printing on the same line
Useful for multiplication tables or matrix-like outputs.
BREAK STATEMENT
Break is used to immediately exit a loop, regardless of the loop condition.
Example
for i in [12, 16, 17, 24, 29]:
if i % 2 == 1: # Check if number is odd
break # Exit loop immediately
print(i)
print("done")
Output
12
16
done
P a g e 36 | 42
PYTHON PROGRAMMING Dept. of ECE
CONTINUE STATEMENT
Continue is used to skip the remaining part of the loop body for the current
iteration, and move to the next iteration.
Example
for i in [12, 16, 17, 24, 29, 30]:
if i % 2 == 1: # Odd number
continue # Skip printing odd numbers
print(i)
print("done")
Output
12
16
24
30
done
P a g e 37 | 42
PYTHON PROGRAMMING Dept. of ECE
P a g e 38 | 42
PYTHON PROGRAMMING Dept. of ECE
WHAT IS A FUNCTION?
A function is a block of reusable code that performs a specific task.
It helps to:
Avoid repetition of code
Break complex problems into smaller modules
Improve readability and maintainability
Functions can take inputs (arguments) and can return outputs (return
values).
P a g e 39 | 42
PYTHON PROGRAMMING Dept. of ECE
P a g e 40 | 42
PYTHON PROGRAMMING Dept. of ECE
return False
n = int(input("Enter a number: "))
if is_even(n):
print("The number is Even")
else:
print("The number is Odd")
Output
Enter a number: 7
The number is Odd
Here, the function returns a Boolean value, which is used in an if statement.
P a g e 42 | 42