0% found this document useful (0 votes)
13 views30 pages

Python Module 1 Notes

This document provides an introduction to Python programming, covering key concepts such as variables, expressions, statements, iterations, and functions. It explains the Python interpreter modes (immediate and script), the types of programming errors (syntax, runtime, and semantic), and the debugging process. Additionally, it discusses Python's features, data types, and the structure of statements and expressions.

Uploaded by

akshayg2040
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)
13 views30 pages

Python Module 1 Notes

This document provides an introduction to Python programming, covering key concepts such as variables, expressions, statements, iterations, and functions. It explains the Python interpreter modes (immediate and script), the types of programming errors (syntax, runtime, and semantic), and the debugging process. Additionally, it discusses Python's features, data types, and the structure of statements and expressions.

Uploaded by

akshayg2040
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

INTRODUCTION TO

PYTHON PROGRAMMING
Code: 25BPLC105A/205A

2025 Scheme

MODULE 1
Introduction, Variables,
Expressions and Statements,
Iterations and Functions
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

MODULE 1

Python: Introduction, Variables, Expressions and Statements,


Iterations and Functions

Syllabus:
 The way of the program: The Python programming language, what is a
program? What is debugging? Syntax errors, Runtime errors, Semantic
errors, Experimental debugging.
 Variables, Expressions and Statements: Values and data types, Variables,
Variable names and keywords, Statements, Evaluating expressions,

1.1 The Python programming language: Python is a general-purpose,


interpreted, object-oriented, powerful high-level programming language.
o The engine that translates and runs Python is called the Python
Interpreter. The Python interpreter can be used in TWO primary
modes
1. Immediate mode: The interpreter processes the input and displays
the result or any output immediately after execution.
2. Script Mode: This mode refers to the method of executing Python
code by running a saved file containing the code. Such a file is called a
script. Scripts have the advantage that they can be saved to disk,
printed, and so on.

Page 1
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

The >>> is called the Python prompt. The interpreter uses the prompt to
indicate that it is ready for instructions. If you typed 2 + 2, and the interpreter
evaluated our expression, and replied 4, and on the next line it gave a new
prompt, indicating that it is ready for more input.
 Python interpreter modes

Immediate Mode Script Mode


It is also called the interactive
Type Non-interactive mode type
mode type
Python code is written in a file
Codes are executed line by line,
and then executed as a whole
Execution and the results or errors are
program. The interpreter reads
Style displayed immediately after
and executes the entire script
each line is entered.
from top to bottom.
Ideal for learning Python, Essential for developing larger
testing small code snippets, applications, creating reusable
Use Cases exploring the functionalities of modules, automating tasks,
libraries, performing quick and building structured
calculations, and debugging programs.
 Code is saved persistently in
files, allowing for easy
 Provides immediate modification, version control,
and sharing.
feedback.  Facilitates organised and
 Commands are not saved structured programming with
functions, classes, and
Characteristics persistently.
modules.
 Limited for developing large,  Output is displayed after the
entire script or relevant
complex programs.
sections have been executed.
 Provides better support for
debugging and testing of
larger programs.
In summary:
 Interactive mode: is for immediate execution and experimentation,
offering quick feedback.
 Script mode: is for developing and running complete, structured
programs, providing persistence and scalability.

Page 2
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

 Python language features / Advantages / Characteristics ***

1. Simple and Readable Syntax: Python's syntax is clear and easy to


read, making it an ideal language for both beginners and experienced
programmers.

2. Rich Standard Library: Python has several standard libraries that


provide ready-to-use modules and functions for various tasks.

4. Dynamically Typed: The data types of variables are determined during


run-time. We do not need to specify the data type of a variable during
writing code.

5. Object-Oriented Programming (OOP) Support: Python supports OOP


paradigms, allowing developers to create reusable and modular code
through classes and objects, encapsulation, inheritance, etc.

6. Interpreted Language: It means that the code is executed line by line


without the need for compilation. This enables rapid development cycles
and facilitates interactive programming.

7. Integrated Language: We can easily integrate it with other languages


such as C, C++, etc.

8. Cross-platform Compatibility: Python can be easily installed on


Windows, macOS, and various Linux distributions, allowing developers to
create software that runs seamlessly across different operating systems.

9. Open source and free: It is an open-source language, which means


that anyone can download it, use it, and share it. Moreover, it is free of
cost.

10. Garbage Collected: Memory allocation and deallocation are


automatically managed. Programmers do not specifically need to manage
the memory.

11. Supports GUI programming: Python has support for creating


various GUI applications. It is the most popular for making graphical
apps.

Page 3
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

1.2 What is a program?


o A program is a sequence of instructions that specifies how to perform a
computation.
o The computation might be something mathematical, logical or other
types of operations. Example: solving a system of equations or finding
the roots of a polynomial, etc.
o Every programming language includes input, output, maths, conditional
executions and repetition function, ect.

1.3 What is debugging?

o The systematic process of finding, isolating and correcting the error in


the programming is called debugging. Programming errors are called
bugs
o Three kinds of errors can occur in a program:
1. Syntax errors
2. Runtime errors
3. Semantic errors

1.4 Syntax errors:


o Syntax refers to the structure of a program and the rules about that
structure.
o A syntax error in programming refers to a mistake in the source code
that violates the grammatical rules or structure of the specific
programming language being used.
o This prevents the compiler or interpreter from understanding and
executing the code.
o If there is a single syntax error anywhere in your program, Itwill display
an error message and quit, and you will not be able to run your program.
o Common causes of syntax errors include:
1. Missing or misplaced punctuation: This can include missing
semicolons, parentheses, brackets, or quotation marks.
2. Incorrectly spelt keywords or variable names: Programming
languages have specific keywords (e.g., if, for, while) that must be
spelt correctly.
3. Improper indentation: In Python, indentation is part of the
syntax, and incorrect indentation will lead to errors.

Page 4
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

4. Using incorrect operators or symbols: For example, using = for


comparison instead of == in many languages.
5. Unmatched opening and closing elements: Such as a missing
closing parenthesis or bracket, etc.

1.5 Runtime errors:


o A runtime error in programming is an error that occurs during the
execution of a program, after it has been successfully compiled.
o Runtime errors manifest only when the program is actually running.
o These errors are also called exceptions because they usually indicate that
something exceptional (and bad) has happened.
o Common causes of runtime errors include:
1. Division by Zero: Attempting to divide a number by zero is
mathematically undefined.
2. Array Index Out of Bounds: Accessing an element in an array using
an index that is outside the valid range of indices for that array.
3. Infinite Loops or Recursion: A loop or recursive function that never
terminates, leading to resource exhaustion, etc.

1.6 Semantic errors:


o A semantic error in programming occurs when code is syntactically
correct and can be successfully compiled or interpreted. Still, it does not
produce the intended or expected results due to a wrong in its logic or
meaning.
o Identifying semantic errors can be tricky because it requires you to work
backwards by looking at the output of the program. And trying to figure
out what it is doing.
o Examples of semantic errors include:
1. Incorrect mathematical operations: Using subtraction instead of
addition, or multiplication instead of division, leading to incorrect
calculations.
2. Logical flaws: An algorithm designed to sort data might sort it in
descending order when ascending order was intended.
3. Incorrect variable assignments or usage: Assigning a value to the
wrong variable or using a variable before it has been properly
initialised, etc.

Page 5
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

1.7 Experimental debugging


o Debugging is also like an experimental science. The most important skills
you will acquire are debugging. Once you have an idea of what is going
wrong, you modify your program and try again.
o Although debugging can be frustrating, it is one of the most intellectually
rich, challenging, and interesting parts of programming.
o In some ways, debugging is like detective work. You are confronted with
clues, and you have to infer the processes and events that led to the
results you see.
o If your hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program. If your
hypothesis was wrong, you have to come up with a new one.
o Key Steps in Experimental Debugging
a. Observe and Gather Information: Note the observed error or
unexpected behaviour in the software.
b. Formulate a Hypothesis: Based on the observations, find out the
root cause of the error.
c. Make Predictions: Determine what should happen if your hypothesis
is correct after a specific modification.
d. Test the Hypothesis: Make a small change to the code,
implementing the predicted modification.
e. Analyse the Results: Observe the outcome of the change. If it
matches your prediction, you're closer to a solution. If not, refine your
hypothesis or form a new one based on the new information.
f. Repeat: Continue this cycle of modification and observation until the
error is identified and fixed.

Page 6
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

Chapter 2: Python Variables, Expressions and Statements


2.1 Values and Data Types:
 Values:
o Values are the fundamental building blocks of information within a
program's execution.
o In programming languages, a value represents a piece of data that can
be stored, manipulated, and processed by a program.
o Examples: 4, ‘Hi Good Morning', etc
 Data types:

3. String Type(str):
o Python programs can also have text values called strings, or str.
o Strings in Python are surrounded by either single quotation marks or
double quotation marks. Ex: 'Hello' is the same as "Hello".

o The string with no characters, ' ', is called a blank string.


o The data type can be identified of any object by using type( ) function
o Example 1:

Page 7
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

Example 2 Complied output

o Example 3: The values like "17" and "3.2". They look like numbers, but they
are in quotation marks like strings.

o Example 4: Strings in Python can be enclosed in either single quotes (') or


double quotes ("), or three of each (''' or """)

o Example 5: When using large integers with commas between groups of


three digits, as in 42,000 is not a legal integer in Python, but it does mean
something else, which is legal

o In the above, that’s not what we expected at all! Because of the comma,
Python chose to treat this as a pair of values. Hence not to put commas or
spaces in your integers, no matter how big they are.
o In formal languages are strict, the notation is strict, and even the smallest
change might mean something quite different from what you intended.

2.2 Variables
o Variables are pices of computer’s memory for storing data values that can be
changed or manuplate.

Page 8
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o Variable in Programming is a named storage location that holds a value or data.


o The assignment statement gives a value to a variable.
o This statement is used to assign the value to the specified variable. An
assignment statement consists of a variable name, an equal sign (called the
assignment operator), and the value to be stored.
o Example:

o In above example makes three assignments. The first assigns the string
value "What's up, Doc?" to a variable named message. The second gives


















2.3 Variable names and Keywords

 Variable names : A variable can have a short name (like x and y) or a


more descriptive name (age, carname, total_volume). We can name a
variable anything as long as it obeys the following rules:
1. It can be only one word.
2. It can’t begin with a number.
3. It can use only letters, numbers, and the underscore (_) character.
4. Only contain alpha-numeric characters and underscores (A, 0-9,
and _ )
5. Variable names are case-sensitive (age, Age & AGE are 3 different
variables)

Page 9
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o Following Table 1-3: gives examples of valid and invalid variable names

2.4 Statements
o In Python, a statement is an instruction that the Python interpreter can
execute to perform a specific action.
o When you type a statement on the command line, Python executes it.
Statements don’t produce any result.
o Common types of statements in Python are:
1. Assignment Statements 2. Expression Statements
3. Conditional Statements 4. Looping Statements
[Link] Flow Statements 7. Import Statements etc.

Page 10
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

2.5 Evaluating expressions:


o An expression is a combination of values, variables, operators, and calls
to functions.
o If you type an expression at the Python prompt, the interpreter evaluates
it and displays the result. Example

o In the above example, len is a built-in Python function that returns the
number of characters in a string.

values or variables.
o These values or variables are known as operands.
o Operators indicate the specific action to be performed, such as addition,
comparison, or logical evaluation.
o Examples of operators include:
 Arithmetic operators: + (addition), - (subtraction), * (multiplication), /
(division), ** (exponentiation).
 Comparison Operators: == (equal to), != (not equal to), > (greater
than), < (less than).
 Logical Operators: and, or, not.
 Assignment Operators: = (assignment), += (add and assign).
o Operands are the values or variables upon which an operator acts. They

Page 11
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

are the data that the operation manipulates.


o For example, in the expression x + 5: + is the operator (addition) and x
and 5 are the operands.
o Operands can be various data types, including numbers, strings,
Booleans, or even other expressions. The combination of operators and
operands forms expressions, which are then evaluated to produce a
result.
o

Note: ** Exponential, / Division, // floor division (the floor division //


rounds the result down to the nearest whole number )

Page 12
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

2.7 Type converter functions


o Python provides several built-in functions for explicit type conversion,
also known as typecasting. Some examples int, float and str,
o These functions allow a programmer to intentionally change the data
type of a value. Common Type Conversion Functions:
1. int(): Converts a value to an integer.
 It can convert floats (truncating the decimal part), numeric strings,

2.8 Order of operations


o When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
o Python follows the standard order of operations, often remembered by
the acronym PEMDAS or BEDMAS. This dictates the sequence in which
operations are evaluated within an expression

Page 13
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o Python follows the same precedence rules for its mathematical operators
that mathematics does.
o The order of operations in Python, from highest to lowest precedence, is:
1. Parentheses (): Operations within parentheses are always evaluated
first, regardless of the operators inside
 Example: result = (5 + 3) * 2 # (5 + 3) is evaluated first,
then multiplied by 2. Similarly 2 * (3-1) is 4, and (1+1)**(5-
2) is 8.
2. Exponents**:Exponentiation is evaluated after parentheses.
Exponentiation has the next highest precedence,
 Example: 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.

Page 14
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

2.9 Operations on strings


o In general, you cannot perform mathematical operations on strings, even if
the strings look like [Link] following are illegal

o Interestingly, the + operator does work with strings, but for strings, the +
operator represents concatenation, not addition.
o String concatenation and replication operation can be performed.
Concatenation is the process of joining two or more strings together and

Example :

Example: ‘Kvg’*3, results ‘kvgKvgKvg’

2.10 Input
o The input() function allows takes a user input. By default, it returns the
user input in the form of a string.
o The input() function waits for the user to type some text on the keyboard
and press ENTER.
Example 1:

Example 2:

Page 15
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

2.11 Composition
o One of the most useful features of programming languages is their ability
to take small building blocks and compose them into larger chunks.
o We know that, the elements of a program — variables, expressions,
statements, and function calls — in isolation, without talking about how
to combine them.
o For example, consider 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 𝑨 = 𝝅𝒓 𝟐
o Firstly, we’ll do the four steps one at a time:

o The modulus operator works on integers (and integer expressions) and


gives the remainder when the first number is divided by the second.
o In Python, the modulus operator is a percent sign (%). The syntax is the
same as for other operators. It has the same precedence as the
multiplication operator.

o The modulus operator useful to check whether one number is divisible by


another, conversion and extract right most digit.

Page 16
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

Chapter 3: Program Flow- Iteration

3.3 Iteration:
o Iteration in Python refers to the process of repeatedly executing a block
of code for each item in a sequence or until a certain condition is met.
o It is a fundamental concept in programming for processing collections of
data or performing repetitive tasks.
3.3.1 Assignment
o Python's assignment operators are used to assign values to variables.
o The most fundamental is the simple assignment operator, =, which
assigns the value on its right to the variable on its left.
o A new assignment makes an existing variable refer to a new value.
o Example:

Program Output

o It is especially important to distinguish between an assignment


statement and equality statement.
o Because Python uses the equal sign (=) for assignment and equality
operator is ==.
o Note that an equality test is symmetric, but assignment is not. For
example, if a == 7 then 7 == a. But in Python, the statement a = 7 is
legal and 7 = a is not.
o In Python, an assignment statement can make two variables equal, but
because further assignments can change either of them, they don’t have
to stay that way, example

o The third line changes the value of a but does not change the value of b,
so they are no longer equal.

Page 17
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

3.3.2 Updating variables


o Updating variables in Python involves changing the value that a variable
refers to. This is primarily done through assignment(=) statements.
o When an assignment statement is executed, the right-hand side
expression is evaluated first. This produces a value. Then the assignment
is made, so that the variable on the left-hand side now refers to the new
value. Example

o In above program, Line 2 means get the current value of n, multiply it by


three and add one, and assign the answer to n, thus making n refer to
the value. So after executing the two lines above, n will point/refer to the
integer 16.
o If you try to get the value of a variable that has never been assigned to,
you’ll get an error:

o Before you can update a variable, you have to initialize it to some rting
value, usually with a simple assignment

o Line 3—updating a variable by adding 1 to it—is very common. It is


called an increment of the variable; subtracting 1 is called a decrement

3.3.3 The for loop revisited


o A for loop is used for iterating over a sequence.
o With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.
o In code, a for statement always consists of the following:
1. The for keyword 2. A variable name [Link] in Keyword
4. A call on the range 5. A Colon

Page 18
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o The for loop processes each item in a list. Each item in turn is (re-)assigned
to the loop variable, and the body of the loop is executed

o Example 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
output=

o Example 2:
for friend in ["Joe", "Zoe", "Zuki", "Thandi", "Paris"]:
invite = "Hi " + friend + ". Please come to my party!"
print(invite)
Output:

line immediately after the loop in the program is executed.


o In code, a while statement always consists of the following:

1. The while keyword

2. A condition (that is an expression that evaluates to True or False.

3. A colon

4. Starting on the next line, an indented block of code (called the


while clause)
o Syntax: for a while loop statement

Page 19
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o Example1: consider the program

o Description of flow of execution for a while statement:


• Evaluate the condition at line 5, yielding a value which is either F or T.
 If the current number n is odd, the next number in the sequence
is 3n + 1.
 The conjecture states that this sequence will eventually reach the
number 1 for any positive integer starting value.
o This Python code captures this algorithm:

Page 20
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o Notice first that the print function on line 4 has an extra argument
end=", ". This tells the print function to follow the printed string with
whatever the programmer chooses (in this case, a comma followed by a
space), instead of ending the line.
o So each time something is printed in the loop, it is printed on the same
output line, with the numbers separated by commas.
o The call to print(n, end=".\n") at line 9 after the loop terminates will then
print the final value of n followed by a period and a newline character.
o Example 2:

the execution of a computer program.


o Tracing involves becoming the computer and following the flow of execution
through a sample program run, recording the state of all variables and any
output the program generates after each instruction is executed.
o Consider the Collatz 3n + 1 sequence with n=3

Page 21
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

Output sequence:

3.3.9 Tables
 One of the things loops are good for is generating tables. For some
operations, computers use tables of values to get an approximate answer
and then perform computations to improve the approximation.
 The following program outputs a sequence of values in the left column
and 2 raised to the power of that value in the right column. Example

 Output:
 The string "\t" represents a tab character.
 The backslash character in "\t" indicates the
beginning of an escape sequence.
 Escape sequences are used to represent
invisible characters like tabs and newlines. The
sequence \n represents a newline.
 An escape sequence can appear anywhere in a
string; in this example, the tab escape sequence
is the only thing in the string.
 The tab character shifts the cursor to the right
until it reaches one of the tab stops.

o Because of the tab characters between the columns, the position of the
second column does not depend on the number of digits in the first
column.

Page 22
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

3.3.10 Two-dimensional tables


o A two-dimensional table is a table where you read the value at the
intersection of a row and a column A multiplication table is a good
example.
o Let’s say to print a multiplication table for the values from 1 to 6.
o A good way to start is to write a loop that prints the multiples of 2, all on
one line, example

o 'Break' in Python is a loop control statement. It is used to control the


sequence of the loop.
o The break keyword is used to break out a for loop, or a while loop. If the
execution reaches a break statement, it immediately exits the while
loop’s clause.
o In code, a break statement simply contains the break keyword.

Page 23
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

3.3.14 The continue statement


o This is a control flow statement (continue keyword) is used to end the
current iteration in a for loop (or a while loop) and continues to the next
iteration. It is used inside the loop.
o When the program execution reaches a continue statement, the program
execution immediately jumps back to the start of the loop and
reevaluates the loop’s condition. Example 1

Example 2:

Page 24
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

3.3.15 Paired Data


o Making a pair of things in Python is as simple as putting them into
parentheses, like this:

variable names, (name, year), instead.

3.3.16 Nested Loops for Nested Data


o A nested loop means a loop statement inside another loop statement. For
a nested loop, the inner loop performs all of its iterations for each
iteration of the outer loop.
o Example: If the outer loop is running from i = 1 to 5 and the inner loop is
running from a to e. Then, for each value of the outer loop variable (i),
the inner loop will run from a to e.

Page 25
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o Nested loops in Python are used to iterate over nested data structures,
such as lists of lists, lists of dictionaries, or nested dictionaries.
o The concept involves placing one loop inside another, where the inner
loop executes completely for each iteration of the outer loop.
o Consider a case, we have a list of students. Each student has a name
which is paired up with another list of subjects that they are enrolled for:

o Now we’d like to ask how many students are taking CompSci. This needs
a counter, and for each student we need a second loop that tests each of
the subjects in turn:

Page 26
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

Chapter 4: Functions
4.4 Functions that require arguments
o In Python, functions can be defined to require arguments, meaning that
values must be provided for these arguments when the function is
called.
o Most functions require arguments: For example, if we want to find the
absolute value of a number, we have to indicate what the number is.
Python has a built-in function for computing the absolute value.
o Example 1: functions with one argument

- In above example, the arguments to the abs function are 5 and -5.
o Example 2: Some functions take more than one [Link] example
the built-in function pow takes two arguments, the base and the
exponent. Inside the function, the values that are passed get assigned to
variables called parameters.

o Example 3: Another built-in function that takes more than one argument

o max can be passed any number of arguments, separated by commas,


and will return the largest value passed. The arguments can be either
simple values or expressions. In the last example, 503 is returned, since
it is larger than 33, 125, and 1.

Page 27
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

4.5 Functions that return values


o The return statement in Python is used within a function to exit the function
and send a value back to the caller.
o Example:
def calculate_sum(a, b):
"""This function calculates the sum of two numbers."""
result = a + b
return result # Returns the calculated sum
o In Python, functions can return values to the part of the code that called
them using the return statement. This allows the function to provide a
result or data back to the main program flow for further processing,
assignment to variables, or use in other operations.
o A function that returns a value is called a fruitful function. The opposite of a
fruitful function is a void function. It is not executed for its resulting value.
o Take an example to write as a fruitful function for compound interest, the
standard formula

Page 28
Python Programming(25BPLC205A) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions

o The return statement is followed an expression (a in this case). This


expression will be evaluated and returned to the caller as the “fruit” of
calling this function.
o We prompted the user for the principal amount. The type of toInvest is a
string, but we need a number before we can work with it. Because it is
money, and could have decimal places, we’ve used the float type
converter function to parse the string and return a float.

o Notice how we entered the arguments for 8% interest, compounded 12 times


per year, for 5 years.

Page 29

You might also like