PYTHON PROGRAMMING
Code: 1BPLCK105B/205B
Dr. SURESHA V
A Simplified Notes As per VTU Syllabus
2025 Scheme
MODULE 1
Introduction, Variables,
Expressions and Statements,
Iterations and Functions
Professor & Principal
Dept. of E&CE
K.V.G. College of Engineering, Sullia, D.K-574 327
Affiliated to Visvesvaraya Technological University
Belagavi - 590018
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
MODULE 1
Python: Introduction, Variables, Expressions and Statements,
Iterations and Functions
Syllabus:
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
Text Book: Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris
Meyers- How to think like a computer scientist: learning with python 3. Green
Tea Press, Wellesley, Massachusetts,2020
Chapter 1: The Way of the Program
1.1 The Python programming language: Python is a general-purpose,
interpreted, object-oriented, powerful high-level programming language.
o The engine that translates and runs Python is called the Python
Interpreter. The Python interpreter can be used in TWO primary
modes
1. Immediate mode: The interpreter processes the input and displays
the result or any output immediately after execution.
2. Script Mode: This mode refers to the method of executing Python
code by running a saved file containing the code. Such a file is called a
script. Scripts have the advantage that they can be saved to disk,
printed, and so on.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 1
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
The >>> is called the Python prompt. The interpreter uses the prompt to
indicate that it is ready for instructions. If you 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.
Python interpreter modes
Immediate Mode Script Mode
It is also called the interactive
Type Non-interactive mode type
mode type
Python code is written in a file
Codes are executed line by line,
and then executed as a whole
Execution and the results or errors are
program. The interpreter reads
Style displayed immediately after
and executes the entire script
each line is entered.
from top to bottom.
Ideal for learning Python, Essential for developing larger
testing small code snippets, applications, creating reusable
Use Cases exploring the functionalities of modules, automating tasks,
libraries, performing quick and building structured
calculations, and debugging programs.
Code is saved persistently in
files, allowing for easy
Provides immediate modification, version control,
and sharing.
feedback. Facilitates organised and
Commands are not saved structured programming with
functions, classes, and
Characteristics persistently.
modules.
Limited for developing large, Output is displayed after the
entire script or relevant
complex programs.
sections have been executed.
Provides better support for
debugging and testing of
larger programs.
In summary:
Interactive mode: is for immediate execution and experimentation,
offering quick feedback.
Script mode: is for developing and running complete, structured
programs, providing persistence and scalability.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 2
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
Python language features / Advantages / Characteristics ***
1. Simple and Readable Syntax: Python's syntax is clear and easy to
read, making it an ideal language for both beginners and experienced
programmers.
2. Rich Standard Library: Python has several standard libraries that
provide ready-to-use modules and functions for various tasks.
3. High-level Language: It is easier for humans to understand and write.
This nature makes Python suitable for rapid development and
prototyping.
4. Dynamically Typed: The data types of variables are determined during
run-time. We do not need to specify the data type of a variable during
writing code.
5. Object-Oriented Programming (OOP) Support: Python supports OOP
paradigms, allowing developers to create reusable and modular code
through classes and objects, encapsulation, inheritance, etc.
6. Interpreted Language: It means that the code is executed line by line
without the need for compilation. This enables rapid development cycles
and facilitates interactive programming.
7. Integrated Language: We can easily integrate it with other languages
such as C, C++, etc.
8. Cross-platform Compatibility: Python can be easily installed on
Windows, macOS, and various Linux distributions, allowing developers to
create software that runs seamlessly across different operating systems.
9. Open source and free: It is an open-source language, which means
that anyone can download it, use it, and share it. Moreover, it is free of
cost.
10. Garbage Collected: Memory allocation and deallocation are
automatically managed. Programmers do not specifically need to manage
the memory.
11. Supports GUI programming: Python has support for creating
various GUI applications. It is the most popular for making graphical
apps.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 3
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
1.2 What is a program?
o A program is a sequence of instructions that specifies how to perform a
computation.
o The computation might be something mathematical, logical or other
types of operations. Example: solving a system of equations or finding
the roots of a polynomial, etc.
o Every programming language includes input, output, maths, conditional
executions and repetition functions, etc.
1.3 What is debugging?
o The systematic process of finding, isolating and correcting the error in
the programming is called debugging. Programming errors are called
bugs
o Three kinds of errors can occur in a program:
1. Syntax errors
2. Runtime errors
3. Semantic errors
1.4 Syntax errors:
o Syntax refers to the structure of a program and the rules about that
structure.
o A syntax error in programming refers to a mistake in the source code
that violates the grammatical rules or structure of the specific
programming language being used.
o This prevents the compiler or interpreter from understanding and
executing the code.
o If there is a single syntax error anywhere in your program, Itwill display
an error message and quit, and you will not be able to run your program.
o Common causes of syntax errors include:
1. Missing or misplaced punctuation: This can include missing
semicolons, parentheses, brackets, or quotation marks.
2. Incorrectly spelt keywords or variable names: Programming
languages have specific keywords (e.g., if, for, while) that must be
spelt correctly.
3. Improper indentation: In Python, indentation is part of the
syntax, and incorrect indentation will lead to errors.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 4
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
4. Using incorrect operators or symbols: For example, using = for
comparison instead of == in many languages.
5. Unmatched opening and closing elements: Such as a missing
closing parenthesis or bracket, etc.
1.5 Runtime errors:
o A runtime error in programming is an error that occurs during the
execution of a program, after it has been successfully compiled.
o Runtime errors manifest only when the program is actually running.
o These errors are also called exceptions because they usually indicate that
something exceptional (and bad) has happened.
o Common causes of runtime errors include:
1. Division by Zero: Attempting to divide a number by zero is
mathematically undefined.
2. Array Index Out of Bounds: Accessing an element in an array using
an index that is outside the valid range of indices for that array.
3. Infinite Loops or Recursion: A loop or recursive function that never
terminates, leading to resource exhaustion, etc.
1.6 Semantic errors:
o A semantic error in programming occurs when code is syntactically
correct and can be successfully compiled or interpreted. Still, it does not
produce the intended or expected results due to a wrong in its logic or
meaning.
o Identifying semantic errors can be tricky because it requires you to work
backwards by looking at the output of the program. And trying to figure
out what it is doing.
o Examples of semantic errors include:
1. Incorrect mathematical operations: Using subtraction instead of
addition, or multiplication instead of division, leading to incorrect
calculations.
2. Logical flaws: An algorithm designed to sort data might sort it in
descending order when ascending order was intended.
3. Incorrect variable assignments or usage: Assigning a value to the
wrong variable or using a variable before it has been properly
initialised, etc.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 5
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
1.7 Experimental debugging
o Debugging is also like an experimental science. The most important skills
you will acquire are debugging. Once you have an idea of what is going
wrong, you modify your program and try again.
o Although debugging can be frustrating, it is one of the most intellectually
rich, challenging, and interesting parts of programming.
o In some ways, debugging is like detective work. You are confronted with
clues, and you have to infer the processes and events that led to the
results you see.
o If your hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program. If your
hypothesis was wrong, you have to come up with a new one.
o Key Steps in Experimental Debugging
a. Observe and Gather Information: Note the observed error or
unexpected behaviour in the software.
b. Formulate a Hypothesis: Based on the observations, find out the
root cause of the error.
c. Make Predictions: Determine what should happen if your hypothesis
is correct after a specific modification.
d. Test the Hypothesis: Make a small change to the code,
implementing the predicted modification.
e. Analyse the Results: Observe the outcome of the change. If it
matches your prediction, you're closer to a solution. If not, refine your
hypothesis or form a new one based on the new information.
f. Repeat: Continue this cycle of modification and observation until the
error is identified and fixed.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 6
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
Chapter 2: Python Variables, Expressions and Statements
2.1 Values and Data Types:
Values:
o Values are the fundamental building blocks of information within a
program's execution.
o In programming languages, a value represents a piece of data that can
be stored, manipulated, and processed by a program.
o Examples: 4, ‘Hi Good Morning', etc
Data types:
o A data type is a category for values, and every value belongs to one data
type. In programming, a datatype is an important concept.
o Some types of data are as follows, with an example
1. Integer type(int):
o It is a numeric data type in Python used to hold numeric values.
o The integer (or int) data type indicates values that are whole numbers.
o It is represented as int and it holds signed integers of non-limited length.
o For example, int: 2, 3, 0, -13, 78, -132, etc.
2. Float type(float):
o It is also a numeric data type in Python used to hold numeric values.
o The float (or float) data type indicates values that are decimal numbers.
o It is represented as a float and it holds floating decimal points and it's
accurate up to 15 decimal places. Ex Float: 2.345, -0.234, 5.0, 1.23, etc..
3. String Type(str):
o Python programs can also have text values called strings, or str.
o Strings in Python are surrounded by either single quotation marks or
double quotation marks. Ex: 'Hello' is the same as "Hello".
o The string with no characters, ' ', is called a blank string.
o The data type can be identified of any object by using type( ) function
o Example 1:
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 7
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
Example 2 Complied output
o Example 3: The values like "17" and "3.2". They look like numbers, but they
are in quotation marks like strings.
o Example 4: Strings in Python can be enclosed in either single quotes (') or
double quotes ("), or three of each (''' or """)
o Example 5: When using large integers with commas between groups of
three digits, as in 42,000 is not a legal integer in Python, but it does mean
something else, which is legal
o In the above, that’s not what we expected at all! Because of the comma,
Python chose to treat this as a pair of values. Hence not to put commas or
spaces in your integers, no matter how big they are.
o In formal languages are strict, the notation is strict, and even the smallest
change might mean something quite different from what you intended.
2.2 Variables
o Variables are pices of computer’s memory for storing data values that can be
changed or manuplate.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 8
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o Variable in Programming is a named storage location that holds a value or data.
o The assignment statement gives a value to a variable.
o This statement is used to assign the value to the specified variable. An
assignment statement consists of a variable name, an equal sign (called the
assignment operator), and the value to be stored.
o Example:
o In above 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.
Overwriting the variable: It refers to the process of assigning a new
value to an existing variable, thereby replacing its previous value. example
2.3 Variable names and Keywords
Variable names : A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume). We can name a
variable anything as long as it obeys the following rules:
1. It can be only one word.
2. It can’t begin with a number.
3. It can use only letters, numbers, and the underscore (_) character.
4. Only contain alpha-numeric characters and underscores (A, 0-9,
and _ )
5. Variable names are case-sensitive (age, Age & AGE are 3 different
variables)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 9
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o Following Table 1-3: gives examples of valid and invalid variable names
o Python Kewords: Keywords in Python are reserved words that have
special meaning and purpose within the language. They are fundamental
building blocks that define the syntax and structure of Python programs.
“A variable name cannot be any of the Python keywords”.
o Python has thirty-something keywords.
2.4 Statements
o In Python, a statement is an instruction that the Python interpreter can
execute to perform a specific action.
o When you type a statement on the command line, Python executes it.
Statements don’t produce any result.
o Common types of statements in Python are:
1. Assignment Statements 2. Expression Statements
3. Conditional Statements 4. Looping Statements
5.Control Flow Statements 7. Import Statements etc.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 10
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
2.5 Evaluating expressions:
o An expression is a combination of values, variables, operators, and calls
to functions.
o If you type an expression at the Python prompt, the interpreter evaluates
it and displays the result. Example
o In the above example, len is a built-in Python function that returns the
number of characters in a string.
o 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. Example
2.6 Operators and operands
o Operators are special symbols or keywords that perform operations on
values or variables.
o These values or variables are known as operands.
o Operators indicate the specific action to be performed, such as addition,
comparison, or logical evaluation.
o Examples of operators include:
Arithmetic operators: + (addition), -
(subtraction), * (multiplication), / (division), ** (exponentiation).
Comparison Operators: == (equal to), != (not equal to), > (greater
than), < (less than).
Logical Operators: and, or, not.
Assignment Operators: = (assignment), += (add and assign).
o Operands are the values or variables upon which an operator acts. They
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 11
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
are the data that the operation manipulates.
o For example, in the expression x + 5: + is the operator (addition) and x
and 5 are the operands.
o Operands can be various data types, including numbers, strings,
booleans, or even other expressions. The combination of operators and
operands forms expressions, which are then evaluated to produce a
result.
o Some of the operators shown below
Examples:
Note: * Division, ** Exponential, / Division, // floor division (the floor
division // rounds the result down to the nearest whole number )
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 12
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
2.7 Type converter functions
o Python provides several built-in functions for explicit type conversion,
also known as typecasting. Some examples int, float and str,
o These functions allow a programmer to intentionally change the data
type of a value. Common Type Conversion Functions:
1. int(): Converts a value to an integer.
It can convert floats (truncating the decimal part), numeric strings,
and booleans (True becomes 1, False becomes 0).
Example: 1
Example 2:
2. float(): Converts a value to a floating-point number.
It can convert integers, numeric strings, and booleans (True
becomes 1.0, False becomes 0.0).
Example: float(5) results in 5.0; float("2.718") results in 2.718.
3. str():Converts any data type to its string representation.
Example: str(42) results in "42"; str([1, 2, 3]) results in "[1, 2, 3]".
2.8 Order of operations
o When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.
o Python follows the standard order of operations, often remembered by
the acronym PEMDAS or BEDMAS. This dictates the sequence in which
operations are evaluated within an expression
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 13
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o Python follows the same precedence rules for its mathematical operators
that mathematics does.
o The order of operations in Python, from highest to lowest precedence, is:
1. Parentheses (): Operations within parentheses are always evaluated
first, regardless of the operators inside
Example: result = (5 + 3) * 2 # (5 + 3) is evaluated first,
then multiplied by 2. Similarly 2 * (3-1) is 4, and (1+1)**(5-
2) is 8.
2. Exponents**:Exponentiation is evaluated after parentheses.
Exponentiation has the next highest precedence,
Example: 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
3. Multiplication and both Division operators: Both 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.
1. 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.
Examples:
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 14
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
2.9 Operations on strings
o In general, you cannot perform mathematical operations on strings, even if
the strings look like numbers.The following are illegal
o Interestingly, the + operator does work with strings, but for strings, the +
operator represents concatenation, not addition.
o String concatenation and replication operation can be performed.
Concatenation is the process of joining two or more strings together and
forming one single string.
o Example :
o 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.
o Replicating the same string “n” several times is called string replication.
Use the * operator on a string to repeat the string a provided number of
times.
o The syntax for the operation is: result = ‘string’ * integer number
o Example: ‘Kvg’*3, results ‘kvgKvgKvg’
2.10 Input
o The input() function allows takes a user input. By default, it returns the
user input in the form of a string.
o The input() function waits for the user to type some text on the keyboard
and press ENTER.
Example 1:
Example 2:
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 15
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
2.11 Composition
o One of the most useful features of programming languages is their ability
to take small building blocks and compose them into larger chunks.
o We know that, the elements of a program — variables, expressions,
statements, and function calls — in isolation, without talking about how
to combine them.
o For example, consider 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 𝑨 = 𝝅𝒓𝟐
o Firstly, we’ll do the four steps one at a time:
o 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.
o If we really wanted to be tricky, we could write it all in one statement:
2.12 The modulus operator
o The modulus operator works on integers (and integer expressions) and
gives the remainder when the first number is divided by the second.
o 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.
o The modulus operator useful to check whether one number is divisible by
another, conversion and extract right most digit.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 16
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
Chapter 3: Program Flow- Iteration
3.3 Iteration:
o Iteration in Python refers to the process of repeatedly executing a block
of code for each item in a sequence or until a certain condition is met.
o It is a fundamental concept in programming for processing collections of
data or performing repetitive tasks.
3.3.1 Assignment
o Python's assignment operators are used to assign values to variables.
o The most fundamental is the simple assignment operator, =, which
assigns the value on its right to the variable on its left.
o A new assignment makes an existing variable refer to a new value.
o Example:
Program Output
o It is especially important to distinguish between an assignment
statement and equality statement.
o Because Python uses the equal sign (=) for assignment and equality
operator is ==.
o Note 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.
o 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, example
o The third line changes the value of a but does not change the value of b,
so they are no longer equal.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 17
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
3.3.2 Updating variables
o Updating variables in Python involves changing the value that a variable
refers to. This is primarily done through assignment(=) statements.
o When an assignment statement is executed, the right-hand side
expression is evaluated first. This produces a value. Then the assignment
is made, so that the variable on the left-hand side now refers to the new
value. Example
o In above program, Line 2 means get the current value of n, multiply it by
three and add one, and assign the answer to n, thus making n refer to
the value. So after executing the two lines above, n will point/refer to the
integer 16.
o If you try to get the value of a variable that has never been assigned to,
you’ll get an error:
o Before you can update a variable, you have to initialize it to some rting
value, usually with a simple assignment
o Line 3—updating a variable by adding 1 to it—is very common. It is
called an increment of the variable; subtracting 1 is called a decrement
3.3.3 The for loop revisited
o A for loop is used for iterating over a sequence.
o With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.
o In code, a for statement always consists of the following:
1. The for keyword 2. A variable name 3.The in Keyword
4. A call on the range 5. A Colon
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 18
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o 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
o Example 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
output=
o Example 2:
for friend in ["Joe", "Zoe", "Zuki", "Thandi", "Paris"]:
invite = "Hi " + friend + ". Please come to my party!"
print(invite)
Output:
Running through all the items in a list is called traversing the list, or traversal.
3.3.4 The while statement
o Python While Loop is used to execute a block of statements repeatedly
until a given condition is satisfied. When the condition becomes false, the
line immediately after the loop in the program is executed.
o In code, a while statement always consists of the following:
1. The while keyword
2. A condition (that is an expression that evaluates to True or False.
3. A colon
4. Starting on the next line, an indented block of code (called the
while clause)
o Syntax: for a while loop statement
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 19
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o Example1: consider the program
o Description of flow of execution for a while statement:
• Evaluate the condition at line 5, yielding a value which is either F or T.
• If the value is False, exit the while statement and continue execution at
the next statement (line 8 in this case).
• If the value is True, execute each of the statements in the body (lines 6
and 7) and then go back to the while statement at line 5.
o The body consists of all of the statements indented below the while
keyword.
3.3.5 The Collatz 3n + 1 sequence
o The Collatz 3n + 1 sequence, also known as the Collatz conjecture, is a
mathematical sequence defined for positive integers.
o The rules for generating the sequence are as follows:
If the current number n is even, the next number in the sequence
is n / 2.
If the current number n is odd, the next number in the sequence
is 3n + 1.
The conjecture states that this sequence will eventually reach the
number 1 for any positive integer starting value.
o This Python code captures this algorithm:
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 20
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o Notice first that the print function on line 4 has an extra argument
end=", ". This tells the print function to follow the printed string with
whatever the programmer chooses (in this case, a comma followed by a
space), instead of ending the line.
o So each time something is printed in the loop, it is printed on the same
output line, with the numbers separated by commas.
o The call to print(n, end=".\n") at line 9 after the loop terminates will then
print the final value of n followed by a period and a newline character.
o Example 2:
Output:
3.3.6 Tracing a program
o To write effective computer programs, and to build a good conceptual model
of program execution, a programmer needs to develop the ability to trace
the execution of a computer program.
o Tracing involves becoming the computer and following the flow of execution
through a sample program run, recording the state of all variables and any
output the program generates after each instruction is executed.
o Consider the Collatz 3n + 1 sequence with n=3
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 21
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
Output sequence:
3.3.9 Tables
One of the things loops are good for is generating tables. For some
operations, computers use tables of values to get an approximate answer
and then perform computations to improve the approximation.
The following program outputs a sequence of values in the left column
and 2 raised to the power of that value in the right column. Example
Output:
The string "\t" represents a tab character.
The backslash character in "\t" indicates the
beginning of an escape sequence.
Escape sequences are used to represent
invisible characters like tabs and newlines. The
sequence \n represents a newline.
An escape sequence can appear anywhere in a
string; in this example, the tab escape sequence
is the only thing in the string.
The tab character shifts the cursor to the right
until it reaches one of the tab stops.
o Because of the tab characters between the columns, the position of the
second column does not depend on the number of digits in the first
column.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 22
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
3.3.10 Two-dimensional tables
o A two-dimensional table is a table where you read the value at the
intersection of a row and a column A multiplication table is a good
example.
o Let’s say to print a multiplication table for the values from 1 to 6.
o A good way to start is to write a loop that prints the multiples of 2, all on
one line, example
o above we’ve used the range function, but made it start its sequence at 1.
As the loop executes, the value of i changes from 1 to 6.
o When all the elements of the range have been assigned to i, the loop
terminates. Each time through the loop, it displays the value of 2 * i,
followed by three spaces.
o Again, the extra end=" " argument in the print function suppresses the
newline, and uses three spaces instead.
o After the loop completes, the call to print at line 3 finishes the current
line, and starts a new line.
o The output of the program is:
3.3.11 The break statement
o 'Break' in Python is a loop control statement. It is used to control the
sequence of the loop.
o The break keyword is used to break out a for loop, or a while loop. If the
execution reaches a break statement, it immediately exits the while
loop’s clause.
o In code, a break statement simply contains the break keyword.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 23
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
3.3.14 The continue statement
o This is a control flow statement (continue keyword) is used to end the
current iteration in a for loop (or a while loop) and continues to the next
iteration. It is used inside the loop.
o When the program execution reaches a continue statement, the program
execution immediately jumps back to the start of the loop and
reevaluates the loop’s condition. Example 1
Example 2:
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 24
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
3.3.15 Paired Data
o Making a pair of things in Python is as simple as putting them into
parentheses, like this:
o Notice that the celebs list has just 3 elements, each of them pairs. Now
we print the names of those celebrities born before 1980:
o This demonstrates something we have not seen yet in the for loop:
instead of using a single loop control variable, we’ve used a pair of
variable names, (name, year), instead.
o The loop is executed three times — once for each pair in the list, and on
each iteration both the variables are assigned values from the pair of
data that is being handled.
3.3.16 Nested Loops for Nested Data
o A nested loop means a loop statement inside another loop statement. For
a nested loop, the inner loop performs all of its iterations for each
iteration of the outer loop.
o Example: If the outer loop is running from i = 1 to 5 and the inner loop is
running from a to e. Then, for each value of the outer loop variable (i),
the inner loop will run from a to e.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 25
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o Nested loops in Python are used to iterate over nested data structures,
such as lists of lists, lists of dictionaries, or nested dictionaries.
o The concept involves placing one loop inside another, where the inner
loop executes completely for each iteration of the outer loop.
o Consider a case, we have a list of students. Each student has a name
which is paired up with another list of subjects that they are enrolled for:
o Here we’ve assigned a list of five elements to the variable students. Let’s
print out each student name, and the number of subjects they are
enrolled for:
o Python agreeably responds with the following output:
o Now we’d like to ask how many students are taking CompSci. This needs
a counter, and for each student we need a second loop that tests each of
the subjects in turn:
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 26
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
Chapter 4: Functions
4.4 Functions that require arguments
o In Python, functions can be defined to require arguments, meaning that
values must be provided for these arguments when the function is
called.
o Most functions require arguments: For example, if we want to find the
absolute value of a number, we have to indicate what the number is.
Python has a built-in function for computing the absolute value.
o Example 1: functions with one argument
- In above example, the arguments to the abs function are 5 and -5.
o Example 2: 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.
o Example 3: Another built-in function that takes more than one argument
is max.
o max can be passed any number of arguments, separated by commas,
and will return the largest value passed. The arguments can be either
simple values or expressions. In the last example, 503 is returned, since
it is larger than 33, 125, and 1.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 27
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
4.5 Functions that return values
o The return statement in Python is used within a function to exit the function
and send a value back to the caller.
o Example:
def calculate_sum(a, b):
"""This function calculates the sum of two numbers."""
result = a + b
return result # Returns the calculated sum
o In Python, functions can return values to the part of the code that called
them using the return statement. This allows the function to provide a
result or data back to the main program flow for further processing,
assignment to variables, or use in other operations.
o A function that returns a value is called a fruitful function. The opposite of a
fruitful function is a void function. It is not executed for its resulting value.
o Take an example to write as a fruitful function for compound interest, the
standard formula
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 28
Python Programming(1BPLCK105B) - Module 1: Introduction, Variables, Expressions and Statements, Iterations and Functions
o 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.
o We prompted the user for the principal amount. The type of toInvest is a
string, but we need a number before we can work with it. Because it is
money, and could have decimal places, we’ve used the float type
converter function to parse the string and return a float.
o Notice how we entered the arguments for 8% interest, compounded 12
times per year, for 5 years.
Acknowledgement:
My sincere thanks to the author Peter Wentworth, Jeffrey Elkner, Allen B.
Downey and Chris Meyers- , because the above contents are prepared from
there textbook “How to think like a computer scientist: learning with
python 3”. Green Tea Press, Wellesley, Massachusetts,2020
Prepared by:
Dr. Suresha V
Professor & Principal
Dept. of Electronics and Communication Engineering.
Reach me at: suresha.vee@gmail.com
WhatsApp: +91 8310992434
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 29