0% found this document useful (0 votes)
1 views38 pages

Module-1 Py

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)
1 views38 pages

Module-1 Py

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

PYTHON PROGRAMMING

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.

1.1 The Python Programming Language


Python is a high-level programming language. Other examples of high-level
languages are C++, PHP, Pascal, C#, and Java. High-level languages are easy for
humans to read, write, and understand.
There are also low-level languages, such as machine language and assembly
language. Computers can directly execute only low-level languages. Therefore,
programs written in high-level languages must be translated into low-level
language before they can run.
Most programs are written in high-level languages because they have many
advantages:
 Easier and faster to write
 Shorter and more readable
 Less chance of errors
 Portable (can run on different types of computers with little or no
changes)
The program that translates and runs Python code is called the Python
Interpreter.
There are two ways to use the Python Interpreter:
1
PYTHON PROGRAMMING

1. Immediate Mode
In this mode, we type Python commands directly into the interpreter.
The result is shown immediately. The symbol >>> is called the Python
prompt, which indicates that the interpreter is ready to accept input.
This mode is useful for testing small pieces of code.

2. Script Mode
In this mode, we write Python code in a file called a script and then
execute it using the interpreter. Scripts can be saved, edited, and reused.
This mode is suitable for longer programs.
When writing scripts, we use a text editor, which is a program used to create
and edit text files (not a word processor like MS Word). Examples include
Notepad, Notepad++, vim, emacs, and Sublime.
There are also special programs called Integrated Development Environments
(IDEs) that provide both a text editor and tools to run Python code. Examples
include Spyder, Thonny, IDLE, and Jupyter Notebook (browser-based).
The choice of editor or IDE depends on personal preference or teacher
recommendation. However, Python itself does not depend on the editor. As
long as the syntax and indentation (tabs and spaces) are correct, Python can
run the program. The editor is only a tool to help write the code.

1.2 What is a Program?


o A program is a sequence of instructions that tells a computer how to
perform a computation.(A program is a set of instructions given to a
computer to perform a task.)
The computation can be:
 Mathematical – such as solving equations or finding roots of a
polynomial.

2
PYTHON PROGRAMMING

 Symbolic – such as searching and replacing text in a document or


compiling a program.
Although programming languages look different, most programs use a few
basic types of instructions:
Basic Instructions in a Program
1. Input
Getting data from the keyboard, a file, or another device (like a sensor).
2. Output
Displaying data on the screen or sending data to a file or another device
(like a motor).
3. Mathematical Operations
Performing calculations like addition, subtraction, multiplication, and
division.
4. Conditional Execution
Checking conditions and executing certain instructions only if the
condition is true.
5. Repetition (Looping)
Repeating an action multiple times, usually with some change.
A program is a sequence of instructions that tells a computer how to perform a
computation. These instructions include input, output, mathematical
operations, conditional execution, and repetition.

1.3 What is Debugging? (Short Theory Notes)


Programming is a complex process, and since it is done by humans, mistakes
often occur. These mistakes are called bugs, and the process of finding and
fixing them is called debugging.
The term bug has been used since at least 1889. Thomas Edison used it to
describe small technical problems in his inventions.

3
PYTHON PROGRAMMING

There are three main types of errors in a program:

1⃣ Syntax Errors
 Occur when the rules (grammar) of the programming language are not
followed.
 Example: missing brackets, incorrect indentation, or spelling mistakes in
keywords.
 The program will not run until the error is fixed.

2⃣ Runtime Errors
 Occur while the program is running.
 The program starts but stops due to an error.
 Example: dividing a number by zero.

3⃣ Semantic Errors
 The program runs without crashing, but gives the wrong result.
 The logic of the program is incorrect.
Understanding these three types of errors helps programmers find and fix
problems more quickly and effectively.

1.4 Syntax Errors


Syntax refers to the rules and structure of a programming language.
For example, in English:
 A sentence must start with a capital letter.
 A sentence must end with a period.
If these rules are not followed, it is considered a syntax error. Similarly, in
Python, rules must be followed strictly.
A syntax error happens when a program does not follow the rules (structure)
of the programming language.
Python can only run a program if it is syntactically correct.

4
PYTHON PROGRAMMING

If there is even one syntax error, Python:


 Shows an error message
 Stops the program
 Does not execute anything

1.5 Runtime Errors


A runtime error is an error that occurs while a program is running. It is called a
runtime error because the program starts executing successfully, but an error
happens during its execution.
Runtime errors are also known as exceptions, as they indicate that something
unusual or unexpected has occurred while the program is being executed.
Unlike syntax errors, runtime errors do not prevent the program from starting.
The program runs until it reaches the line where the problem occurs. At that
point, Python stops execution and displays an error message.
Runtime errors usually happen due to invalid operations, such as dividing a
number by zero, trying to open a file that does not exist, or accessing an invalid
position in a list.

🔹 Examples of Runtime Errors:


 Dividing a number by zero
 Accessing a file that does not exist
 Using an invalid index in a list

1.6 Semantic Errors


A semantic error is the third type of error in programming. It occurs when a
program runs successfully without showing any error messages, but produces
incorrect results.
In this case, the computer executes the program exactly as written. However,
the logic of the program is wrong. The program does what you told it to do, but
not what you actually intended it to do.

5
PYTHON PROGRAMMING

Semantic errors are related to the meaning (semantics) of the program. The
structure and syntax are correct, and there are no runtime problems, but the
output is incorrect because the logic or idea behind the code is wrong.
Identifying semantic errors can be difficult. Since the program runs without
errors, the programmer must carefully examine the output and trace the logic
step by step to understand where the mistake occurred.
Semantic errors usually happen due to:
 Incorrect formulas or calculations
 Wrong conditions in decision statements
 Misunderstanding of the problem requirements
Correcting semantic errors requires logical thinking and careful analysis of the
program’s behavior.

1.7 Experimental Debugging


Debugging is one of the most important skills in programming. Even though it
can sometimes be frustrating, it is also one of the most interesting and
important parts of learning to program.
Debugging is like detective work. When a program does not give the correct
result, you look at the clues (such as error messages or wrong output) and try
to find out what caused the problem.
It is also like doing a science experiment. First, you guess what might be wrong.
Then you change the program slightly and run it again to see what happens.
 If your guess is correct, the program works better.
 If your guess is wrong, you try a different idea.
This process continues until the program works correctly.
Some people say that programming and debugging are almost the same thing.
Programming is the process of writing code and continuously fixing and
improving it until it does what you want.
A good method is to:
 Start with a small program that works.

6
PYTHON PROGRAMMING

 Make small changes step by step.


 Test and fix errors as you go.
Even large systems, like the Linux operating system, started as very small
programs and were improved gradually over time.
In simple words, experimental debugging means:
 Finding problems carefully
 Making small changes
 Testing again
 Repeating the process until the program works correctly
This step-by-step improvement helps in building correct and reliable programs.

2.1 Values and Data Types


A value is one of the basic things that a program works with, such as a number
or text.
Examples of values are 4 and "Hello, World!".
Every value belongs to a specific data type (or class).

🔹 Types of Values
 4 is an integer (type: int).
 "Hello, World!" is a string (type: str).
 Numbers with decimal points like 3.2 are called floating-point numbers
(type: float).
Strings are called strings because they contain a string of characters (letters,
symbols, etc.). Strings are always written inside quotation marks.
In Python, we can check the type of a value using the type() function.
Examples:
 type("Hello, World!") → str
 type(17) → int
 type(3.2) → float

7
PYTHON PROGRAMMING

At this stage, the terms class and type can be used interchangeably.

🔹 Numbers and Strings


Values like "17" and "3.2" may look like numbers, but because they are inside
quotation marks, they are treated as strings, not numbers.

🔹 Different Ways to Write Strings


In Python, strings can be written using:
1. Single quotes ' ' (Example: name = 'Bindu')
2. Double quotes " " (Example: text = "Bindu's book")
3. Triple single quotes ''' '''
4. Triple double quotes """ """
All of these represent strings of type str.
Double quotes can contain single quotes inside them:
 "Bruce's beard"
Single quotes can contain double quotes inside them:
 'The knights who say "Ni!"'

🔹 Triple-single Strings
o Used for multi-line strings.

8
PYTHON PROGRAMMING

o Can contain both single and double quotes.


o Often used for long text or documentation.
Example:
message = '''This is a
multi-line
string.'''

Triple Double Quotes """ """


 Same purpose as triple single quotes.
 Used for multi-line strings.
 Commonly used for documentation (docstrings).
Example:
message = """This is
another multi-line
string."""

🔹 Storage of Strings
Python does not treat strings differently based on whether you use single,
double, or triple quotes. Once the program is parsed, the stored value is the
same. The quotation marks are not part of the value; they only indicate where
the string begins and ends.
When Python displays a string, it usually uses single quotes.

🔹 Important Rule About Numbers


When writing large integers in Python:
 Do not use commas (e.g., 42,000).
 Do not use spaces.

9
PYTHON PROGRAMMING

For example:
 42000 is a valid integer.
 42,000 is not treated as a single number. Python interprets it as a pair of
values.
This shows that Python, like all formal languages, is strict. Even a small change
in notation can change the meaning completely.

2.2 Variables
A variable is a name that refers to a value.
In simple words, a variable is like a container used to store data in a program.
Programming languages use variables to store information so that it can be
used later in the program.
The assignment statement gives a value to a variable:

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 ==. = → Assignment operator (used to assign value). == → Equality
operator (used to compare two values)

Error occurs because:


 You cannot assign a value to a number (literal).
 The variable must always be on the left side.

10
PYTHON PROGRAMMING

State of a Variable(Variable state or state snapshot)


The value currently stored in a variable is called its state.
If we write:
day = "Friday"
We can represent it as:
day → "Friday"
This representation is called a state snapshot.
It shows the current value stored in each variable at a particular time.

In Python, when a variable name is entered in the interpreter, the system


evaluates the variable and displays the value currently stored in it.

When the interpreter reads message, it checks the value linked to that variable
and prints it.
Similarly, when n is entered, Python displays 17, which is the current value
assigned to it.
This process is called evaluating a variable. It means retrieving or accessing the
value associated with the variable name at that moment.
Therefore, a variable does not store the name itself; it stores a value that can
be accessed whenever needed.
The term variable means something that can vary or change.
In programming, a variable can store different values at different times during
program execution.

11
PYTHON PROGRAMMING

A variable can change its value multiple times. The most recent assignment
determines the current value of the variable. Each new assignment replaces
the previous value. The old value is removed, and the variable now refers to
the new value.

2.3 Variable Names and Keywords

✅ Rules for Naming Variables


In Python, variable names must follow certain rules:
1. Variable names can be any length.
2. They can contain:
o Letters (a–z, A–Z)
o Digits (0–9)
o Underscore (_)
3. They must begin with a letter or an underscore.
4. They cannot contain special characters like $, @, #, etc.
5. Variable names are case-sensitive.

76trombones is illegal because it does not begin with a letter. more$ is illegal
because it contains an illegal character, the dollar sign.
But what’s wrong with class? It turns out that class is one of the Python
keywords. Keywords define the language’s syntax rules and structure, and they
cannot be used as variable names.
Python has thirty-something keywords (and every now and again
improvements to Python introduce or eliminate one or two):

12
PYTHON PROGRAMMING

In programming, variable names are chosen to make the program easier for
humans to read and understand. A meaningful variable name clearly indicates
the purpose of the variable and helps the programmer remember what the
stored value represents.
For example, a variable named radius clearly indicates that it stores the radius
of a circle. Similarly, area suggests that the variable stores the calculated area.
Such naming improves readability and makes the program self-explanatory.

2.4 Statements
 A statement is an instruction that the Python interpreter can execute.
 So far, we have seen only the assignment statement.
 Other types of statements include:
o while statements
o for statements
o if statements
o import statements
o (There are many other types as well.)
 When a statement is typed on the command line, Python executes it
immediately.

13
PYTHON PROGRAMMING

 Statements do not produce any result (they do not return a value).

2.5 Evaluating Expressions


An expression is a combination of values, variables, operators, and function
calls that Python can evaluate to produce a result.
An expression may contain:
 Values (like numbers or strings)
 Variables
 Operators (such as +, -, *, /)
 Function calls
When an expression is entered at the Python prompt, the interpreter evaluates
it and displays the result.

Here, len() is a built-in Python function that returns the number of characters
in a string.
Expressions and Functions
Functions can be part of expressions.
Previously seen examples of functions include:
 print()
 type()
 len()
A function call in an expression produces a value.

2.6 Operators and Operands


Operators are special symbols (tokens) that perform operations such as
addition, subtraction, multiplication, and division.

14
PYTHON PROGRAMMING

The values on which the operator works are called operands.

The asterisk (*) is the token for multiplication, and ** is the token for
exponentiation.

When a variable appears as an operand, Python replaces it with its stored value
before performing the operation.

In Python 3, the division operator / always produces a floating-point result,


even when both operands are whole numbers.
However, in some situations, we may want to find:
 The number of whole units (such as whole hours), and
 The remaining part separately.
To handle such cases, Python provides another type of division called floor
division.
The floor division operator is represented by //.
 It always returns a whole number.
 It rounds the result downward (towards the left on the number line).
 The result is the largest whole number less than or equal to the actual
division result.

15
PYTHON PROGRAMMING

2.7 Type Converter Functions


 Python provides type converter functions to change one data type into
another.
 The main type converter functions are:
o int()
o float()
o str()
The int() function converts a given value into an integer type. It can convert a
floating-point number or a numeric string into an integer.
When converting a float, it removes the decimal part without rounding the
number. This process is known as truncation toward zero.
If the given string does not represent a valid integer, Python raises a ValueError.

In int(“23 bottles”) it results in ERROR;


ValueError: invalid literal for int() with base 10: '23 bottles'

The float() function converts a value into a floating-point number. It can accept
an integer, a float, or a properly formatted numeric string and returns its
floating-point equivalent.

16
PYTHON PROGRAMMING

The str() function converts its argument into a string type. Numbers or other
data types passed to this function are transformed into their string
representation.

2.8 Order of Operations


When an expression contains more than one operator, the order in which the
operations are performed depends on the rules of precedence. Python follows
the same order of operations used in mathematics. The acronym PEMDAS
helps us remember this order.
1. Parentheses have the highest precedence. Expressions inside
parentheses are evaluated first. Parentheses can also be used to make
expressions clearer, even if they do not change the result.
2. Exponentiation (**) has the next highest precedence after parentheses.
It is evaluated before multiplication, division, addition, and subtraction.
3. Multiplication (*), Division (/), and Floor Division (//) have the same
precedence. They are evaluated before addition and subtraction.
4. Addition (+) and Subtraction (-) have the lowest precedence among
mathematical operators.

When two operators have the same precedence, they are evaluated from left
to right. This property is called left-associativity. For example, in an expression
containing both addition and subtraction, the operations are performed in the
order they appear from left to right.
However, there is an important exception. The exponentiation operator (**) is
right-associative, meaning it is evaluated from right to left. Therefore, in
expressions involving multiple exponent operators, the rightmost
exponentiation is performed first. To avoid confusion, it is recommended to use

17
PYTHON PROGRAMMING

parentheses to clearly specify the desired order when working with


exponentiation.
Thus, understanding operator precedence and associativity is essential to
ensure correct evaluation of expressions in Python programs.

2.9 Operations on Strings


In Python, mathematical operations cannot generally be performed on strings,
even if the strings contain numeric characters. Operations such as subtraction,
division, or multiplication between two strings are illegal and result in an error.
Similarly, adding a string and a number directly is not allowed because they are
different data types.

However, some operators behave differently when used with strings.


The + operator works with strings, but instead of performing addition, it
performs concatenation.

Concatenation means joining two strings together end-to-end to form a single


string. For example, combining "banana" and " nut bread" produces "banana
nut bread". Any spaces required between words must be included inside the
strings themselves.
The * operator also works with strings. When a string is multiplied by an
integer, it performs repetition. For example, "Fun" * 3 results in "FunFunFun".
In this operation, one operand must be a string and the other must be an
integer.
This behavior is somewhat similar to arithmetic operations. Just as
multiplication of numbers represents repeated addition (for example, 4 * 3
means 4 + 4 + 4), string repetition represents repeated concatenation.
However, string concatenation and repetition do not have all the same
mathematical properties as numeric addition and multiplication. For example,
18
PYTHON PROGRAMMING

numeric multiplication is commutative (3 × 4 equals 4 × 3), but string repetition


is not commutative ("Fun" * 3 is valid, while 3 * "Fun" works, but two strings
cannot be multiplied together). Also, subtraction and division are not defined
for strings.
Thus, while certain operators can be applied to strings, their meaning changes
from mathematical computation to text manipulation.

2.10 Input
Python provides a built-in function called input() to receive input from the user.
This function allows a program to pause and wait for the user to enter some
data.
When the input() function is executed, it displays a prompt message on the
screen. The user can type a value and press Enter. The text entered by the user
is then returned by the function and can be stored in a variable.
For example:
name = input("Please enter your name: ")
In this case, whatever the user types is stored in the variable name.
An important point to remember is that the input() function always returns the
entered value as a string, even if the user enters numbers. For example, if the
user enters 17, the program receives it as "17" (a string), not as an integer.
Therefore, if numerical calculations are required, the programmer must convert
the input string into the appropriate data type using type converter functions
such as int() or float().
Thus, the input() function is used to collect data from the user, and proper type
conversion is necessary when working with numeric input.

2.11 Composition
In programming, composition refers to the process of combining small building
blocks such as variables, expressions, statements, and function calls into larger
and more complex programs.

19
PYTHON PROGRAMMING

So far, these elements have been studied separately. However, one of the most
powerful features of programming languages is their ability to combine these
simple elements to solve meaningful problems.

For example, to calculate the area of a circle, a program may need to:
 Get input from the user,
 Convert the input into a numeric type,
 Perform a mathematical calculation,
 Display the result.
Each of these steps can be written separately. This makes the program clear
and easy to understand. However, programming also allows these steps to be
combined into fewer lines of code by nesting function calls and expressions
inside one another.

By composing statements together, we can create compact programs that


perform multiple actions in a single line.

This demonstrates how smaller components can be combined to form larger


functional units.
Although compact code may look impressive, it is not always the best choice
for readability. In practice, code should be written in a way that is simple and
easy for humans to understand. Breaking a problem into smaller, clear steps is
often better than combining everything into a single complex statement.
Thus, composition is the technique of building larger programs by combining
smaller parts, while maintaining clarity and readability.

20
PYTHON PROGRAMMING

2.12 The Modulus Operator


The modulus operator is used to find the remainder when one integer is
divided by another. In Python, the modulus operator is represented by the
percent symbol %.
It works only with integers (or integer expressions) and has the same
precedence as the multiplication operator.
For example, when 7 is divided by 3:

So 7 divided by 3 is 2 with a remainder of 1.


Uses of the Modulus Operator
The modulus operator is very useful in programming for several purposes:
1. Checking divisibility
If x % y equals 0, then x is divisible by y.
2. Extracting digits from a number
o x % 10 gives the last digit of a number.
o x % 100 gives the last two digits.
3. Time and unit conversions
The modulus operator is commonly used to convert larger units into
smaller units, such as converting total seconds into hours, minutes, and
remaining seconds.
For example, to convert total seconds:
 First, divide by 3600 to get the number of hours.
 Use % 3600 to find the remaining seconds.
 Divide the remaining seconds by 60 to get minutes.
 Use % 60 to get the final remaining seconds.
This demonstrates how the modulus operator helps in breaking down a total
quantity into smaller parts.

21
PYTHON PROGRAMMING

3.3 Iteration
The repeated execution of a group of statements is called iteration. Iteration
allows a program to run the same block of code multiple times, either for a
fixed number of times or until a certain condition is met.

3.3.1 Assignment
An assignment statement gives a value to a variable using the = operator.
It is legal to assign a new value to the same variable multiple times.
When a new assignment is made, the variable refers to the new value and
stops referring to the old value.

In Python, the symbol = is used for assignment, while == is used to test


equality.
An assignment statement such as a = b does not test whether a and b are
equal. Instead, it assigns the value of b to a. In contrast, a == b checks whether
the two values are equal.
Another important difference is that equality is symmetric, but assignment is
not. If a == 7, then 7 == a is also true. However, in assignment, a = 7 is valid, but
7 = a is invalid because a literal value cannot be assigned to.
An assignment can also make two variables temporarily equal. For example, if b
is assigned the value of a, both variables will have the same value at that
moment. However, if the value of a is later changed, the value of b does not
automatically change. This shows that assignment copies the value, not the
variable itself.

3.3.2 Updating Variables


When an assignment statement is executed:

22
PYTHON PROGRAMMING

1. The right-hand side expression is evaluated first.


2. The result is then assigned to the left-hand side variable.
The variable now refers to the new value.
An update occurs when the new value of a variable depends on its old value. In
this case, the new value of the variable depends on its previous value. The old
value is used in a calculation, and the result replaces the old value.
Example:

if a variable n is first assigned the value 5, and then reassigned using an


expression like 3 * n + 1, Python first calculates the expression using the
current value of n. The result of that calculation becomes the new value of n.
Thus, the variable is updated.

Updating variables is very common in programming, especially when counting


or tracking values. For example, increasing a score or counting runs in a game.
Adding 1 to a variable is called incrementing the variable. Subtracting 1 is
called decrementing the variable. Incrementing is frequently written using the
+= operator, which is a shorthand form of updating. Instead of writing a longer
assignment statement, the shorthand operator makes the code simpler and
more readable.
Thus, updating variables allows programs to modify stored values during
execution, which is essential for iteration and dynamic program behavior.

23
PYTHON PROGRAMMING

3.3.3 The for loop revisited


A for loop in Python is a control structure used to iterate (repeat) over a
sequence such as a list, tuple, string, or range.
It executes a block of code once for each item in the sequence.
Syntax
for variable in sequence:
statement(s)
o variable → Loop variable (takes each value one by one)
o sequence → List, string, range, etc.
o statement(s) → Code executed in each iteration
Example

A common use of the for loop is to calculate the total of numbers in a list. To do
this, we need a variable to store a running total. This variable keeps track of
the accumulated sum as the loop progresses.
Before the loop begins, the running total must be initialized to zero. As the
loop traverses each number in the list, the current number is added to the
running total. The variable is updated during each iteration. After the loop
finishes, the running total contains the sum of all elements in the list.
Thus, the for loop is useful for:
 Traversing lists,
 Performing repeated actions,
 Updating variables step by step,
 Solving problems such as summing values.
The combination of traversal and updating variables allows programs to
process collections of data efficiently.

24
PYTHON PROGRAMMING

A for loop is a looping statement in Python that repeatedly executes a block of


code for each item in a given sequence.

3.3.4 The while Statement


A while loop is a control structure that repeatedly executes a block of code as
long as a given condition is True.
Flow of Execution in a While Loop
The execution of a while loop follows these steps:
1. The condition is evaluated.
2. If the condition is False, the loop terminates immediately.
3. If the condition is True, the statements inside the loop body are
executed.
4. After executing the body, the program returns to re-evaluate the
condition.
5. This process repeats until the condition becomes False.
If the condition is false at the very beginning, the loop body is never executed.
Syntax:

Example:

25
PYTHON PROGRAMMING

Comparison Between while and for


The while loop requires more responsibility from the programmer. When using
a while loop, the programmer must:
 Initialize the loop variable,
 Write the condition,
 Update the loop variable inside the loop body.
In contrast, a for loop automatically manages the loop variable when iterating
over a sequence. Therefore, for loops are often simpler and less error-prone
when the number of repetitions is known in advance.
However, the while loop is more flexible and powerful in situations where the
number of iterations is not known beforehand and depends on a changing
condition.

3.3.5 The Collatz (3n + 1) Sequence


The Collatz sequence (also called the 3n + 1 sequence) is a mathematical
process defined as follows:
 Start with any positive integer n.
 If n is even, divide it by 2.
 If n is odd, multiply it by 3 and add 1.
 Repeat the process until n becomes 1.
The sequence stops when n == 1.
This process is repeated using a while loop in Python because we do not know
in advance how many steps will be required.

26
PYTHON PROGRAMMING

How the Algorithm Works


The loop continues as long as n is not equal to 1.
During each iteration:
1. The current value of n is printed.
2. The program checks whether n is even or odd using the modulus
operator (n % 2).
3. If n is even, it is divided by 2 using integer division.
4. If n is odd, it is replaced with 3n + 1.
The loop stops when n becomes 1.

Important Observations
 The value of n sometimes increases and sometimes decreases.
 There is no obvious proof that the sequence will always reach 1.
 For certain values, such as powers of two, the sequence clearly
decreases to 1.
 If we do not stop at 1, the sequence enters a repeating cycle:
1, 4, 2, 1, 4, 2, ...
The major unsolved question, called the Collatz Conjecture, states:
Every positive integer will eventually reach 1 if the Collatz rules are applied
repeatedly.
Despite extensive computer testing of very large numbers, no one has proven
or disproven this statement.

Choosing Between for and while (Theory)


In Python, both for and while loops are used for iteration, but they are suited
for different situations depending on the nature of the problem.
A for loop is generally used when the number of repetitions is known in
advance. This type of iteration is called definite iteration. In definite iteration,
we can determine beforehand how many times the loop will execute. For

27
PYTHON PROGRAMMING

example, when traversing a list, printing a multiplication table, or running a


loop a fixed number of times, the maximum number of iterations is clearly
defined. In such cases, the for loop is more appropriate and easier to manage.
On the other hand, a while loop is used when the number of repetitions is not
known in advance. This type of iteration is called indefinite iteration. In
indefinite iteration, the loop continues executing until a certain condition
becomes false. Since it is not always possible to predict how many times the
loop will run, the while loop provides the flexibility needed to handle such
situations.
The Collatz sequence is an example of indefinite iteration because we do not
know beforehand how many steps it will take for a number to reach 1. The loop
continues until the condition is satisfied, making the while loop the appropriate
choice.
Thus, the choice between for and while depends on whether the number of
iterations is known (definite iteration) or unknown (indefinite iteration).

Conclusion
The Collatz sequence is a simple yet unsolved mathematical problem. It
demonstrates the use of a while loop for indefinite iteration and highlights the
difference between definite and indefinite looping in programming.

3.3.9 Tables
Loops are useful for generating tables of values.
Before computers, mathematical tables (logarithms, trigonometric values, etc.)
were calculated manually. This process was slow and often contained errors.
With computers, generating such tables became easy and accurate.
Even today, computers sometimes use internal tables to calculate approximate
values and then refine the result.
Example: Generating a Table
The following program prints numbers in one column and their powers of 2 in
another column:

28
PYTHON PROGRAMMING

Output :

Explanation
 range(13) generates numbers from 0 to 12.
 2**x calculates 2 raised to the power of x.
 "\t" represents a tab character.
To format table output neatly, special characters called escape sequences are
used. The tab character \t creates horizontal spacing between columns,
allowing values to align properly. The newline character \n moves the cursor to
the next line.
Escape sequences begin with a backslash (\). They represent invisible
characters that control formatting. For example:
 \t represents a tab.
 \n represents a newline.
When printing output, the cursor automatically moves to the next line after
each print statement. The tab character moves the cursor to the next tab stop,
helping create aligned columns of text. Because of this, the alignment of the
second column does not depend on how many digits appear in the first
column.
Thus, loops combined with proper formatting techniques make it easy to
generate structured tables of data in Python.

29
PYTHON PROGRAMMING

3.3.10 Two-Dimensional Tables


A two-dimensional table is a table where values are arranged in rows and
columns.
The value is read at the intersection of a row and a column.
A multiplication table is a common example of a two-dimensional table.
Example: Printing Multiples of 2

The output of the program is:

Explanation
 range(1, 7) generates numbers from 1 to 6.
 The loop variable i takes each value one by one.
 2 * i calculates multiples of 2.
 end=" " prevents a newline and prints values on the same line separated
by spaces.
 The final print() moves the cursor to the next line.

Important Concepts
 range(start, stop) generates numbers starting from start up to (but not
including) stop.
 The end parameter in print() controls how the output is formatted.
 This example prints one row of a multiplication table.
 To create a full multiplication table (multiple rows and columns), nested
loops are used.

30
PYTHON PROGRAMMING

3.3.11 The break Statement


The break statement is used to immediately terminate a loop. When a break
statement is executed inside a loop, the loop stops running at once, and control
passes to the first statement after the loop body.
In other words, break forces the program to exit the loop before it has finished
all its normal iterations.

Pre-test Loop Behaviour


Both for and while loops in Python are called pre-test loops. This means that
the loop condition is checked at the beginning of each iteration, before the
loop body is executed.
 If the condition is true, the body of the loop runs.
 If the condition is false, the loop terminates.
Because the test occurs before executing the loop body, the loop may not
execute at all if the condition is false at the start.
The break statement provides a way to modify this standard behaviour. Even if
the loop condition is still true, break allows the programmer to exit the loop
early when a specific situation occurs.
Thus, the break statement gives additional control over loop execution by
allowing immediate termination of the loop when required.

31
PYTHON PROGRAMMING

3.3.14 The continue Statement (Theory)


The continue statement is a control flow statement used inside loops. It causes
the program to immediately skip the remaining statements in the current
iteration of the loop and move to the next iteration.
When the continue statement is executed:
 The rest of the loop body for that particular iteration is ignored.
 The loop does not terminate.
 Control returns to the beginning of the loop for the next iteration.
Unlike the break statement, which completely exits the loop, the continue
statement only skips the current iteration and allows the loop to continue
running.
For example, when iterating through a list of numbers, the continue statement
can be used to skip certain values (such as odd numbers) while still processing
the remaining elements in the list.
Thus, the continue statement provides finer control within a loop by allowing
selective skipping of specific iterations without stopping the entire loop.

3.3.15 Paired Data


Paired data in Python means grouping two related values together as a single
unit.
This is done using parentheses ( ), and such a pair is called a tuple.

32
PYTHON PROGRAMMING

A tuple allows us to store multiple values as a single unit. For example, a


person's name and year of birth can be stored together as a pair.

Here:
 "Paris Hilton" and 1981 are grouped together.
 The two values form one tuple.

List of Pairs
We can store multiple pairs inside a list:
In this case, each element of the list is itself a tuple containing two related
values. Even though each tuple contains two items, the list treats each tuple as
a single element.

Here:
 The list has 3 elements.
 Each element is a pair (tuple).
This type of structure is useful for representing structured data, where pieces
of information logically belong together. For example, storing a celebrity’s
name along with their birth year keeps related information organized.

Printing the List

 The list contains 3 paired elements.

33
PYTHON PROGRAMMING

Using Paired Variables in a for Loop


We can access both values in each pair using two loop variables:

Output:

Explanation
 The loop runs once for each pair in the list.
 name and year are assigned values from each tuple.
 This is called unpacking.
 Both variables receive values at the same time.

Unpacking is the process of assigning the elements of a sequence (like a tuple


or list) to multiple variables at the same time.
It allows us to extract values from a collection and store them into separate
variables in a single statement.

3.3.16 Nested Loops for Nested Data


Nested data means data stored inside another data structure.
A nested loop is a loop inside another loop. It is used to process such
structured data.

Example: List of Students with Subjects

34
PYTHON PROGRAMMING

Here,
 The outer structure is a list.
 Each element is a pair (tuple).
 Each tuple contains:
o A student name
o A list of subjects

When working with nested data, we often use nested loops. A nested loop is a
loop inside another loop. The outer loop processes each main element (such as
each student), while the inner loop processes the elements contained within
that element (such as each subject of the student).

Explanation:
 Outer loop → processes each student.
 Inner loop → checks each subject of that student.
 Counter increases when "CompSci" is found.

Output:

Nested loops are powerful tools for handling structured or hierarchical data.
They allow programmers to process complex data step by step and answer
detailed questions about the data.

35
PYTHON PROGRAMMING

4.4 Functions that Require Arguments


Most functions in Python require arguments. Arguments are values that are
passed to a function so that it can perform a specific task. They allow functions
to be more general and reusable, because the same function can work with
different inputs.
Example:

In this example, the arguments to the abs function are 5 and -5.
to compute the absolute value of a number, Python provides the built-in
function abs(). The number whose absolute value is required must be passed
as an argument. The function then returns the positive value of that number,
regardless of whether the original number was positive or negative.

Some functions take more than one argument. For example, the built-in
function pow() requires two arguments: the base and the exponent. Inside the
function, these values are assigned to variables known as parameters. The
function then performs the calculation and returns the result.

Another example is the max() function, which returns the largest value among
the arguments provided.
Unlike many functions, max() can accept multiple arguments separated by
commas.
These arguments can be simple values or even expressions. The function
evaluates all the arguments and returns the greatest one.

36
PYTHON PROGRAMMING

Thus, functions that require arguments rely on input values to perform their
operations. Arguments provide flexibility and allow a single function to handle
many different cases, making programs more efficient and modular.

4.5 Functions that Return Values


A function that returns a value is called a fruitful function.
When such a function is called, it produces a result that can be:
 Assigned to a variable
 Used in an expression
Example:

Here:
 max() and abs() return values.
 These values are stored or used in expressions.

built-in functions like max() and abs() return values. When these functions are
executed, they compute a result and give it back to the caller. The returned
value can then be assigned to a variable or used in further calculations.
This is different from functions that are executed only to perform an action,
such as drawing a shape or printing output. These functions are called void
functions because they are not executed to obtain a value, but to perform
some useful task. Even though they do not explicitly return a value, Python
automatically returns a special value called None if no return statement is
provided.

37
PYTHON PROGRAMMING

To create our own fruitful function, we use the return statement. The return
statement sends a value back to the place where the function was called. The
expression following the return keyword is evaluated, and its result becomes
the output of the function.
For example, in a function that calculates compound interest, the final
computed amount is returned using the return statement. This allows the
calling program to store the result in a variable and use it later.
It is important to understand that the argument names used when calling a
function do not need to match the parameter names defined inside the
function. When the function is called, the argument values are assigned to the
parameters. The parameter names are local to the function and exist only
within it.
Different versions of the same function may use different parameter names,
but as long as the logic is correct, they all produce the same result. However,
meaningful and descriptive variable names improve readability and make the
program easier for humans to understand.
Thus, fruitful functions are essential in programming because they allow values
to be computed and returned, making programs modular, reusable, and
organized.
Example for fruit full function:

Output:
At the end of the period you'll have 14898.457083

38

You might also like