Module 1
Module 1
PYTHON PROGRAMMING
SUBJECT CODE:
1BPLC105B/205B
MODULE-1
Name:
USN:
College:
AZ Documents
Your Engineering Study Partner
[Link]
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
PYTHON PROGRAMMING
1BPLC105B/205B
Module-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.
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.
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.
Functions: Functions with arguments and return values.
Chapters: 1.1-1.7, 2.1-2.12, 3.3, 4.4, 4.5
Python is a high-level programming language, just like C++, Java, C#, PHP, and Pascal. High-level
languages are designed to be easy for humans to read, write, and understand. In contrast, low-level
languages (such as machine language and assembly language) are difficult for humans but are the only
languages computers can directly understand.
Because computers cannot run high-level language programs directly, such programs must first be
translated into low-level language. In Python, this translation and execution are handled by a program
called the Python Interpreter.
Most programs today are written in high-level languages because they offer many advantages. They take
less time to write, are shorter, easier to read, and less prone to errors. Another major advantage is
portability, meaning Python programs can run on different computers with little or no modification.
2. Script Mode: You write Python code in a file (called a script) and then run it using the interpreter.
Scripts can be saved, reused, and are better for writing longer programs.
[Link] 1
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
To write scripts, you need a text editor, such as Notepad, Notepad++, Sublime Text, Vim, or Emacs.
These editors are different from word processors like MS Word because they work only with plain text.
Some software tools combine a text editor and the Python Interpreter. These are called Development
Environments or IDEs. Popular Python IDEs include Spyder, Thonny, IDLE, and browser-based tools
like Jupyter Notebook.
The choice of editor or IDE depends on personal preference or teacher recommendation. However, it is
important to remember that Python itself does not depend on the editor. As long as the code is written
with correct syntax, indentation, and spacing, Python will execute it correctly. The editor is only a tool to
help the programmer.
The >>> is called the Python prompt. The interpreter uses the prompt to indicate that it is ready for
instructions. We 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.
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 details look different in different languages, but a few basic instructions appear in just about every
language:
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.
[Link] 2
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
subtasks are simple enough to be performed with sequences of these basic [Link] may be a
little vague, but we will come back to this topic later when we talk about algorithms.
Programming is a complex process, and because it is done by human beings, it often leads to errors.
Programming errors are called bugs and 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, and semantic errors. It is useful to distinguish between them in order to
track them down more quickly.
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.
For example, in English, a sentence must begin with a capital letter and end with a period. this sentence
contains a syntax error. So does this one For most readers, a few syntax errors are not a significant
problem, which is why we can read the poetry of E. E. Cummings without problems. Python is not so
forgiving. If there is a single syntax error anywhere in your program, Python will display an error message
and quit, and you will not be able to run your program. During the first few weeks of your programming
career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, though,
you will make fewer errors and find them faster.
The second type of error is a runtime error, so called because the error does not appear until you run the
program. These errors are also called exceptions because they usually indicate that something exceptional
(and bad) has happened. Runtime errors are rare in the simple programs you will see in the first few
chapters, so it might be a while before you encounter one.
The third type of error is the semantic error. If there is a semantic error in your 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. Specifically, it will do what you told it to do. The problem is that
the program you wrote is not the program you wanted to write. The meaning of the program (its
semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward
by looking at the output of the program and trying to figure out what it is doing.
[Link] 3
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Debugging is similar to detective work. When a program does not work as expected, the programmer
looks for clues in error messages, outputs, and program behavior. Using these clues, the programmer tries
to find out what went wrong and how the error happened.
Debugging is also like an experimental science. The programmer forms a hypothesis about what might
be causing the problem, then changes the program slightly and runs it again. If the result matches the
prediction, the hypothesis was correct, and the program moves closer to working properly. If not, the
programmer forms a new hypothesis and tries again.
The famous idea quoted by Sherlock Holmes applies well to debugging: when all impossible causes are
eliminated, whatever remains—no matter how unlikely—must be the correct explanation. This approach
encourages logical thinking and patience.
For many programmers, programming and debugging are closely connected. Programming is often
seen as a process of writing a program and continuously fixing and improving it until it works as desired.
Instead of writing a large program at once, it is better to start with a small working program and make
small changes, debugging each step. This way, the program always remains functional.
A good example of this process is the development of Linux. Today, Linux is a powerful operating system
with millions of lines of code, but it started as a very simple program written by Linus Torvalds to
experiment with computer hardware. Over time, through continuous debugging and improvement, it
evolved into the Linux operating system.
In conclusion, debugging is not just about fixing errors; it is a systematic way of thinking that helps
programmers understand, improve, and successfully build software.
A value is one of the basic things that a program works with, such as a number or a piece of text. Examples
of values include 4 (the result of 2 + 2) and "Hello, World!".
Each value in Python belongs to a specific data type (also called a class). A data type tells Python what
kind of value it is and how it can be used.
• Integer (int): Whole numbers without decimal points, such as 4, 17, or 42000.
[Link] 4
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• String (str): A sequence of characters (letters, numbers, symbols) enclosed in quotation marks,
such as "Hello, World!".
For example:
Values like "17" or "3.2" may look like numbers, but because they are inside quotation marks, Python
treats them as strings, not numbers.
[Link] 5
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• Triple quotes (''' ''' or """ """): Used for multi-line strings or strings containing both single and
double quotes.
Triple-quoted strings are especially useful when a string spans multiple lines or contains quotation marks
inside it.
Python does not treat single-quoted, double-quoted, or triple-quoted strings differently internally. The
quotation marks are not part of the value; they are only used to tell Python where the string begins and
ends.
When Python displays a string, it usually shows it with single quotes, unless single quotes are already
part of the string.
An important rule in Python is that numbers should not contain commas or spaces. For example:
This shows that Python is a strict formal language, where even a small change in notation can
completely change the meaning of the code.
[Link] 6
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
1.9 Variables
One of the most powerful features of a programming language is the use of variables. A variable is a
name that refers to a value stored in the computer’s memory. Variables allow a program to store,
remember, and manipulate data while the program is running.
In Python, values are given to variables using an assignment statement, which uses the assignment
operator =.
Examples:
• message = "What's up, Doc?" assigns a string value to the variable message.
The symbol = is called the assignment operator and should not be confused with the equality operator
==, which is used to compare two values. An assignment statement links the variable name on the left-
hand side to the value on the right-hand side.
An assignment must always have a variable on the left side. Writing 17 = n is invalid and results in a
syntax error because a literal value cannot be assigned another value.
Variables can be visualized using a state snapshot, where the variable name points to its current value.
This helps in understanding how values change during program execution.
[Link] 7
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
When a variable name is typed in the interpreter, Python displays the value currently associated with that
variable.
One important property of variables is that they are changeable. A variable can be assigned a new value
at any time, and the new value replaces the old one.
Example:
• day = "Thursday"
• day = "Friday"
• day = 21
Here, the variable day is first assigned a string, then another string, and finally an integer. Python allows
a variable to change its value and even its data type during execution.
[Link] 8
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Variables are widely used to help programs remember information, such as scores in a game, the number
of missed calls on a phone, or user input. The ability to update variable values makes programs dynamic
and useful.
In Python, variable names can be of any length. They may contain letters (a–z, A–Z), digits (0–9), and
the underscore (_) symbol. However, there are certain rules that must be followed.
A variable name must begin with a letter or an underscore, not with a digit. For example:
• myname valid
• _count valid
Although Python allows uppercase letters in variable names, by convention programmers usually use
lowercase letters. Python is case-sensitive, which means Bruce and bruce are treated as different
variables.
The underscore character _ is commonly used to separate words in variable names, especially when the
name contains multiple words, such as:
• my_name
• price_of_tea_in_china
Some variable names that begin with an underscore have special meanings in Python, so beginners are
advised to start variable names with a letter.
If an illegal character is used in a variable name, Python raises a syntax error. For example:
Python Keywords
Keywords are reserved words in Python that define the language’s syntax and structure. They cannot be
used as variable names.
[Link] 9
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
and, as, break, class, continue, def, elif, else, except, for, if, import, in, is, lambda, not, or, pass, raise,
return, try, while, with, yield, True, False, None
If Python shows an error for a variable name and the reason is unclear, it is a good idea to check whether
the name is a keyword.
Choosing Meaningful Variable Names
Programmers usually choose meaningful variable names so that the code is easy for humans to read and
understand. Good variable names act as documentation for the program.
However, beginners sometimes think that a variable name itself gives meaning to the computer. This is
not true. The computer does not understand the meaning of words like average or pi. It only follows the
instructions written by the programmer.
1.11 Statements
A statement is an instruction that the Python interpreter can execute. We have only seen the assignment
statement so far. Some other kinds of statements that we’ll see shortly are while statements, for
statements, if statements, and
When you type a statement on the command line, Python executes it. Statements don’t produce any result.
[Link] 10
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
In this example len is a built-in Python function that returns the number of characters in a string. We’ve
previously seen the print and the type functions, so this is our third example of a function!
The evaluation of an expression produces a value, which is why expressions can appear on the right hand
side of assignment statements. A value all by itself is a simple expression, and so is a variable.
Operators are special tokens that represent computations like addition, multiplication and division. The
values the operator uses are called operands.
The following are all legal Python expressions whose meaning is more or less clear:
The tokens +, -, and *, and the use of parenthesis for grouping, mean in Python what they mean in
mathematics. The asterisk (*) is the token for multiplication, and ** is the token for exponentiation.
[Link] 11
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
When a variable name appears in the place of an operand, it is replaced with its value before the operation
is performed.
In Python 3, the division operator / always yields a floating point result. What we might have wanted to
know was how many whole hours there are, and how many minutes remain. Python gives us two different
flavors of the division operator. The second, called floor division uses the token //. Its result is always a
whole number — and if it has to adjust the number it always moves it to the left on the number line. So
6 // 4 yields 1, but -6 // 4 might surprise you!
Take care that you choose the correct flavor of the division operator. If you’re working with expressions
where you
need floating point values, use the division operator that does the division accurately.
Here we’ll look at three more Python functions, int, float and str, which will (attempt to) convert their
arguments
into types int, float and str respectively. We call these type converter functions.
The int function can take a floating point number or a string, and turn it into an int. For floating point
numbers, it discards the decimal portion of the number — a process we call truncation towards zero on
the number line. Let us see this in action:
[Link] 12
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
The type converter float can turn an integer, a float, or a syntactically legal string into a float:
[Link] 13
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
1. Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-
2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) /
60, even though it doesn’t change the result.
2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and
not 27.
3. Multiplication and both Division operators have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4,
and 5-2*2 is 1, not 6.
4. Operators with the same precedence are evaluated from left-to-right. In algebra we say they are
left-associative. So in the expression 6-3+2, the subtraction happens first, yielding 3. We then add
2 to get the result 5. If the operations had been evaluated from right to left, the result would have
been 6-(3+2), which is 1. (The acronym PEDMAS could mislead you to thinking that division has
higher precedence than multiplication, and addition is done ahead of subtraction - don’t be misled.
Subtraction and addition are at the same precedence, and the left-to-right rule applies.)
Due to some historical quirk, an exception to the left-to-right left-associative rule is the
exponentiation operator **, so a useful hint is to always use parentheses to force exactly the order
you want when exponentiation is involved:
The immediate mode command prompt of Python is great for exploring and experimenting with
expressions like this.
1.16 Operations on strings
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers.
The following are illegal (assuming that message has type string):
[Link] 14
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Interestingly, the + operator does work with strings, but for strings, the + operator represents
concatenation, not addition. Concatenation means joining the two operands by linking them end-to-end.
For example:
The output of this program is banana nut bread. The space before the word nut is part of the string, and
is necessary to produce the space between the concatenated strings. The * operator also works on strings;
it performs repetition. For example, 'Fun'*3 is 'FunFunFun'. One of the operands has to be a string; the
other has to be an integer. On one hand, this interpretation of + and * makes sense by analogy with
addition and multiplication. Just as 4*3 is equivalent to 4+4+4, we expect "Fun"*3 to be the same as
"Fun"+"Fun"+"Fun", and it is. On the other hand, there is a significant way in which string concatenation
and repetition are different from integer addition and multiplication
1.17 Input
There is a built-in function in Python for getting input from the user:
The user of the program can enter the name and click OK, and when this happens the text that has been
entered is returned from the input function, and in this case assigned to the variable name. Even if you
asked the user to enter their age, you would get back a string like "17". It would be your job, as the
programmer, to convert that string into a int or a float, using the int or float converter functions we saw
earlier.
1.18 Composition
So far, we have looked at the elements of a program — variables, expressions, statements, and function
calls in isolation, without talking about how to combine them. One of the most useful features of
programming languages is their ability to take small building blocks and compose them into larger
chunks. For example, we know how to get the user to enter some input, we know how to convert the
string we get into a float, we know how to write a complex expression, and we know how to print values.
[Link] 15
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Let’s put these together in 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
Now let’s compose the first two lines into a single line of code, and compose the second two lines into
another line of code.
Such compact code may not be most understandable for humans, but it does illustrate how we can
compose bigger chunks from our building blocks.
If you’re ever in doubt about whether to compose code or fragment it into smaller steps, try to make it as
simple as you can for the human to follow. My choice would be the first case above, with four separate
steps.
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.
[Link] 16
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
The modulus operator turns out to be surprisingly useful. For example, you can check whether one
number is divisible by another—if x % y is zero, then x is divisible by y.
Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-
most digit of x (in base 10). Similarly x % 100 yields the last two digits.
It is also extremely useful for doing conversions, say from seconds, to hours, minutes and seconds. So
let’s write a program to ask the user to enter some seconds, and we’ll convert them into hours, minutes,
and remaining seconds.
1.20 Iteration
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without
making errors is something that computers do well and people do poorly.
Repeated execution of a set of statements is called iteration. Because iteration is so common, Python
provides several language features to make it easier.
1.20.1 Assignment
As we have mentioned previously, 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).
[Link] 17
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
because the first time airtime_remaining is printed, its value is 15, and the second time, its value is 7. It
is especially important to distinguish between an assignment statement and a Boolean expression that
tests for equality. Because Python uses the equal token (=) for assignment, it is tempting to interpret a
statement like a = b as a Boolean test. Unlike mathematics, it is not! Remember that the Python token for
the equality operator is ==.Note too 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. 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:
The third line changes the value of a but does not change the value of b, so they are no longer equal. (In
some programming languages, a different symbol is used for assignment, such as <- or :=, to avoid
confusion. Some people also think that variable was an unfortunae word to choose, and instead we should
have called them assignables. Python chooses to follow common terminology and token usage, also found
in languages like C, C++, Java, and C#, so we use the tokens = for assignment, == for equality, and we
talk of variables.
[Link] 18
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
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. We saw this example before:
Running through all the items in a list is called traversing the list, or traversal. Let us write some code
now to sum up all the elements in a list of numbers. Do this by hand first, and try to isolate exactly what
steps you take. You’ll find you need to keep some “running total” of the sum so far, either on a piece of
paper, in your head, or in your calculator. Remembering things from one step to the next is precisely why
[Link] 19
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
we have variables in a program: so we’ll need some variable to remember the “running total”. It should
be initialized with a value of zero, and then we need to traverse the items in the list. For each item, we’ll
want to update the running total by adding the next number to it.
The while statement in Python is used to repeat a block of code as long as a condition remains true. It
is especially useful when the number of repetitions is not known in advance.
• Then increase i by 1.
• When i becomes greater than n, the loop stops and the final sum is printed.
How a while Loop Executes (Flow of Execution)
2. If the condition is False, the loop ends and the program moves to the next statement.
3. If the condition is True, the statements inside the loop body are executed.
4. After executing the body, the program goes back and checks the condition again.
The loop body consists of all statements that are indented under the while keyword.
[Link] 20
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
If the condition is False the very first time it is checked, the loop body is never executed.
Loop Termination and Infinite Loops
The body of a while loop must change one or more variables involved in the condition. If the condition
never becomes False, the loop will run forever. This situation is called an infinite loop.
In this example:
• n is a fixed value.
In more complex programs, it is sometimes difficult to know whether a while loop will ever stop.
The same task can be written more simply using a for loop:
This makes for loops simpler and less error-prone when iterating over a known range.
Although for loops are easier in many cases, while loops provide more control. They are useful when:
• The number of iterations is not known beforehand
[Link] 21
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
The Collatz sequence is a famous mathematical sequence that has puzzled mathematicians for many
years. Even today, no one has been able to fully prove why it behaves the way it does.
Start with any positive integer n and repeatedly apply the following rules:
• If n is even, divide it by 2 → n = n // 2
• The print(..., end=", ") keeps printing numbers on the same line
• When n finally becomes 1, the loop stops and prints the final value
• Sometimes n increases
• Sometimes n decreases
Because of this unpredictable behavior, it is not obvious whether the sequence will always reach 1. For
so me numbers, termination is easy to prove. For example, if n starts as a power of 2 (like 16), it will
always be even and quickly reduce to 1. However, for many other numbers, the sequence can take a very
long time before reaching 1. Some small starting numbers require more than 100 steps.
[Link] 22
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
All positive integers will eventually reach 1 if the Collatz rules are applied repeatedly.
So far:
If the process does not stop at 1, the sequence enters a repeating cycle:
1 → 4 → 2 → 1 → 4 → 2 → ...
One possibility is that other cycles might exist, but none have been found yet.
• You know in advance how many times the loop will run Examples:
• Printing tables
• You do not know in advance how many iterations are needed Examples:
[Link] 23
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Initial State
• n=3
Step-by-Step Execution
• 3 is printed
• New value of n = 3 * 3 + 1 = 10
Then the loop repeats:
3 3,
10 3, 10,
5 3, 10, 5,
16 3, 10, 5, 16,
8 3, 10, 5, 16, 8,
4 3, 10, 5, 16, 8, 4,
2 3, 10, 5, 16, 8, 4, 2,
1 3, 10, 5, 16, 8, 4, 2, 1.
When n becomes 1, the condition n != 1 becomes False, and the loop terminates. The final value 1 is
printed outside the loop.
[Link] 24
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• The final value 1 is not printed inside the loop, which is why a separate print statement is needed
after the loop
• Improve efficiency
This section explains how a program can count the number of digits in a positive integer using a while
loop.
o count is increased by 1
[Link] 25
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• The final value of count represents the number of digits in the original number
This technique is called a counter pattern, where a variable is incremented each time a loop executes.
n count
3029 0
302 1
30 2
3 3
0 4
Explanation
• n % 10 extracts the last digit of the number
• The if condition checks whether the digit is 0 or 5
This program counts how many times the digits 0 or 5 appear in the number.
• count remains 0
[Link] 26
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• The number 0 has one digit, but the loop never runs
• Counter pattern
Python provides extensive built-in documentation for its language features, functions, and libraries.
Programmers can use this documentation to understand how functions work, what arguments they take,
and how they should be used. This help is available through official Python documentation websites and
also through built-in help tools.
When reading Python documentation, you will often see special symbols and formatting that are not
part of actual Python code. These are called meta-notation. Meta-notation is used to describe Python
syntax, not to be typed directly into programs.
• stop is mandatory
• start is optional
• step is optional
• 1 argument: range(stop)
• 2 arguments: range(start, stop)
The documentation also tells us that all arguments to range() must be integers and that the sequence can
increase or decrease depending on the step.
[Link] 27
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• Bold text represents exact Python keywords or symbols that must be typed exactly as shown.
• Italic text represents a placeholder, meaning you should replace it with something valid of that
type.
For example:
Here:
Example:
print([object, ...])
1.20.9 Tables
One of the important uses of loops in programming is to generate tables of values. Before computers
were common, people manually calculated values such as logarithms, sines, and cosines and wrote them
in printed tables. This process was slow, boring, and often contained errors.
With the arrival of computers, it became easy to generate such tables automatically and accurately.
Eventually, calculators and computers became so common that printed tables were no longer needed.
[Link] 28
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
However, tables are still used internally by computers for approximate calculations, such as in floating-
point arithmetic. In fact, one of the most famous computer bugs occurred due to an error in the floating-
point division table of the Intel Pentium processor.
Even though tables are not as important today, they are still an excellent example to demonstrate iteration
using loops.
The string "\t" represents a tab character. The backslash (\) begins an escape sequence, which represents
characters that are not visible on the screen.
Common escape sequences:
• \t → Tab
• \n → New line
"\\"
When text is printed on the screen, an invisible pointer called the cursor keeps track of where the next
character will appear. Normally, after a print statement, the cursor moves to the beginning of the next
line. The tab character (\t) moves the cursor to the next tab stop. This helps align text neatly into columns,
regardless of how many digits appear in each column.
[Link] 29
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Because of the tab character, the second column remains properly aligned even when the first column has
numbers with different digit lengths.
A two-dimensional table is a table in which values are arranged in rows and columns, and each value
is found at the intersection of a row and a column. A multiplication table is a common and easy
example of a two-dimensional table.
For example, a multiplication table shows how each number (row) is multiplied by another number
(column).
Before printing a full table, it is helpful to start with a single row. The following program prints the
multiples of 2 from 1 to 6 on a single line.
• end=" " prevents the print function from moving to a new line and instead prints a space after each
value
• The final print() moves the cursor to the next line after the loop finishes
[Link] 30
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
To create a complete multiplication table (rows and columns), we would later use nested loops, where:
This process of improving and generalizing code step by step is an important programming practice.
The break statement is used to immediately leave the body of its loop. The next statement to be executed
is the first one after the body:
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.
[Link] 31
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
In programming, loops can differ based on where the exit condition is tested. Some languages provide
separate loop constructs for each case, but Python uses only the while loop, combined with if and break,
to handle all these variations.
A middle-test loop checks the exit condition after doing some work, but before finishing the loop
body. This pattern is very common in interactive programs, where input must be read first before
deciding whether to continue.
[Link] 32
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
How It Works
• while True: creates an infinite loop
• If the user enters a blank line or -1, the loop exits using break
Here, the exit decision happens in the middle of the loop body.
The condition True is always true, so the loop would normally run forever. This is a Python idiom—a
commonly accepted programming pattern. Since the loop cannot end naturally, the programmer must
explicitly exit using break. Modern compilers and interpreters recognize this as a dummy condition, so
they optimize it efficiently.
2. Post-Test Loop
A post-test loop checks its exit condition after the loop body has executed at least once. This ensures
that the loop body always runs at least one time.
Python does not have a built-in post-test loop, but we can simulate it using while True: and break.
while True:
play_the_game_once()
response = input("Play again? (yes or no)")
if response != "yes":
break
print("Goodbye!")
Explanation
[Link] 33
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Interactive programs and file-processing programs often require middle-test or post-test loops, because
the decision to stop can only be made after reading input.
1.12.13 An example
This program makes use of the mathematical law of trichotomy (given real numbers a and b, exactly one
of these three must be true: a > b, a < b, or a == b). At line 18 there is a call to the input function, but we
don’t do anything with the result, not even assign it to a variable. This is legal in Python. Here it has the
effect of popping up the input dialog window and waiting for the user to respond before the program
terminates. Programmers often use the trick of doing some extra input at the end of a script, just to keep
the window [Link] notice the use of the message variable, initially an empty string, on lines 6, 12 and
14. Each time through the loop we extend the message being displayed: this allows us to display the
program’s feedback right at the same place as we’re asking for the next guess.
[Link] 34
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
This is a control flow statement that causes the program to immediately skip the processing of the rest of
the body of
the loop, for the current iteration. But the loop still carries on running for its remaining iterations:
In Python, data can be grouped together to form pairs, which allow related pieces of information to be
stored and processed together. A pair is created by placing two values inside parentheses, separated by a
comma. Such a structure is commonly called a tuple.
[Link] 35
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Here:
• 1981 is the year of birth Both values together form one paired data item
• The condition checks the year and prints the name if it is less than 1980
This is different from earlier loops that used only one loop variable.
In Python, data is often nested, meaning that one data structure exists inside another. To process such
data, we use nested loops—that is, a loop inside another loop.
[Link] 36
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
In this example, we have a list of students. Each student’s data consists of:
• A name
Here:
• students is a list
Explanation
• The loop runs once for each student
[Link] 37
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Explanation
• The outer loop goes through each student
• The inner loop goes through each subject of that student
Output
counter = 0
for name, subjects in students:
if "CompSci" in subjects:
counter += 1
[Link] 38
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• Student databases
• Product catalogs
• Movie–actor lists
• Music playlists
Before calculators and computers existed, people computed square roots manually. Newton’s method is
especially powerful because it converges very quickly, meaning it reaches an accurate result in only a
few steps.
Each time this formula is applied, the result gets closer to the actual square root.
Exact equality between two real numbers is unreliable in computers because real numbers are stored
approximately. Instead, we stop when the difference between two successive guesses is very small.
[Link] 39
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Example: sqrt(25)
If you start with an initial guess (say 12.5) and repeatedly apply Newton’s formula, you will see that:
[Link] 40
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
1.20.18 Algorithms
Newton’s method is an example of an algorithm. An algorithm is a step-by-step, mechanical process
used to solve a class of problems, not just one specific problem. In this case, Newton’s method provides
a general way to compute square roots of any number.
Some types of knowledge are algorithmic, meaning they follow a fixed procedure. Examples include:
• Addition with carrying
• Long division
These processes follow clear rules and can be repeated for many similar problems.
Other kinds of knowledge rely on memorization rather than procedures. Examples include:
• Remembering historical dates
The idea that complex problems can be solved through simple, step-by-step procedures is one of the
greatest breakthroughs in human history. With computers executing algorithms, humans can solve
problems at a scale and speed that was previously impossible.
Designing Algorithms
While executing an algorithm may be repetitive or boring, designing algorithms is:
• Intellectually challenging
[Link] 41
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• Creative
• A central part of programming
Limits of Algorithms
Interestingly, some tasks that humans perform easily are very difficult to express algorithmically. A
good example is understanding natural language. Humans understand language naturally, but creating
a complete step-by-step algorithm to explain how this happens is extremely challenging and still an open
problem in computer science.
Most functions in Python require arguments. Arguments are the values that we pass to a function so that
it can perform its task. Arguments allow functions to be generalized, meaning the same function can
work with many different inputs.
Here, 5 and -5 are the arguments passed to the function. The function uses these values to compute the
result.
• The base
• The exponent
Some functions take more than one argument. For 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.
[Link] 42
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
Functions in Python can be divided into two main types based on whether they return a value or not.
A function that returns a value is called a fruitful function. When such a function is called, it produces a
result that can:
• Be stored in a variable, or
Here:
• max() returns the largest value
Void Functions
Some functions are written not to compute a value, but to perform an action, such as drawing or
printing.
For example, a function like draw_square() is executed to make the turtle draw a shape, not to return a
number.
[Link] 43
1BPLC105B/205B PYTHON PROGRAMMING MODULE-01 AZ Documents
• 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.
[Link] 44
Thank You
We’re glad to be part of your engineering journey.
Keep exploring, keep innovating, and keep growing.
AZ Documents
Your Engineering Study Partner
[Link]