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

Python Module1 EC

The document provides an overview of Python programming, highlighting its high-level nature, ease of use, and the importance of debugging. It discusses the Python interpreter, modes of execution, common data types, and the significance of understanding and converting data types. Additionally, it covers types of errors in programming and the debugging process, emphasizing its role in improving program quality and logical thinking.

Uploaded by

shamnachammu158
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)
2 views42 pages

Python Module1 EC

The document provides an overview of Python programming, highlighting its high-level nature, ease of use, and the importance of debugging. It discusses the Python interpreter, modes of execution, common data types, and the significance of understanding and converting data types. Additionally, it covers types of errors in programming and the debugging process, emphasizing its role in improving program quality and logical thinking.

Uploaded by

shamnachammu158
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

KVG COLLEGE OF ENGINEERING

DEPARTMENT OF ECE

NOTES
PYTHON PROGRAMMING
1BPLC105B/205B

PYTHON PROGRAMMING
Module-1
PYTHON PROGRAMMING Dept. of ECE

THE PYTHON PROGRAMMING LANGUAGE


 Python is a high-level programming language. High-level means it is
closer to human languages, making it easier to understand and use.
Computers, on the other hand, only understand low-level languages like
machine code (binary 0s and 1s) or assembly. That is why high-level
languages like Python must be translated into low-level language before
execution.
 Other High-level Languages
1. C++
2. PHP
3. Pascal
4. C#
5. Java
 Why High-level Languages Are Popular
 Easy to write: Programs are shorter and faster to code.
 Easy to read: Clear structure, close to English.
 Less error-prone: Rules are simple.
 Portable: The same code can run on many types of computers.
 Nearly all modern software is written in high-level languages.
 Example Comparison:
 High-level (Python): python print("Hello, World!")
 Low-level (Assembly): assembly MOV AH, 09h LEA DX, message
INT 21h Python is much simpler for beginners

THE PYTHON INTERPRETER


 Python code is executed by the Python Interpreter, which acts like a
translator between human-friendly code and machine instructions.

 Two Modes of Execution


1. Interactive (Immediate) Mode
 Code is typed line by line.
 Immediate results are shown.
 Example:
 >>> 2 + 3
5
 The >>> is called the Python prompt.
 Best for small experiments.

2. Script Mode
P a g e 2 | 42
PYTHON PROGRAMMING Dept. of ECE

 Code is saved in a .py file and then run.


 Example: [Link]
 print("Hello, Python!")
 Run once, save forever.
 Best for long programs.

 Tools for Writing Python


 Text editors: Notepad, Notepad++, Vim, Emacs, Sublime.
 IDEs (Integrated Development Environments): IDLE, Thonny, PyCharm,
Spyder, Jupyter Notebook.

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)

DEBUGGING – FINDING AND FIXING ERRORS


 Programming is done by humans, and it is common to make mistakes
while writing code. These mistakes are known as bugs, and the process of
identifying and correcting them is called debugging.
 When a program does not run correctly or produces wrong results, it
usually indicates that there is some error in the code.
 Debugging involves:

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

number = int("abc") # Cannot convert text to number


 # Example 1: Division by zero
num = 10
den = 0
print(num / den) # ZeroDivisionError

 # Example 2: Invalid input conversion


Value = int(input("Enter a number: "))
# If the user enters a non-numeric value → ValueError
 # Example 3: Accessing an invalid index
list1 = [10, 20, 30]
print(list1[5]) # IndexError

 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

1. Helps Understand Program Behaviour


While debugging, programmers closely examine how each part of the program
works. This gives them a better understanding of the program’s flow, logic, and
how different components interact. It also helps in identifying hidden issues that may
not be immediately visible.
2. Builds Logical Thinking
Debugging requires a step-by-step, logical approach to trace the cause of an
error. By analysing problems carefully, students develop strong reasoning and
analytical skills, which are essential for writing efficient and error-free programs.
3. Improves Problem-Solving
Every error is like a mini problem. Debugging trains programmers to break
down complex issues, explore different solutions, and choose the best one. Over
time, this improves their problem-solving ability, making it easier to handle more
complex programming challenges.

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.

CHAPTER-2: VALUES AND DATA TYPES IN PYTHON


IDENTIFYING DATA TYPES
 In Python, every value has a data type that determines what kind of data it is
(e.g., number, text, decimal, etc.) and what operations can be performed on it.
 Identifying the correct data type is important because it helps us:
 Understand how the data will be stored and processed.
 Choose appropriate operations (e.g., we can add numbers but cannot add a
number and a string directly).
 Avoid unexpected errors in programs.

P a g e 6 | 42
PYTHON PROGRAMMING Dept. of ECE

 Common Python Data Types:


Data Type Description Example
int Integer — whole numbers 10, -5, 0
float Floating point — decimal numbers 3.14, -2.5, 0.0
str String — sequence of characters "Hello", '123'
bool Boolean — represents True or False True, False

 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'>

>>> type("And so is this.")


<class 'str'>

>>> type("""and this.""")


<class 'str'>

>>> type('''and even this...''')


<class 'str'>
Triple quoted strings can span multiple lines and include both single and double
quotes without escaping:

P a g e 7 | 42
PYTHON PROGRAMMING Dept. of ECE

>>> message = """This message will


... span several
... lines."""
>>> print(message)
This message will
span several
lines.
Strings are extremely important because much of real-world programming
involves text processing, such as reading filenames, user input, or website data.

 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.

 Booleans and None


 Boolean values (True and False) are used to represent truth values. They are
essential in conditional statements and loops.
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
 The special value None represents 'no value' or 'nothing'. Functions that do
not explicitly return anything will return None.

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

2. Explicit Type Conversion (Type Casting)


 Done manually by the programmer using built-in functions.
 Useful when we want to convert data from one type to another
intentionally.

Common Type Conversion Functions:


Function Converts To Example
int(x) Integer int("10") → 10
float(x) Floating point float("3.14") → 3.14
str(x) String str(25) → "25"
bool(0) → False, bool(5) →
bool(x) Boolean
True

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.

FORMAL VS. NATURAL LANGUAGES


 Natural Languages: human languages (English, Hindi, French).
 Formal Languages: special languages designed for precision (math, chemistry,
programming).
 Key Differences

P a g e 10 | 42
PYTHON PROGRAMMING Dept. of ECE

1. Ambiguity: Natural → words can mean different things. Formal →


one exact meaning.
2. Redundancy: Natural → uses extra words. Formal → concise.
3. Literalness: Natural → idioms/metaphors. Formal → always literal.
 Examples: - Natural: “The other shoe fell” (idiom, not literal). - Formal
(Python): python print("Happy New Year for", 2025)
 In programming, small mistakes in syntax can stop execution.

Syntax in Formal Languages


 Tokens: smallest building blocks (keywords, numbers, parentheses).
 Structure: arrangement of tokens.
 Example:
o print("Happy New Year")
o Tokens: print, (, string, ).
o If parentheses are misplaced:
o print"Happy New Year") #Invalid syntax.

CHAPTER-3: VARIABLES, EXPRESSIONS AND STATEMENTS

VALUES AND DATA TYPES


 In Python, data is the information that a program works with. Every piece of
data in a program is called a value, and each value belongs to a specific data
type.
 A value is simply any piece of information — like a number, text, or a logical
value.
 A data type defines the kind of value and what operations can be performed
on it.
 Examples of Values:
25 # an integer value
3.14 # a floating-point value
"Hello" # a string value
True # a boolean value

 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

 Understanding data types is essential because Python is strongly typed, meaning


it does not allow operations between incompatible types (e.g., adding a string
and an integer without conversion).

Common Data Types in Python


Data Type Description Example Values
int Integer – whole numbers 10, -5, 0
float Floating point – decimal numbers 3.14, -2.5, 0.0
str String – sequence of characters (text) "Python", '123', "A"
bool Boolean – represents truth values True, False
 Numeric Data Types
 These are data types that represent numbers.
 Python supports three main numeric types:
Type Description Examples
10, -5, 0,
int Integer — Whole numbers without decimal points
2025
3.14, -0.5,
float Floating point — Numbers with decimal points
2.0
Complex numbers with a real and imaginary part (in
complex 3+4j, 2-5j
a+bj format)
 String Data Type (str)
 A string is a sequence of characters enclosed in single quotes, double
quotes, or triple quotes.
 Strings are immutable, meaning they cannot be changed after creation.

 Boolean Data Type (bool)


 Boolean values represent truth values: True or False.
 Often used in conditional statements and logical expressions.
 Internally, True = 1 and False = 0.
x = True
y = False
print(x + y) # 1 (True) + 0 (False) = 1
print(type(x)) # <class 'bool'>
 Boolean expressions return either True or False:
print(5 > 3) # True
print(10 == 5) # False
P a g e 12 | 42
PYTHON PROGRAMMING Dept. of ECE

 Using type() to Identify Data Types


 Python provides a built-in function called type() to find out the data type of
any value or variable.]
 This function is very useful when:
 You want to check what kind of data a variable is storing.
 You need to debug a program and find unexpected data types.
 You are working with user input, which is often in string form by default.
 Example:
print(type(10)) # <class 'int'>
print(type(3.5)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>

ORDER OF OPERATIONS (OPERATOR PRECEDENCE)


 When an expression contains more than one operator, Python needs to decide
which operation to perform first.
 This is determined by operator precedence — just like in regular mathematics.
Python follows PEMDAS rules:
P – Parentheses
E – Exponents (** operator)
M – Multiplication ( * )
D – Division ( / , // , % )
A – Addition ( + )
S – Subtraction ( - )
 But there’s a small twist:
 Multiplication and Division have equal precedence (same level).
 Addition and Subtraction have equal precedence (same level).
 When operators have the same precedence, Python evaluates from left to
right, except for exponentiation, which is evaluated right to left.

 Parentheses – Highest Precedence-Any operation inside parentheses ( ) is


done first, regardless of what is outside.
o Examples:
print(2 * (3 - 1)) #2*2=4
print((1 + 1) ** (5 - 2)) # (2) ** (3) = 8
print((10 + 2) * 3) # 12 * 3 = 36
 Even if parentheses are not needed for the result, you can use them to make
your code easier to read and understand.
P a g e 13 | 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.

Multiplication, Division, Floor Division, and Modulus


 These operators come after exponents and are evaluated from left to
[Link] all share the same precedence level:
* → multiplication
/ → division (gives float)
// → floor division (gives integer result after flooring)
% → modulus (remainder)
 Examples:
print(2 * 3 - 1) # (2*3)=6, then 6-1 = 5
print(5 - 2 * 2) # (2*2)=4, then 5-4 = 1
print(10 / 2 * 4) # (10/2)=5.0, then 5.0*4 = 20.0
print(20 // 3 * 2) # (20//3)=6, then 6*2 = 12
print(10 % 4 * 2) # (10%4)=2, then 2*2 = 4
 Notice: Multiplication and Division are done before Addition/Subtraction, but
if both are present, Python goes left to right.

Addition and Subtraction


 These have the lowest precedence among arithmetic operators.
If they appear with other operators, they are done last, and evaluated left to
right.
 Examples:
print(6 - 3 + 2) # (6-3)=3; then 3+2 = 5
print(10 + 2 - 3) # (10+2)=12; then 12-3 = 9

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.

Exponentiation Associates Right-to-Left


 Exponentiation is the only arithmetic operator in Python that does not follow
left-to-right evaluation when operators are at the same precedence.
 Example:
print(2 ** 3 ** 2) # 2 ** (3**2) = 2**9 = 512
If you want the opposite:
print((2 ** 3) ** 2) # (2**3)=8, then 8**2 = 64
 Rule of thumb: Use parentheses to make exponentiation order explicit.
 Example: Let’s break them step by step
Example 1:
result = 10 + 2 * 3 ** 2
print(result)
Step-by-step:
3 ** 2 → 9
2 * 9 → 18
10 + 18 → 28
 Example 2:
result = (10 + 2) * 3 ** 2
print(result)
Step-by-step:
(10 + 2) → 12
3 ** 2 → 9
12 * 9 → 108
 Example 3:
result = 100 / 5 * 2 + 3
print(result)
Step-by-step:
100 / 5 → 20.0
20.0 * 2 → 40.0
40.0 + 3 → 43.0

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

 But unlike numbers, you cannot use normal mathematical operations on


strings.

1. Illegal Operations on Strings


 You cannot subtract, divide, or multiply two strings together in a mathematical
way.
Even if the string contains numbers (like "15"), Python still treats it as text.
 Examples of invalid operations:
message = "Hello"
print(message - 1) # Error (cannot subtract from a string)
print("Hello" / 123) # Error (cannot divide string and number)
print(message * "Hi") # Error (cannot multiply string by string)
print("15" + 2) # Error (cannot add string and number directly)
 If you want to use strings that look like numbers in calculations, you must
convert them using functions like int() or float().
 Example:
num_str = "15"
num = int(num_str) # convert string to integer
print(num + 2) # Output: 17

[Link] Concatenation using +


 The + operator joins two strings together, end to end.
 This operation is called concatenation.
 Example 1: Basic Concatenation
fruit = "banana"
baked_good = " nut bread"
print(fruit + baked_good)
 Output:
banana nut bread
Notice that the space before " nut bread" is important.
If you don’t include it, the words will stick together like this:
print(fruit + "nut bread") # Output: banananut bread

 Example 2: Joining Variables


first_name = "James"
last_name = " R"
full_name = first_name + last_name
print(full_name)
 Output:

P a g e 16 | 42
PYTHON PROGRAMMING Dept. of ECE

James R

 Example 3: String + Number (with Conversion)


age = 20
# print("Age: " + age) # Error
print("Age: " + str(age)) # Convert number to string first
 Output:
Age: 20
To concatenate numbers with strings, use str() to convert the number into a
string.

3. String Repetition using *


 The * operator repeats a string a specified number of times.
 One operand must be a string, and the other must be an integer.
 Example 1: Basic Repetition
print("Fun" * 3)
Output:
FunFunFun

 Example 2: Variable Repetition


laugh = "Ha"
print(laugh * 4)
Output:
HaHaHaHa

 Example 3: Using Integer First


print(3 * "Hello ")
Output:
Hello Hello Hello
 You can write "Hello" * 3 or 3 * "Hello". #Both work.
But "Hello" * "3" #will cause an error.

4. Important Differences Between String Operations and Numeric


Operations
 Although + and * are used with both numbers and strings, their behavior is
different:
🔸 Commutative Property
For numbers:
2+3=3+2
P a g e 17 | 42
PYTHON PROGRAMMING Dept. of ECE

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.

 Input is Always Returned as a String


 Even if the user types a number, the input() function still returns it as text (string).
 Example 2: Entering a Number

P a g e 18 | 42
PYTHON PROGRAMMING Dept. of ECE

age = input("Enter your age: ")


print(age)
print(type(age))
Sample Run:
Enter your age: 17
17
<class 'str'>
 Notice that the type of age is str (string), not an integer.

 Converting Input to Numbers


 If you want to perform calculations with the user’s input, you must convert the string
to a number using:
int() → for integers
float() → for decimal numbers
 Example 3: Converting to Integer
age = input("Enter your age: ")
age = int(age) # Convert string to integer
print(age + 1)
Sample Run:
Enter your age: 17
18
 Without conversion, age + 1 would give an error, because you cannot add a string and a
number.

 Example 4: Converting to Float


marks = input("Enter your marks: ")
marks = float(marks) # Convert to decimal number
print("Marks after bonus:", marks + 2.5)
Sample Run:
Enter your marks: 75.5
Marks after bonus: 78.0

 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.

 Composed Code (Fewer Lines)


 We can combine steps to make the code shorter:
 2-step version:
1. r = float(input("What is your radius? "))
2. print("The area is", 3.14159 * r**2)

 All-in-one Line (Compact Code)


 print("The area is", 3.14159 * float(input("What is your radius? "))**2)
 This works the same, but may be harder for humans to read.

THE MODULUS OPERATOR (%)


 The modulus operator % works on integers (or integer expressions) and
returns the remainder when one number is divided by another.
 Basic Syntax
remainder = a % b
a → dividend (number to be divided)
b → divisor (number you divide by)
remainder → result after division
The % operator has the same precedence as * and /.

 Example: Basic Division


q = 7 // 3 # Integer division (quotient)
print(q) #2
P a g e 20 | 42
PYTHON PROGRAMMING Dept. of ECE

r=7%3 # Modulus (remainder)


print(r) #1
 Explanation:
7 ÷ 3 → quotient = 2, remainder = 1
So, 7 % 3 = 1

 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.

 Time Conversion Example


 Modulus is very useful in converting seconds into hours, minutes, and
seconds.
Example Program
total_secs = int(input("How many seconds, in total? "))

hours = total_secs // 3600


secs_still_remaining = total_secs % 3600

minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60

P a g e 21 | 42
PYTHON PROGRAMMING Dept. of ECE

print("Hrs =", hours, "mins =", minutes, "secs =", secs_finally_remaining)


Sample Run:
How many seconds, in total? 5000
Hrs = 1 mins = 23 secs = 20
Here:
// gives quotient (full hours, full minutes)
% gives remainder (what’s left over)

CHAPTER 3: CONDITIONALS

BOOLEAN VALUES AND EXPRESSIONS


 Boolean Values
 A Boolean value represents either:
 True ✅
 False ❌
 Named after George Boole, who developed Boolean algebra — the base of
modern computer logic.
 In Python:
o True and False must be capitalized correctly.
o Their type is bool.
o print(type(True)) # <class 'bool'>
o print(type(false)) # ❌ Error (wrong capitalization)

 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

Operator Meaning Example (x=5, y=3) Result


< Less than x<y False
>= Greater than or equal to x >= y True
<= Less than or equal to x <= y False
 Important:
 = → assignment operator
 == → comparison operator
 There is no =< or => in Python

 Assigning Boolean Values


 Boolean expressions can be stored in variables:
age = 19
old_enough = age >= 18
print(old_enough) # True
print(type(old_enough)) # <class 'bool'>

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

 True if at least one of the expressions is True.


 Example:
n=6
print(n % 2 == 0 or n % 3 == 0) # True (divisible by 2)
o If n is divisible by both 2 and 3, the expression is still True,
because only one True is enough.
Expr1 Expr2 Expr1 or Expr2
True True True
True False True
False True True
False False False

 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

SIMPLIFYING BOOLEAN EXPRESSIONS


 Boolean Algebra is a set of rules for simplifying and rearranging Boolean
expressions.
It works similarly to how ordinary algebra simplifies numeric expressions.
 Example (Normal Algebra):
n*0=0

P a g e 24 | 42
PYTHON PROGRAMMING Dept. of ECE

 Similarly, Boolean algebra helps simplify logical expressions involving and, or,
and not.

 Simplification Rules for and Operator


Expression Simplified To
x and False False
False and x False
y and x x and y
x and True x
True and x x
x and x x
 Tip: Anything AND False → False
Order doesn’t matter (x and y = y and x).

 Simplification Rules for or Operator


Expression Simplified To
x or False x
False or x x
y or x x or y
x or True True
True or x True
x or x x
 Tip: Anything OR True → True
Order doesn’t matter (x or y = y or x).

 Simplification Rules for not Operator


 Two not operators cancel each other:
 not (not x) == x

 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")

# Simplified step by step:


# (x and True) → x
# not (not x) → x
# Final:
if x:
print("Yes")
Same logic, cleaner code!

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.

 Example: Check if a number is Even or Odd


if x % 2 == 0:
print(x, "is even.")
print("Did you know that 2 is the only even prime?")
else:
print(x, "is odd.")
print("Multiplying two odd numbers always gives an odd result.")
Here:

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.

 Omitting the else Clause


 An if statement does not need an else part.
if x < 0:
print("The negative number", x, "is not valid.")
x = 42
print("The square root of", x, "is", [Link](x))
 If x < 0 is True, the code inside runs.
If False, the program simply continues with the next statement.
 Note: To use [Link](), you must import math at the top of your program.

 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.

CHAINED & NESTED CONDITIONALS


 Chained Conditionals
 Sometimes, we have more than two possible conditions.
 In such cases, we use if – elif – else structure.
if x < y:
<STATEMENTS_A>
elif x > y:
<STATEMENTS_B>
P a g e 27 | 42
PYTHON PROGRAMMING Dept. of ECE

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.

 Flowchart (for if–elif–else):


 Start → check first condition → if True → execute and stop
 If False → check next condition → … → else executes if all fail.

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

 Using Logical Operators Instead of Nesting


 Nested conditionals can often be simplified using logical operators (and,
or).
 Example:
# Nested version
if 0 < x:
if x < 10:
print("x is a positive single digit.")
 Simplified with and:
if 0 < x and x < 10:
print("x is a positive single digit.")
 Even shorter (Python supports chained comparisons):
if 0 < x < 10:
print("x is a positive single digit.")
 This is cleaner, easier to read, and does the same job.

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”

 Rewriting Conditions Without not


 Using not (less clear)
if not (age >= 18):
print("Hey, you're too young to get a driving licence!")

P a g e 29 | 42
PYTHON PROGRAMMING Dept. of ECE

 Using Logical Opposite (clearer)


if age < 18:
print("Hey, you're too young to get a driving licence!")
Using the opposite operator makes the code easier to understand.

 De Morgan’s Laws
 Two important rules to simplify complex Boolean expressions:

 These rules help remove not from around complex conditions.

 Example: Dragon Game


 We can attack only if:
 sword_charge ≥ 0.90
 shield_energy ≥ 100
 Complex version:
if not (sword_charge >= 0.90 and shield_energy >= 100):
print("Your attack has no effect, the dragon fries you to a crisp!")
else:
print("The dragon crumples in a heap. You rescue the gorgeous princess!")
 Simplified using De Morgan’s:
if sword_charge < 0.90 or shield_energy < 100:
print("Your attack has no effect, the dragon fries you to a crisp!")
else:
print("The dragon crumples in a heap. You rescue the gorgeous princess!")
Clearer and avoids not.

 Swapping Branches for Clarity


 Another way to eliminate not is to swap the then and else parts:
if sword_charge >= 0.90 and shield_energy >= 100:
print("The dragon crumples in a heap. You rescue the gorgeous princess!")
else:
print("Your attack has no effect, the dragon fries you to a crisp!")

 Using Intermediate Variables


 For even more clarity, break down complex conditions:
 sword_check = sword_charge >= 0.90
 shield_check = shield_energy >= 100
P a g e 30 | 42
PYTHON PROGRAMMING Dept. of ECE

if sword_check and shield_check:


print("The dragon crumples in a heap. You rescue the gorgeous princess!")
else:
print("Your attack has no effect, the dragon fries you to a crisp!")
 This version is closest to natural language, easy to read, and easy to modify
later.

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.

 Assignment vs Equality Check


Operation Symbol Meaning
Assignment = Store a value in a variable
Equality comparison == Check if two values are equal
 Important:
o a = b → assignment (not a test!)
o a == b → comparison
 Equality is symmetric: if a == 7 then 7 == a.
 Assignment is not symmetric: a = 7 but 7 = a
P a g e 31 | 42
PYTHON PROGRAMMING Dept. of ECE

 Common Mistake Example


a=5
b = a # b now has the same value as a (5)
a = 3 # a is changed, but b is still 5
After these lines:
a=3
b = 5 (not updated automatically!)
 Why this matters
o Some languages use different symbols (:= or <-) to avoid this confusion.
o Python follows C/Java style:
o = → assignment
o == → equality check

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.

Incrementing and Decrementing


 Very common in loops or counters.
 Example – Increment
runs_scored = 0
runs_scored = runs_scored + 1
 Adds 1 to runs_scored.
 Shortcut:
runs_scored += 1 # Increment by 1
P a g e 32 | 42
PYTHON PROGRAMMING Dept. of ECE

runs_scored -= 1 # Decrement by 1
o Increment → Adding 1
o Decrement → Subtracting 1
o Sometimes called “bumping” a variable.

THE FOR LOOP REVISITED


 Traversal of Lists
 The for loop processes each item in a list.
 Each item is assigned to the loop variable one by one.
 The loop body executes once for each item.
 Example – Sending Invitations
for friend in ["Joe", "Zoe", "Zuki", "Thandi", "Paris"]:
invite = "Hi " + friend + ". Please come to my party!"
print(invite)
 The loop variable friend takes on each name in the list.
 A message is created and printed for each friend.
 This process is called traversing or traversal of the list.

 Example – Summing Numbers in a List


o To find the total of a list manually, we usually:
o Start with total = 0
o Add each number one by one to the total
o Keep the updated total after each step
o In code:
numbers = [5, 6, 32, 21, 9]
running_total = 0
for number in numbers:
running_total = running_total + number
print(running_total)
o running_total keeps track of the sum as the loop progresses.
o After the loop ends, running_total holds the final total.

THE while STATEMENT


while <CONDITION>:
<STATEMENTS>
 The loop continues as long as the condition is True.
 Once the condition becomes False, the loop stops.
 Example – Sum of Numbers 0 to n
n=6

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

 Key Points About While Loops


 If the condition is False at the start, the loop body never runs.
 Always update loop variables inside the body — otherwise → 🔁 infinite
loop.
 While loops give you more manual control than for, but require more care:
o Initialize loop variables
o Write a proper condition
o Update variables inside the loop

 Equivalent for-loop version


n=6
current_sum = 0
for i in range(n+1):
current_sum += i

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.

The Collatz 3n + 1 Sequence


 Start with any positive integer n.
Generate the next number by:
 If n is even → n = n // 2
 If n is odd → n = n * 3 + 1
 Repeat until n reaches 1.
n = 1027371
while n != 1:
print(n, end=", ")
if n % 2 == 0: # n is even
n = n // 2
else: # n is odd
n=n*3+1
print(n, end=".\n")
 Explanation:
o The loop continues until n becomes 1.
o Uses end=", " in print() to print all numbers on one line separated by
commas.
o When loop ends, prints the last number with end=".\n".

TABLES & ADVANCED LOOP CONTROL

Using Loops to Generate Tables


o One of the best uses of loops is to automatically generate tabular data (e.g.,
logarithmic or trigonometric tables).
o Before computers, these tables were calculated manually — a slow and error-
prone process.
o When computers became common, they were first used to generate these tables
more accurately and efficiently.
o Example: Generating Powers of 2 Table
for x in range(13): # Generate numbers 0 to 12
print(x, "\t", 2**x) # Print x and 2^x separated by a tab
o Output
0 1
1 2

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

 The loop stops at 17 because it's odd.


 Code after the loop continues as usual.

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

PAIRED DATA (TUPLES IN LOOPS)


 Python allows you to pair values easily using tuples
 This is useful for structured data like (name, year), or (student, [subjects]).
 Example: List of Pairs
celebs = [("Brad Pitt", 1963),
("Jack Nicholson", 1937),
("Justin Bieber", 1994)]

for name, year in celebs:


if year < 1980:
print(name)
 Output
Brad Pitt
Jack Nicholson
 Loop uses two variables name, year to unpack each tuple.
 Makes code more readable and expressive.

P a g e 37 | 42
PYTHON PROGRAMMING Dept. of ECE

NESTED LOOPS FOR NESTED DATA


 You can use nested loops to process nested lists, like a list of students each
with a list of subjects.
 Example: List of Students with Courses
students = [
("John", ["CompSci", "Physics"]),
("Vusi", ["Maths", "CompSci", "Stats"]),
("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])
]

# Print each student with number of subjects


for name, subjects in students:
print(name, "takes", len(subjects), "courses")
 Output
John takes 2 courses
Vusi takes 3 courses
Jess takes 4 courses
Sarah takes 4 courses
Zuki takes 5 courses

 Example: Counting students enrolled in a specific subject


counter = 0
for name, subjects in students:
for s in subjects:
if s == "CompSci":
counter += 1

print("The number of students taking CompSci is", counter)


 Output
o The number of students taking CompSci is 3
o We used a nested for loop to check every subject of every student.

P a g e 38 | 42
PYTHON PROGRAMMING Dept. of ECE

FUNCTIONS IN PYTHON – FUNCTIONS WITH ARGUMENTS AND


RETURN VALUES

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

 Types of Functions Based on Arguments and Return Values


Return
Type Arguments Example Use Case
Value
1. No Arguments, No
❌ ❌ Displaying a message
Return
2. With Arguments, No Taking inputs, printing
✅ ❌
Return results directly
3. No Arguments, With Generating and returning
❌ ✅
Return values internally
4. With Arguments, Performing calculations and
✅ ✅
With Return ✅ returning result
 We focus here on Type 4

FUNCTIONS WITH ARGUMENTS AND RETURN VALUES


 In this type of function:
 Arguments are passed from the calling function to the called function.
 The called function processes the data and returns a result.
 The returned value can be stored in a variable, printed, or used in
expressions.
 Syntax
def function_name(parameter1, parameter2, ...):
# processing statements
return value
# Calling the function
result = function_name(argument1, argument2, ...)

P a g e 39 | 42
PYTHON PROGRAMMING Dept. of ECE

 parameter → variable inside the function (formal parameter)


 argument → value passed while calling (actual argument)
 return → used to send the output back to the caller

 Example 1: Function to Add Two Numbers


def add(a, b): # Function with 2 parameters
sum = a + b
return sum # Return the result

# Calling the function


result = add(10, 20)
print("Sum =", result)
Output
Sum = 30
o Here:
o a and b are parameters
o 10 and 20 are arguments
o return sum gives the result to result variable in main program

 Example 2: Function to Calculate Area of a Rectangle


def area(length, width):
result = length * width
return result
l = float(input("Enter length: "))
w = float(input("Enter width: "))
a = area(l, w) # Function call with arguments
print("Area of rectangle =", a)
Output
Enter length: 5
Enter width: 3
Area of rectangle = 15.0
 The inputs are taken outside the function and passed as arguments.
 The computed value is returned and printed.

 Example 3: Check Even or Odd Using Function


def is_even(num):
if num % 2 == 0:
return True
else:

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.

MULTIPLE RETURN VALUES


 In Python, a function can return multiple values as a tuple.
 Example: Returning Sum and Product
def compute(a, b):
s=a+b
p=a*b
return s, p # Return two values
x, y = compute(4, 5)
print("Sum =", x)
print("Product =", y)
Output
Sum = 9
Product = 20
 This feature is very useful for functions that need to send more than one
result.

 Difference Between print() and return


print() return
Displays output to the user Sends value back to the caller
Used for displaying results Used for further processing
Doesn’t give a value to
Can store the returned value
store
 Example
def demo1():
print("Hello")
def demo2():
return "Hello"
P a g e 41 | 42
PYTHON PROGRAMMING Dept. of ECE

print(demo1()) # Prints Hello and then None


print(demo2()) # Prints Hello only
demo1() prints but returns nothing → output includes None
demo2() returns the string → can be printed or stored

P a g e 42 | 42

You might also like