Module-1 Py
Module-1 Py
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. 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.
2
PYTHON PROGRAMMING
3
PYTHON PROGRAMMING
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.
4
PYTHON PROGRAMMING
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.
6
PYTHON PROGRAMMING
🔹 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.
🔹 Triple-single Strings
o Used for multi-line strings.
8
PYTHON PROGRAMMING
🔹 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.
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)
10
PYTHON PROGRAMMING
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.
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
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.
14
PYTHON PROGRAMMING
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.
15
PYTHON PROGRAMMING
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.
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
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.
20
PYTHON PROGRAMMING
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.
22
PYTHON PROGRAMMING
23
PYTHON PROGRAMMING
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
Example:
25
PYTHON PROGRAMMING
26
PYTHON PROGRAMMING
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.
27
PYTHON PROGRAMMING
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
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
31
PYTHON PROGRAMMING
32
PYTHON PROGRAMMING
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.
33
PYTHON PROGRAMMING
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.
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
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.
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