1BPLC205B Module1Notes
1BPLC205B Module1Notes
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.
❌
● 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:
This causes a runtime error because division by zero is not allowed and the error occurs while the
program is running.
Runtime error:
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.
● 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.
✅ ✅ ✅
● 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
● 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:
○ 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.
● 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.
● 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.
● 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.
● 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.
● 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.
● 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.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.
● 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.
● 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.
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.
● 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.
● 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.