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

1BPLC205B Module1Notes

Uploaded by

ankushshastry
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 views22 pages

1BPLC205B Module1Notes

Uploaded by

ankushshastry
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

Module 1 (Notes)

Contents:
Chapter 1
The way of the program: The Python programming language, what is a program? What is debugging?
Syntax errors, Runtime errors, Semantic errors, Experimental debugging.

Chapter 2
Variables, Expressions and Statements: Values and data types, Variables, Variable names and keywords,
Statements, Evaluating expressions, Operators and operands, Type converter functions, Order of
operations, Operations on strings, Input, Composition, The modulus operator.

Chapter 3
Iteration: Assignment, Updating variables, the for loop, the while statement, The Collatz 3n + 1 sequence,
tables, two-dimensional tables, break statement, continue statement, paired data, Nested Loops for Nested
Data.

Chapter 4
Functions: Functions with arguments and return values.
Chapter 1
The way of the program
1.1 The Python programming language
●​ Python is an example of high-level language.
●​ High-level languages are programming languages that are used for writing programs that can be
understood by humans.
●​ There are also low-level languages.
●​ Low-level languages are programming languages that are close to the hardware and easily
understood by computers.
●​ Sometimes referred to as machine languages or assembly languages.
●​ Computers can only execute programs written in low level languages.
●​ Thus, programs written in a high-level language have to be translated into something more suitable
(low-level form) before they can run.
●​ Advantages of high-level languages:
●​ Programs take less time to write.
●​ Programs are shorter and easier to read.
●​ Programs are more likely to be correct.
●​ High-level languages are portable i. e. The program written in high-level language can run on
different kinds of computers with few or no modifications.
●​ The engine that translates and runs Python is called the Python Interpreter.
●​ There are two ways to use it:
●​ Immediate mode
●​ Script mode
Each of them is explained below
●​ Immediate mode:
●​ In immediate mode, when Python expressions are typed into the Python Interpreter
window, the interpreter immediately shows the result.

●​ The >>> is called the Python prompt. The interpreter uses the prompt to indicate that
it is ready for instructions.
●​ Script mode:
●​ Alternatively, a program can be written in a file and the interpreter can be used to
execute the contents of that file. Such a file is called a script. Scripts have the
advantage that they can be saved to disk, printed, and reused.
●​ Working directly in the interpreter is convenient for testing short pieces of code
because it provides immediate feedback.
●​ When writing a script, a text editor is required. This refers to a program that edits
plain text files, not a word processor that handles layout and formatting, such as
Microsoft Word or LibreOffice Writer. Examples of text editors include Notepad,
Notepad++, Vim, Emacs, and Sublime Text.
●​ For Python, there are programs that combine a text editor with tools to interact with
the interpreter. These are called development environments or Integrated
Development Environments (IDEs). Examples for Python include Spyder, Thonny,
and IDLE. There are also browser-based development environments, such as Jupyter
Notebook.
●​ The choice of a development environment is largely personal, though in a course
setting a specific one may be recommended for consistency and support.
●​ Python is independent of the editor used, and any correctly written code with proper
syntax and indentation can be executed successfully.

1.2 What is a program?


●​ A program is a sequence of instructions that specifies how to perform a computation.
●​ The computation might be something mathematical, such as solving a system of equations or
finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and
replacing text in a document or (strangely enough) compiling a program.
●​ The exact form of instructions varies from one programming language to another, but some basic
instructions are common to almost all languages. Those are as follows:
●​ input Get data from the keyboard, a file, or some other device such as a sensor.
●​ output Display data on the screen or send data to a file or other device such as a motor.
●​ math Perform basic mathematical operations like addition and multiplication.
●​ conditional execution Check for certain conditions and execute the appropriate sequence of
statements.
●​ repetition Perform some action repeatedly, usually with some variation.
●​ Programming is a process of breaking a large, complex task into smaller and smaller subtasks until
the subtasks are simple enough to be performed with sequences of these basic instructions.

1.3 What is debugging?


●​ Programming is a complex process, and because it is done by human beings, it often leads to errors.
●​ Programming errors are called bugs.
●​ The process of tracking them down and correcting them is called debugging.
●​ Use of the term bug to describe small engineering difficulties dates back to at least 1889, when
Thomas Edison had a bug with his phonograph.
●​ Three kinds of errors can occur in a program:
●​ Syntax errors
●​ Runtime errors
●​ Semantic errors.

1.4 Syntax errors


●​ Python can only execute a program if the program is syntactically correct.
●​ Otherwise, the process fails and returns an error message.
●​ Syntax refers to the structure of a program and the rules about that structure.


●​ In English, a sentence must begin with a capital letter and end with a period.


Eg 1: this sentence contains a syntax error.
Eg 2: This sentence contains a syntax error.
●​ If there is a single syntax error anywhere in the program, Python will display an error message and
quit, and the program will not run.
●​ Eg: print("Hello World"
This causes syntax errors as the “ ) ” is missing.
Syntax error:

1.5 Runtime errors


●​ The second type of error is a runtime error.
●​ An error that does not occur until the program has started to execute but that prevents the program
from continuing.
●​ These errors are also called exceptions because they usually indicate that something exceptional
(and bad) has happened.
●​ Eg:

This causes a runtime error because division by zero is not allowed and the error occurs while the
program is running.
Runtime error:

1.6 Semantic errors


●​ The third type of error is the semantic error.
●​ If there is a semantic error in the program, it will run successfully, in the sense that the computer
will not generate any error messages, but it will not do the right thing. It will do something else.
●​ Identifying semantic errors can be tricky because it requires to work backward by looking at the
output of the program and trying to figure out what it is doing.
●​ Eg:

This is a semantic error because the syntax is correct and the program runs, but the logic is wrong.
The area should be calculated using multiplication (length * width), not addition.

1.7 Experimental debugging


●​ Debugging is one of the most important skills in programming.
●​ Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and
interesting parts of programming.
●​ Debugging is almost like detective work. A programmer is presented with clues in the form of
errors or unexpected results and must infer the sequence of events and processes that caused those
outcomes.
●​ After forming a hypothesis about what might be going wrong, the program is modified and tested
again.
●​ If the hypothesis is correct, the result can be predicted and the program moves closer to working
correctly. If the hypothesis is incorrect, a new explanation must be considered.
●​ A program is built step by step by first creating a simple version that works. Then, small changes
are added one at a time. After each change, the program is tested and any mistakes are fixed. This
way, the program keeps working properly at every stage while it is being improved.
●​ A famous example of this idea is the Linux operating system. Today, Linux has millions of lines of
code, but it started as a very simple program.
●​ Linus Torvalds first wrote it just to learn and experiment with the Intel 80386 processor.
●​ One of his early programs could only switch the screen output between “AAAA” and “BBBB.”
●​ Over time, this small and simple program was gradually improved and eventually became the Linux
kernel.
Chapter 2
Variables, Expressions and Statements
2.1 Values and data types
●​ A value is one of the fundamental things like a letter or a number that a program manipulates.
●​ These values are classified into different classes or data types.
●​ String belongs to class str
●​ Integers belongs to class int
●​ Numbers with decimal point belongs to class float
●​ Eg:

In the given example:


●​ "Hello World" → str because it is text written inside quotes.
●​ 10 → int because it is a whole number without quotes.
●​ 3.14 → float because it is a number with a decimal point.
●​ "10" → str because numbers inside quotes are treated as text.
●​ "1.2" → str because a decimal inside quotes is still text.
●​ Double quoted strings can contain single quotes inside them.

●​ Eg:
In the given example, "What's up, Doc?" is printed correctly because the string is enclosed in
double quotes, allowing the apostrophe (') inside without causing an error.
●​ Single quoted strings can contain double quotes inside them.

●​ Eg:
In the given example, "Bruce's beard" is printed correctly because the string is enclosed in double
quotes, allowing the apostrophe (') inside without causing an error.
●​ Triple quoted strings can even span multiple lines.

●​ Eg:
In the given example, """This message will span several lines.""" is written using triple double
quotes, allowing the string to span multiple lines and be printed exactly as shown.
●​ Triple quoted strings can contain single quotes or double quotes inside them.

●​ Eg:
In the given example, ''' "Oh no", she exclaimed, "Ben's bike is broken!" ''' is printed correctly
because triple quotes allow the string to contain both double quotes and an apostrophe without
causing any error.

2.2 Variables
●​ One of the most powerful features of a programming language is the ability to manipulate variables.
●​ A variable is a name that refers to a value.
●​ The assignment statement gives a value to a variable:

●​ Eg:
This example makes three assignments. The first assigns the string value "What's up, Doc?" to a
variable named message. The second gives the integer 17 to n, and the third assigns the
floating-point number 3.14159 to a variable called pi.
●​ The assignment token, =, should not be confused with equals, which uses the token ==.
●​ The assignment statement binds a name, on the left-hand side of the operator, to a value, on the
right-hand side.
●​ Tip: When reading or writing code, say to yourself “n is assigned 17” or “n gets the value 17”.
Don’t say “n equals 17”.
●​ A common way to represent variables on paper is to write the name with an arrow pointing to the
variable’s value.
●​ This kind of figure is called a state snapshot because it shows what state each of the variables is in
at a particular instant in time (At particular time what value is stored in the variable).
●​ This diagram shows the result of executing the assignment statements:

In the given diagram message variable is storing “What’s up, Doc?” , n is storing 17 and pi is
storing 3.14159. In other words a message is assigned “What’s up, Doc?”, n is assigned 17 and pi is
assigned 3.14159.

2.3 Variable names and keywords


●​ Identifiers are names used for variables, functions, arrays, and other program elements.
●​ Rules for writing variable names (identifiers):

✅ ✅ ✅
●​ Variable names can contain only letters, numbers, and underscores.
●​ Eg: message , message1 , msg_2

✅ ✅ ✅
●​ Variable names can start with a letter or an underscore (_).
●​ Eg: _message , count , total_sum

❌ ❌
●​ Variable names must not start with a number.
●​ Eg: 1count , 3total_sum

❌ ❌ ❌
●​ Variable names must not contain special characters such as @, #, $, etc.
●​ Eg: @count , $count , #total_sum
✅ ✅ ✅
●​ Variable names can be of any length.
●​ Eg: a , totalMarksofStudents ,largest_of_three
●​ Variable names are case-sensitive.
●​ Eg: Num is different from num

In the given example num is assigned 10 and Num is assigned 20 when num is accessed it is
printing value 10 and when Num is accessed it is printing value 20.


●​ Variable names must not be keywords.
●​ Eg: class, elif, etc

✅ ❌
●​ Variable name must not have space between them.
●​ Eg: total_marks , total marks
Keywords
●​ Keywords are words that are already defined by the language and cannot be used as variable names,
function names, or identifiers.
●​ Python has thirty-something keywords (and every now and again improvements to Python introduce
or eliminate one or two) & below are some of keywords:

2.4 Statements
●​ A statement is an instruction that the Python interpreter can execute.
●​ Some of statements are:
●​ assignment statement
●​ if statement
●​ else statement
●​ while statement
●​ for statement
●​ import statement, etc
●​ Assignment statement: Used to store a value in a variable.
●​ Eg: age=18
In the given example age is assigned 18
●​ If statement: Used to check a condition and execute code only if the condition is true.

●​ Eg:
In the given example, as the value of x is greater than 5, the message “x is greater than 5” is printed.
●​ Else statement: Used to execute code when the if condition is false.
●​ Eg:
In the given example, as the value of x is less than 5, the message “x is not greater than 5” is
printed.
●​ While statement: Used to repeat a block of code as long as a condition is true.

●​ Eg:
In the given example, the loop prints from 1 to 3.
●​ For statement: Used to repeat a block of code for a fixed number of times.

●​ Eg:
In the given example the loop prints from 1 to 3.
●​ Import statement: Used to include modules in a Python program so that their functions and
variables can be used.

●​ Eg:
In the given example, a random module is imported so that the randint( ) function can be used to
generate a random number between 1 to 5. This prints a random number between 1 to 5

2.5 Evaluating expressions


●​ An expression is a combination of values, variables, operators, and calls to functions.
●​ The evaluation of an expression produces a value, which is why expressions can appear on the right
hand side of assignment statements.

●​ Eg:
In the given example:
●​ The expression 1+1 is evaluated and the value 2 is printed on the screen.
●​ The len(“hello”) is evaluated and returns the number of characters in the string.
●​ A single value is itself a single expression.
●​ The variable y is assigned with the evaluated expression 10+10
2.6 Operators and Operands
●​ Operators are special tokens that represent computations like addition, multiplication and division.
●​ The values the operator uses are called operands.
●​ The tokens +, -, and *, and the use of parenthesis for grouping, mean in Python what they mean in
mathematics.

●​ Eg:
●​ The asterisk (*) is the token for multiplication, and ** is the token for exponentiation.

●​ Eg:
●​ The division operator (/) always yields a floating point result.
●​ The floor division operator yields the floor of the division result, which may be an integer or a
float, depending on the operands.

●​ Eg:
●​ When a variable name appears in the place of an operand, it is replaced with its value before the
operation is performed.

●​ Eg:

2.7 Type converter functions


●​ The process of changing values from one datatype to another is called type conversion.
●​ It helps to correct the operations and calculations.
●​ Type conversion is done when different datatypes are used in the expression.
●​ There are two type of conversions:
○​ Implicit conversion
○​ Explicit conversion
●​ Implicit conversion:
○​ Python automatically converts one data type into another.
○​ It does not cause data loss.

○​ Eg:
In the given example, num1 is assigned 10 (an integer), num2 is assigned 20.15(a float).
Python automatically converts num1 int to float. It prints the sum 30.15 in float.
●​ Explicit conversion:
○​ The programmer manually converts one data type into another.
○​ It may cause data loss.
○​ It is done with the help of functions like int( ), float( ), str( ), etc.

○​ Eg:
Note: When the conversion is done from float to int, only the decimal portion of the number
is discarded. It will not be rounded off to the nearest number.

○​ Eg:
In the given example, 3.6 is converted to 3 and 3.999 is also converted to 3 even though the
nearest number is 4.

2.8 Order of operations


●​ Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order in which the user wants.

●​ Eg:
In the given example, first parentheses will be evaluated.
●​ Exponentiation has the next highest precedence.

●​ Eg:
It is important to note that the solution of an expression is 3 and not 5
●​ Multiplication and Division operators have the same precedence.

●​ Eg:
●​ Addition and Subtraction operators have the same precedence.

●​ Eg:
●​ It is important to note that operators with the same precedence are evaluated from left-to-right.

●​ Eg:
In the given example,
○​ + and - have the same precedence. So, evaluation is done from left to right.
○​ * and // have the same precedence. So, the evaluation is done from left to right.

2.9 Operations on strings


●​ In general operation cannot be performed on strings.
●​ An integer cannot be added to or subtracted from a string.
●​ String cannot be divided by an integer.

●​ Eg:
●​ String concatenation
○​ The process of joining or combining two or more strings is called string concatenation.
○​ This is done with the help of ‘+’ operator.

○​ Eg:
In the given example, firstName is assigned John and lastName is assigned Doe. These two
strings are concatenated with the help of ‘+’ operator which provides the concatenated string
John Doe
●​ String replication
○​ The process of string repeating multiple times is called string replication.
○​ This is done with the help of ‘*’ operator.

○​ Eg:
In the given example, name is assigned John. John is replicated five times with the help of
the ‘*’ operator.

2.10 Input
●​ There is an in-built function in Python to take input from the user i. e. input( )

●​ Eg:

Output:
In the given example, input( ) function is used to get the user input. When the user provides input
and press Enter. The user input is assigned to the variable name. Following the name is printed on
screen with the help of print( ) function.

2.11 Composition
●​ So far, the basic parts of a program such as variables, expressions, statements, and function calls
have been introduced separately.
●​ Programming languages allow these small parts to be combined to form larger and more meaningful
programs.
●​ By combining simple operations like taking input from the user, converting that input to the
required data type, performing a calculation, and displaying the result, a complete program can be
created.

●​ Eg:
In this example, the program asks the user to enter the radius of a circle, converts the input into a
number, calculates the area using the formula for the area of a circle, and then prints the result.
●​ These steps can be written either as separate, clear statements or combined into fewer lines of code:
●​ Although combining many operations into a single line makes the program shorter, it can reduce
readability.

●​ Therefore, writing code in smaller, well-structured steps is generally preferred because it is easier
for humans to understand and maintain.

2.12 The modulus operator


●​ The modulus operator works on integers (and integer expressions) and gives the remainder when the
first number is divided by the second.
●​ 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.

●​ Eg:
In the given example, // (division) operator provides the quotient i. e. 2 when division operation is
performed on 7 and 3 and % (modulus) operator provides the remainder i. e. 1 when modulus
operation is performed on 7 and 3.
●​ A modulus operator can be used to check if one number is completely divisible by another number.
Chapter 3
Iteration
3.1 Iteration
●​ Repeated execution of a set of statements is called iteration.

3.3.1 Assignment
●​ It is legal to make more than one assignment to the same variable.
●​ A new assignment makes an existing variable refer to a new value (and stop referring to the old
value).
●​ Eg:

In the given example, the variable airtime_remaining is first assigned the value 15 and printed. Then
the variable is reassigned a new value 7, replacing the old value. When printed again, it displays 7,
showing that variables can be updated in Python.

3.3.2 Updating variables


●​ When Python sees an assignment statement, it first calculates or finds the value on the right side of
the = sign. After it gets that value, it stores it in the variable written on the left side. So the variable
always ends up holding the final result of the right-hand side expression.

●​ Eg:
In the given example, the variable n is first assigned the value 0. Then the expression 3*n + 5 is
evaluated using the current value of n, which becomes 3*0 + 5 = 5, and this new value is stored
back in n. Finally, print(n) displays 5 as the output.

3.3.3 The for loop revisited


●​ A for loop is used when a block of code needs to be repeated for each item in a collection or for a
fixed number of times.

●​ Syntax:
●​ Working of for loop:
○​ Python takes the first item from the sequence and assigns it to the variable.
○​ It executes the code inside the loop.
○​ It moves to the next item and repeats the process.
○​ The loop stops automatically when there are no more items left.
●​ Eg:
In the given example, a list named numbers is created with the values [5, 6, 32, 21, 9], and a
variable total is initialized to 0 to store the sum. The for loop goes through each number in the list
one by one and adds it to total using total += i. After all the numbers are processed, the final total,
which is 73, is printed.

3.3.4 The while statement


●​ A while loop is used when a block of code needs to run as long as a condition is true.

●​ Syntax:
●​ Working of while statement:
○​ A while loop works by first checking the condition.
○​ If the condition is true, the code inside the loop runs.
○​ After executing the code, the condition is checked again.
○​ This process repeats as long as the condition remains true.
○​ When the condition becomes false, the loop stops automatically.

●​ Eg:
In the given example, the variable n is set to 6, current_sum is initialized to 0 to store the total, and i
is initialized to 0. The while loop runs as long as i is less than or equal to 6, and in each iteration, the
value of i is added to current_sum, then i is increased by 1. This continues until i becomes 7, at
which point the condition becomes false and the loop stops. Finally, the program prints the total
sum, which is 21.

3.3.5 The Collatz 3n + 1 sequence


●​ The Collatz 3n + 1 sequence states that starting with any positive integer and applying specific rules
will eventually lead to the number 1.
●​ Working of Collatz 3n + 1 sequence:
○​ If the number is even, divide it by 2.
○​ If the number is odd, multiply it by 3 and add 1.
This process is repeated with the resulting number until the sequence reaches 1. Once it
reaches 1, it enters a loop of 4, 2, 1, repeating indefinitely.
●​ Eg:
In the given example, the variable n is initialized to 1027371. The while loop runs as long as n is not
equal to 1. Inside the loop, the current value of n is printed, and then the program checks whether n
is even or odd using n % 2. If n is even, it is divided by 2 using integer division (n = n // 2); if n is
odd, it is updated to 3n + 1. This process continues repeatedly until n becomes 1. After the loop
ends, the final value 1 is printed followed by a period and a newline.
●​ The Collatz sequence shows how a simple rule can create a complex and unsolved mathematical
problem.

3.3.9 Tables
●​ One of the things loops are good for is generating tables.
●​ Before computers were readily available, people had to calculate logarithms, sines and cosines, and
other mathematical functions by hand.
●​ To make that easier, mathematics books contained long tables listing the values of these functions.
●​ Creating the tables was slow and boring, and they tended to be full of errors.
●​ For some operations, computers use tables of values to get an approximate answer and then perform
computations to improve the approximation.
●​ In some cases, there have been errors in the underlying tables, most famously in the table the Intel
Pentium processor chip used to perform floating-point division.

●​ Eg:
In the given example, the for loop runs from 0 to 12 using range(13). For each value of x, it prints
the number and the value of 2**x, which means 2 raised to the power of x. This produces a table of
numbers from 0 to 12 along with their corresponding powers of 2.

3.3.10 Two-dimensional tables


●​ A two-dimensional table displays values at the intersection of rows and columns. A multiplication
table is an example of this structure.

●​ Eg:
●​ To print the multiples of 2 from 1 to 6, the loop uses range(1, 7), which generates numbers from 1
through 6. During each iteration, the variable i takes one value from this range, and 2 * i is printed
on the same line using end=" " to prevent a newline. After the loop finishes, a separate print()
statement moves the cursor to the next line.
3.3.11 The break statement
●​ The break statement in Python is used to exit or "break" out of a loop (either a for or while loop)
prematurely, before the loop has iterated through all its items or reached its condition.
●​ When the break statement is executed, the program immediately exits the loop, and the control
moves to the next line of code after the loop.

●​ Eg:
In the given example, the for loop goes through each number in the list [12, 16, 17, 24, 29]. During
each iteration, it checks whether the number is odd using i % 2 == 1. When it reaches 17, which is
odd, the break statement immediately stops the loop. After the loop ends, print("done") executes, so
the final output is:
12​
16
done
The pre-test loop — standard loop behaviour
for and while loops do their tests at the start, before executing any part of the body. They’re called
pre-test loops, because the test happens before (pre) the body. break and return (discussed later) are
our tools for adapting this standard behaviour.

3.3.14 The continue statement


●​ Python continue statement is a loop control statement that forces to execute the next iteration of the
loop while skipping the rest of the code inside the loop for the current iteration only, i.e. when the
continue statement is executed in the loop, the code inside the loop following the continue statement
will be skipped for the current iteration and the next iteration of the loop will begin.

●​ Eg:
In the given example, the for loop goes through each number in the list [12, 16, 17, 24, 29, 30].
During each iteration, it checks whether the number is odd using i % 2 == 1. If the number is odd,
the continue statement skips the rest of that iteration and moves to the next number. As a result, only
the even numbers are printed, followed by "done" at the end.

3.3.15 Paired Data


●​ Paired data means two related values stored together like a key and value, or two elements that
belong together.
●​ Eg:

In the given example, celebs is a list containing paired data, where each element is a tuple with a
celebrity’s name and birth year. The print(celebs) statement displays the entire list of tuples. The
print(len(celebs)) statement prints the number of elements in the list, which is 3, because there are
three celebrity pairs stored in the list.

3.3.16 Nested Loops for Nested Data


●​ Nested loops are programming structures where one or more loops are placed inside another loop.
●​ Nested data where one or more data are placed inside the other data.

●​ Eg:
In the given example, students is a list that contains multiple tuples. Each tuple stores two related
pieces of information: a student’s name and a list of subjects that the student is enrolled in. This is
an example of nested data because each tuple contains another list inside it. Such a structure allows
storing and organizing related data together, making it easier to process using loops or nested loops.
To print the students name:

The for loop goes through each element in the students list. Each element is a tuple containing a
student’s name and a list of subjects, which are unpacked into the variables name and subjects. The
statement len(subjects) calculates the number of subjects for that student, and the program prints the
student’s name along with the total number of courses they are taking.

The variable counter is initialized to 0 to count how many students are taking "CompSci". The outer
for loop goes through each student in the students list, unpacking the name and their list of subjects.
The inner (nested) loop goes through each subject of that student, and if the subject is equal to
"CompSci", the counter is increased by 1. After all students and their subjects are checked, the
program prints the total number of students taking CompSci.
Chapter 4
Function
4.4 Functions that require arguments
●​ Function is a block of code that performs a specific task.

●​ Syntax:
●​ Most functions require arguments: the arguments provide for generalization.
●​ Parameters are variables defined in a function declaration. This act as placeholders for the values
(arguments) that will be passed to the function.
●​ Arguments are the actual values that you pass to the function when the function is called. These
values replace the parameters defined in the function.

●​ Eg:
In the given example, abs(5) returns 5 because the absolute value of a positive number is the
number itself. The function abs(-5) also returns 5 because the absolute value removes the negative
sign and gives the distance of the number from zero. The abs() function always returns a
non-negative value.
●​ Some functions take more than one argument.

●​ Eg:
In the given example, pow(2, 3) returns 8 because it calculates 2 raised to the power of 3 (2 × 2 × 2).
Similarly, pow(7, 4) returns 2401 because it calculates 7 raised to the power of 4 (7 × 7 × 7 × 7).
The pow() function performs exponentiation.

4.5 Functions that return values


●​ Function is a block of code that performs a specific task.

●​ Syntax:
●​ A function that returns a value is called a returning function.
●​ A function that does not return a value is called a void function.
●​ Eg:
the function final_amount_v4 calculates the final amount of money after applying compound
interest. It takes four parameters: amount (initial investment), rate (annual interest rate),
compounded (number of times interest is compounded per year), and years (total number of years).
Inside the function, the compound interest formula amount * (1 + rate / compounded) **
(compounded * years) is applied and the result is returned directly.
In the main program, the user enters the amount they want to invest. The function is then called with
an interest rate of 8% (0.08), compounded 12 times per year (monthly), for 5 years. The calculated
final amount is stored in the result and printed. This shows how functions can be used to perform
financial calculations in a clean and reusable way.

You might also like