0% found this document useful (0 votes)
6 views33 pages

Python Programming Basics and Debugging

The document outlines the syllabus for a Python programming course, covering topics such as the Python language features, program structure, debugging, and data types. It details the types of errors that can occur in programming, including syntax, runtime, and semantic errors, along with methods for debugging. Additionally, it introduces variables, expressions, statements, and various data types in Python, including numeric, sequence, and mapping types.

Uploaded by

kashlub2017
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)
6 views33 pages

Python Programming Basics and Debugging

The document outlines the syllabus for a Python programming course, covering topics such as the Python language features, program structure, debugging, and data types. It details the types of errors that can occur in programming, including syntax, runtime, and semantic errors, along with methods for debugging. Additionally, it introduces variables, expressions, statements, and various data types in Python, including numeric, sequence, and mapping types.

Uploaded by

kashlub2017
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

1 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Syllabus
1 The way of the Program
1.1 The Python programming language
1.2 What is a program?
1.3 What is debugging?
1.4 Syntax errors
1.5 Runtime errors
1.6 Semantic errors
1.7 Experimental debugging

2 Variables, expressions and statements


2.1 Values and data types
2.2 Variables
2.3 Variable names and keywords
2.4 Statements
2.5 Evaluating expressions
2.6 Operators and operands
2.7 Type converter functions
2.8 Order of operations
2.9 Operations on strings
2.10 Input
2.11 Composition
2.12 The modulus operator

3 Program Flow
3.1 Iteration
3.1.1 Assignment
3.1.2 Updating variables
3.1.3 The for loop revisited
3.1.4 The while statement
3.1.5 The Collatz 3n + 1 sequence
3.1.6 Tables
3.1.7 Two-dimensional tables
3.1.8 The break statement
3.1.9 The continue statement
3.1.10 Paired Data
3.1.11 Nested Loops for Nested Data

4 Functions
4.1 Functions that require arguments
4.2 Functions that return values

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


2 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Chapter 1
The way of the Program
1.1 The Python programming language
1.2 What is a program?
1.3 What is debugging?
1.4 Syntax errors
1.5 Runtime errors
1.6 Semantic errors
1.7 Experimental debugging

1.1 The Python programming language


Salient Features of Python:
Ø Readable and Simple Syntax: Python's syntax is easy to read and write, making it accessible for
beginners and experienced programmers alike.
Ø High-Level Language: Python abstracts low-level details, providing a high-level language that
simplifies programming.
Ø Interpreted Language: Python code is executed line by line by an interpreter, which means you
can interact with the code in a more dynamic way.
Ø Dynamically Typed: Python is dynamically typed, allowing you to change the data type of a
variable during runtime.
Ø Cross-Platform: Python is available on various platforms, and code can be run on different
operating systems without modification.
Ø Rich Standard Library: Python comes with a comprehensive standard library, providing ready-to-
use modules and packages.
Ø Support for Multiple Programming Paradigms: Python supports procedural, object-oriented, and
functional programming styles.
Ø Community Support: Python has a large and active user community, with extensive documentation
and third-party libraries.
Ø Integration with Other Languages: Python can be integrated with other languages (e.g., C, C++)
for performance-critical tasks.
Ø Open Source: Python is open-source, which means it's free to use and has a large ecosystem of
libraries and tools.
The engine that translates and runs Python is called the Python Interpreter: There are two ways to
use it: immediate mode and script mode.
Ø immediate mode: you type Python expressions into the Python Interpreter window, and the
interpreter immediately shows the result:

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


3 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Ø The >>> is called the Python prompt. The interpreter uses the prompt to indicate that it is
ready for instructions.
Ø We typed 2 + 2, and the interpreter evaluated our expression, and replied 4, and on the next
line it gave a new prompt, indicating that it is ready for more input.
Ø script mode: you can write a program in a file and use the interpreter to execute the contents
of the file. Such a file is called a script.
Ø When you are writing a script you need something like a text editor. A few examples of text
editors are Notepad, Notepad++.
Ø Integrated Development Environment or IDE: For Python there are programs that include
both a text editor and a way to interact with the interpreter.
Ø Example: Spyder, Thonny or IDLE, Visual Studio Code.
Ø There are also development environments that run in your browser. One example of this is
Jupyter Notebook.

1.2 What is a program?


Ø A program is a sequence of instructions that specifies how to perform a computation. The
computation might be something mathematical, such as solving a system of equations or
finding the roots of a polynomial, but it can also be a symbolic computation, such as searching
and replacing text in a document or (strangely enough) compiling a program.
Ø The details look different in different languages, but a few basic instructions appear in just
about every language:
Ø Input: Get data from the keyboard, a file, or some other device such as a sensor.
Ø Output: Display data on the screen or send data to a file or other device such as a motor.
Ø Math: Perform basic mathematical operations like addition and multiplication.
Ø Conditional execution: Check for certain conditions and execute the appropriate sequence of
statements.
Ø Repetition: Perform some action repeatedly, usually with some variation.
1.3 What is debugging?
Ø Programming is a complex process, and because it is done by human beings, it often leads to
errors.
Ø Programming errors are called bugs and the process of tracking them down and correcting
them is called debugging.
Ø Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors.
1.4 Syntax errors
Ø Python can only execute a program if the program is syntactically correct; otherwise, the
process fails and returns an error message.
Ø Syntax refers to the structure of a program and the rules about that structure.
Ø If there is a single syntax error anywhere in your program, Python will display an error
message and quit, and you will not be able to run your program.
Ø These happen when Python cannot understand the code because it violates the
grammar (rules of Python).
Ø Detected before execution.
Ø Example:
Ø print ("Hello” # Missing closing parenthesis
1.5 Runtime errors
Ø Runtime error, so called because the error does not appear until you run the program. These
errors are also called exceptions because they usually indicate that something exceptional
(and bad) has happened.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


4 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Ø • Occur while the program is running.


Ø • Even if the code is syntactically correct, it may fail during execution.
Ø Example:
Ø x = 10 / 0
Ø Error: ZeroDivisionError: division by zero
Common Runtime Errors (Exceptions):
• ZeroDivisionError → dividing by zero
• ValueError → invalid value (e.g., int("abc"))
• TypeError → operation on incompatible types (e.g., "2" + 2)
• IndexError → accessing out-of-range index in a list
• KeyError → accessing a missing dictionary key
• FileNotFoundError → opening a file that doesn’t exist
1.6 Semantic errors
The code runs without any syntax or runtime errors, but the meaning (semantics) of the code
is wrong, so the output is not what the programmer intended.
◆ Example of Semantic Error
# Program to calculate the average of 3 numbers

a, b, c = 10, 20, 30
average = a + b + c / 3 # + wrong
print("Average:", average)

Output:
Average: 40.0

What programmer intended:


Average: 20.0

The mistake is in operator precedence.


Python evaluates a + b + c / 3 as a + b + (c / 3) instead of (a + b + c) / 3.
1.7 Experimental debugging
Ø Experimental debugging is the process of testing your program with small changes or
experiments to figure out where and why it is going wrong.
Ø Instead of directly knowing the bug, you try different inputs, print statements, or code
modifications to isolate the error.
Ø It’s like doing a small “experiment” to confirm or reject a hypothesis about the bug.
o Steps in Experimental Debugging
Make a Hypothesis
Think about where the error might be.
Example: “Maybe the loop is running one extra time.”
Modify/Test the Code
Add print statements, test different inputs, or comment out suspicious parts.
Run the Program
Check if the modification supports or disproves your guess.
Refine and Repeat
Keep experimenting until you isolate the exact bug.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


5 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

o Example in Python
Suppose this program is giving wrong results:
def factorial(n):
result = 1
for i in range(1, n): # % suspecting error here
result *= i
return result

print(factorial(5)) # Expected: 120


Output:
24
Debugging Experiment:
Add print statements:
def factorial(n):
result = 1
for i in range(1, n):
print("i =", i, "result =", result) # Debug experiment
result *= i
return result
Observation:
It multiplies only up to 4, not 5.
Hypothesis confirmed → The loop should run till n, not n-1.
Fix:
for i in range(1, n+1): # & ' corrected

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


6 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

CHAPTER 2
Variables, expressions and statements
2.1 Values and data types
2.2 Variables
2.3 Variable names and keywords
2.4 Statements
2.5 Evaluating expressions
2.6 Operators and operands
2.7 Type converter functions
2.8 Order of operations
2.9 Operations on strings
2.10 Input
2.11 Composition
2.12 The modulus operator

2.1 Values and data types


Ø In Python, values are the fundamental pieces of data that programs manipulate
Ø while data types categorize these values, indicating the kind of operations that can be
performed on them and how they are stored in memory.
Common Python Data Types:
A data type defines:
• The kind of values that can be stored (e.g., numbers, text, true/false).
• The operations that can be performed on those values (e.g., addition, concatenation).
• How much memory the value takes and how it’s stored internally.
Think of it as a “blueprint” that tells the computer what the data means.

The following are the standard or built-in data types in Python:


• Numeric - int, float, complex
• Sequence Type - string, list, tuple
• Mapping Type - dict
• Boolean - bool
• Set Type - set, frozenset

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


7 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

1. Numeric Data Types in Python


Ø The numeric data type in Python represents the data that has a numeric value.
Ø A numeric value can be an integer, a floating number, or even a complex number.
Ø These values are defined as Python int, Python float and Python complex classes
in Python.
• Integers - This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an
integer value can be.
• Float - This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point.
• Complex Numbers - A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example - 2+3j

Example:
a=5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>

2. Sequence Data Types in Python


The sequence Data Type is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion.
There are several sequence data types of Python:
• String
• List
• Tuple
String Data Type
Ø In Python, a character is a string of length one. It is represented by str class.
Ø Strings in Python can be created using single quotes, double quotes or even triple
quotes.
Ø We can access individual characters of a String using index.
Example:
s = 'Welcome to the Geeks World'
print(s)

# check data type


print(type(s))
# access string with index
print(s[1])
print(s[2])
print(s[-1])

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


8 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Output
Welcome to the Geeks World
<class 'str'>
e
l
d
List Data Type:
Ø List are just like arrays, which is an ordered collection of data. It is very flexible as the
items in a list do not need to be of the same type.
Ø Lists in Python can be created by just placing the sequence inside the square brackets[].
Creating a List in Python
# Empty list
a = []

# list with int values


a = [1, 2, 3]
print(a)

# list with mixed int and string


b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Access List Items
Ø In order to access the list items refer to the index number. In Python, negative sequence
indexes represent positions from the end of the array.
Ø Instead of having to compute the offset as in List[len(List)-3], it is enough to just write
List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second-last item, etc.
Example:
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative indexing")


print(a[-1])
print(a[-3])

Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


9 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Tuple Data Type


Ø Just like a list, a tuple is also an ordered collection of Python objects.
Ø The only difference between a tuple and a list is that tuples are immutable. Tuples
cannot be modified after it is created.

Creating a Tuple in Python


Ø tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence.
Ø Tuples can contain any number of elements and of any datatype (like strings, integers,
lists, etc.).

# initiate empty tuple


tup1 = ()

tup2 = ('Geeks', 'For')


print("\nTuple with the use of String: ", tup2)

Output
Tuple with the use of String: ('Geeks', 'For')

Access Tuple Items


In order to access the tuple items refer to the index number. Use the index operator [ ] to access
an item in a tuple.
tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items


print(tup1[0])
print(tup1[-1])
print(tup1[-3])

Output
1
5
3

3. Boolean Data Type in Python


Ø Python Data type with one of the two built-in values, True or False. Boolean objects
that are equal to True are truthy (true), and those equal to False are falsy (false).
Ø However non-Boolean objects can be evaluated in a Boolean context as well and
determined to be true or false. It is denoted by the class bool.
Example:
Ø The first two lines will print the type of the boolean values True and False, which
is <class 'bool'>.
Ø The third line will cause an error, because true is not a valid keyword in Python.
Ø Python is case-sensitive, which means it distinguishes between uppercase and
lowercase letters.
print(type(True))
print(type(False))
print(type(true))

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


10 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Output:
<class ‘bool’>
<class ‘bool’>
NameError: name 'true' is not defined

4. Set Data Type in Python


Set is an unordered collection of data types that is iterable, mutable, and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
Create a Set in Python
Ø Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a ‘comma’.
Ø The type of elements in a set need not be the same, various mixed-up data type values
can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values
# initializing empty set
s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)

Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered the items have
no index. But we can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in the keyword.
set1 = set(["Geeks", "For", "Geeks"])
print(set1)

# loop through set


for i in set1:
print(i, end=" ")

# check if item exist in set


print("Geeks" in set1)

Output
{'Geeks', 'For'}
Geeks For True
5. Dictionary Data Type
Ø A dictionary is a collection of data values, used to store data values like a map, unlike
other Python Data Types that hold only a single value as an element, a Dictionary holds
a key: value pair.
Ø Key-value is provided in the dictionary to make it more optimized. Each key-value pair
in a Dictionary is separated by a colon : , whereas each key is separated by a ‘comma’.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


11 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Create a Dictionary in Python


Ø Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t
be repeated and must be immutable.
Ø The dictionary can also be created by the built-in function dict().
Note - Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
# initialize empty dictionary
d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d)

# creating dictionary using dict() constructor


d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.
Using get() method we can access the dictionary elements.
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key


print(d['name'])

# Accessing a element using get


print([Link](3))

Output
For
Geeks

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


12 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

2.2 Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example:
x= 5
y= "John"
print(x)
print(y)
Output:
5
John
Example:
x=4 # x is of type int
x=”Praveen” # x is of type str
Output:
Praveen

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).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


13 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Example:
Legal variable names:
myvar= "Akash"
my_var= "Akash"
_my_var= "Akash"
myVar= "Akash"
MYVAR= "Akash"
myvar2 = "Akash"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
Output:
Akash
Akash
Akash
Akash
Akash
Akash
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Output:
SyntaxError: invalid syntax

Keywords:
Ø Python keywords are reserved words that have predefined meanings and purposes in
the language.
Ø They cannot be used as identifiers (e.g., variable names, function names, or class
names). These keywords are case-sensitive.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


14 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

List of commonly used Python keywords as of Python 3.10:


Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal

Difference Between Variables and Keywords


Variables Keywords
Used to store data Reserved words with predefined meanings
Can create, modify and delete by the Cannot be modified and used as variable
programmer names.
Ex: x, age, name etc... Ex: for, while, if etc…
Holds values that are manipulated in the Used to define structure
program
Must follows naming rules Cannot be altered

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


15 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

2.4 Statements
Ø A statement is an instruction that the Python interpreter can execute.
Ø Python statements are the building blocks of a program and can perform actions like
assigning values, making decisions, or iterating over data.
Ø When you type a statement on the command line, Python executes it. Statements don’t
produce any result.

2.5 Evaluating expressions


An expression is a combination of values, variables, operators, and calls to functions. If you
type an expression at the Python prompt, the interpreter evaluates it and displays the result:
>>> 1 + 1
2
>>> len("hello")
5
In this example len is a built-in Python function that returns the number of characters in a string.

Types of Statements in Python


1. Expression Statements:
o These evaluate an expression and return a value.
o Example:
o x = 5 + 3 # Assignment statement with an expression
o print(x) # Expression statement
2. Assignment Statements:
o Used to assign values to variables.
o Example:
o name = "Python"
o age = 25
3. Conditional Statements:
o Used for decision-making (e.g., if, elif, else).
o Example:
o if age > 18:
o print("Adult")
o else:
o print("Minor")
4. Looping Statements:
o Used for iteration (e.g., for, while).
o Example:
o for i in range(5):
o print(i)
5. Import Statements:
o Used to include external modules or libraries.
o Example:
o import math
o print([Link](16))
6. Try-Except Statements:
o Used for exception handling.
o Example:
o try:
o result = 10 / 0

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


16 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

o except ZeroDivisionError:
o print("Cannot divide by zero!")

7. Pass Statement:
o A placeholder that does nothing; used to define empty blocks.
o Example:
o def my_function():
o pass
8. With Statement:
o Used for resource management (e.g., file handling).
o Example:
o with open("[Link]", "r") as file:
o content = [Link]()

2.6 Operators and operands


Ø In Python programming, Operators in general are used to perform operations on
values and variables.
Ø These are standard symbols used for logical and arithmetic operations. In this
article, we will look into different types of Python operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.

Arithmetic Operators in Python


Ø Python Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication and division.
Example:
# Variables
a = 15
b=4

# Addition

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


17 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)

# Division
print("Division:", a / b)

# Floor Division
print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

# Exponentiation
print("Exponentiation:", a ** b)

Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

Relational or Comparison in Python


Comparison or Relational operators compares the values.
It either returns True or False according to the condition.
Example:
a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


18 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Logical Operators in Python


Logical Operators perform Logical AND, Logical OR and Logical NOT operations. It is used
to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example:
a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

Bitwise Operators in Python


Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on
binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example:
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output:
0
14
-11
14
2
40
Assignment Operators in Python
Ø Assignment operators are used to assign values to the variables.
Ø This operator is used to assign the value of the right side of the expression to the left
side operand.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


19 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Example:
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

Output:
10
20
10
100
102400

2.7 Type converter functions


In programming, type conversion is the process of converting data of one type to another. For
example: converting int data to str.
There are two types of type conversion in Python.
• Implicit Conversion - automatic type conversion
• Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known as
implicit type conversion.
1. Type Conversion is the conversion of an object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are
converted using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower data type (integer) to
the higher data type (float) to avoid data loss.
integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


20 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Output
Value: 124.23
Data Type: <class 'float'>
Ø In the above example, two variables are created.integer_number and float_number of
int and float type respectively.
Ø Then added these two variables and stored the result in new_number.
Ø It is because Python always converts smaller data types to larger data types to avoid the
loss of data.
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type
of the objects.

Example 2: Addition of string and integer Using Explicit Conversion


num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

In the above example, created two variables. Num_string and num_integer with str and int type
values respectively.

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


21 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

2.8 Order of operations

When more than one operator appears in an expression, the order of evaluation depends on the
rules of precedence.

Python follows the same precedence rules for its mathematical operators that mathematics
does. The acronym PEMDAS is a useful way to remember the order of operations:

1. Parentheses have the highest precedence and can be used to force an expression to evaluate
in the order you want.

Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8.

You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60,
even though it doesn’t change the result.

2. Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3
and not 27.

3. Multiplication and both Division operators have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than
4, and 5-2*2 is 1, not 6.

4. Operators with the same precedence are evaluated from left-to-right.

So in the expression 6-3+2, the subtraction happens first, yielding 3. We then add 2 to get the
result 5. If the operations had been evaluated from right to left, the result would have been 6-
(3+2), which is 1. (The acronym PEDMAS could mislead you to thinking that division has
higher precedence than multiplication, and addition is done ahead of subtraction - don’t be
misled. Subtraction and addition are at the same precedence, and the left-to-right rule applies.)

Due to some historical quirk, an exception to the left-to-right left-associative rule is the
exponentiation operator **, so a useful hint is to always use parentheses to force exactly the
order you want when exponentiation is involved:

>>> 2 ** 3 ** 2 # The right-most ** operator gets done first!

512

>>> (2 ** 3) ** 2 # Use parentheses to force the order you want!

64

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


22 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

2.9 Operations on strings

In general, you cannot perform mathematical operations on strings, even if the strings look like
numbers.
The following are illegal (assuming that message has type string):
>>> message - 1 # Error
>>> "Hello" / 123 # Error
>>> message * "Hello" # Error
>>> "15" + 2 # Error
Ø The + operator does work with strings, but for strings, the + operator represents
concatenation, not addition.
Ø Concatenation means joining the two operands by linking them end-to-end.
For example:
1 fruit = "banana"
2 baked_good = " nut bread"
3 print(fruit + baked_good)
Ø The output of this program is banana nut bread. The space before the word nut is part
of the string, and is necessary to produce the space between the concatenated strings.
Ø The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is
'FunFunFun'.
Ø One of the operands has to be a string; the other has to be an integer.
Ø On one hand, this interpretation of + and * makes sense by analogy with addition and
multiplication.
Ø Just as 4*3 is equivalent to 4+4+4, we expect "Fun"*3 to be the same as
"Fun"+"Fun"+"Fun", and it is.
Ø On the other hand, there is a significant way in which string concatenation and
repetition are different from integer addition and multiplication.
2.10 Input
Ø It is a built-in function in Python for getting input from the user:
1 name = input("Please enter your name: ")
Ø The user of the program can enter the name and click OK, and when this happens the
text that has been entered is returned from the input function, and in this case assigned
to the variable name.
Ø Even if you asked the user to enter their age, you would get back a string like "17".
Ø It would be your job, as the programmer, to convert that string into a int or a float, using
the int or float converter functions we saw earlier.
2.11 Composition
Ø combine multiple behaviours into a single function
Ø For example, we know how to get the user to enter some input, we know how to convert
the string we get into a float, we know how to write a complex expression, and we know
how to print values.
Ø Let’s put these together in a small four-step program that asks the user to input a value
for the radius of a circle, and then computes the area of the circle from the formula
Area = 𝜋𝑅2
Firstly, we’ll do the four steps one at a time:
1 response = input("What is your radius? ")
2 r = float(response)
3 area = 3.14159 * r**2
4 print("The area is ", area)

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


23 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Ø 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.
Ø 1 r = float( input("What is your radius? ") )
Ø print("The area is ", 3.14159 * r**2)
Ø If we really wanted to be tricky, we could write it all in one statement:
Ø 1 print("The area is ", 3.14159* float(input("What is your radius?"))**2)
Ø Such compact code may not be most understandable for humans, but it does illustrate
how we can compose bigger chunks from our building blocks.
2.12 The modulus operator
Ø The modulus operator works on integers (and integer expressions) and gives the
remainder when the first number is divided by the second.
Ø In Python, the modulus operator is a percent sign (%).
Ø The syntax is the same as for other operators. It has the same precedence as the
multiplication operator.
>>> q = 7 // 3 # This is integer division operator
>>> print(q)
2
>>> r = 7 % 3
>>> print(r)
1
So 7 divided by 3 is 2 with a remainder of 1.
Ø The modulus operator turns out to be surprisingly useful. For example, you can check
whether one number is divisible by another—if x % y is zero, then x is divisible by y.
Ø Also, you can extract the right-most digit or digits from a number. For example, x %
10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two
digits.
Ø It is also extremely useful for doing conversions, say from seconds, to hours, minutes
and seconds.
So let’s write a program to ask the user to enter some seconds, and we’ll convert them into
hours, minutes, and remaining seconds.
1 total_secs = int(input("How many seconds, in total?"))
2 hours = total_secs // 3600
3 secs_still_remaining = total_secs % 3600
4 minutes = secs_still_remaining // 60
5 secs_finally_remaining = secs_still_remaining % 60
6 print("Hrs=", hours, " mins=", minutes,
7 "secs=", secs_finally_remaining)

Output:
How many seconds, in total?244
Hrs= 0 mins= 4 secs= 4

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


24 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

CHAPTER 3 PROGRAM FLOW


3.1 Iteration
3.1.1 Assignment
3.1.2 Updating variables
3.1.3 The for loop revisited
3.1.4 The while statement
3.1.5 The Collatz 3n + 1 sequence
3.1.6 Tables
3.1.7 Two-dimensional tables
3.1.8 The break statement
3.1.9 The continue statement
3.1.10 Paired Data
3.1.11 Nested Loops for Nested Data

3.1 Iteration
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks
without making errors is something that computers do well and people do poorly.
Repeated execution of a set of statements is called iteration.
3.1.1 Assignment
In Python, "assignment" refers to the process of binding a value (an object) to a name (a
variable). This is achieved using the assignment operator, which is the equals sign (=).
Example:
1 airtime_remaining = 15
2 print(airtime_remaining)
3 airtime_remaining = 7
4 print(airtime_remaining)
The output of this program is:
15
7
because the first time airtime_remaining is printed, its value is 15, and the second time, its
value is 7.
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:
1a=5
2 b = a # After executing this line, a and b are now equal
3 a = 3 # After executing this line, a and b are no longer equal
The third line changes the value of a but does not change the value of b, so they are no longer
equal.
so we use the tokens = for assignment, == for equality.

3.1.2 Updating variables


Ø When an assignment statement is executed, the right-hand side expression (i.e. the
expression that comes after the assignment token) 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.
Ø One of the most common forms of assignment is an update, where the new value of the
variable depends on its old value. Deduct 40 cents from my airtime balance, or add one
run to the scoreboard.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


25 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

1n=5
2n=3*n+1
Ø 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.
Before you can update a variable, you have to initialize it to some starting value, usually with
a simple assignment:
1 runs_scored = 0
2 ...
3 runs_scored = runs_scored + 1
Ø 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. This is commonly done
with the += operator.
1 runs_scored = 0
2 ...
3 runs_scored += 1
3.1.3 The for loop revisited
Recall that the for loop processes each item in a list. Each item in turn is assigned to the loop
variable — also called the iterator variable — and the body of the loop is executed
Example:
for first_year in ["Akash", "Anil", "Ashwath", "Praveen", "Akshatha"]:
print ("Hi", Students, ". Please attend the Induction Program")

Output:
Hi Akash. Please attend the Induction Program
Hi Anil. Please attend the Induction Program
Hi Ashwath. Please attend the Induction Program
Hi Praveen. Please attend the Induction Program
Hi Akshatha. Please attend the Induction Program
Ø We have also seen iteration and variable updating in the form of the accumulator
pattern.
Ø For example, to compute the sum of the first n integers,
Ø we could create a for loop using the range function to produce the numbers 1 through n.
Ø Using the accumulator pattern, we can start with a running total variable initialized to
0 and on each iteration, add the current value of the loop variable to the total.
A function to compute this sum is shown below.

def sum_to(n):
sum = 0
for num in range(1, n+1):
sum = sum + num
return sum

print(sum_to(4))

print(sum_to(1000))

Output:
10
500500

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


26 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Ø Here,the variable sum is called the accumulator. It is initialized to zero before we start
the loop. The loop variable, num will take on the values produced by the
range(1, n+1) function call. Note that this produces all the integers from 1 up to the value
of n.
Ø If we had not added 1 to n, the range would have stopped one value short
since range does not include the upper bound in the returned list.
Ø The assignment statement, sum = sum + num, updates sum each time through the loop.
Ø This accumulates the running total. Finally, we return the value of the accumulator.
3.1.4 The while statement
A while loop repeats a block of code as long as a condition is True
Here is a fragment of code that demonstrates the use of the while statement:
1 while <CONDITION>:
2 <STATEMENT>
1n=6
2
3 current_sum = 0
4i=0
5 while i <= n:
6 current_sum += i
7 i += 1
8 print(current_sum)
Ø It means, while i is less than or equal to n, continue executing the body of the loop.
Within the body, each time, increment i. When i passes n, return your accumulated sum.
Ø In other words: while <CONDITION> is True, <STATEMENT> is executed.
More formally, here is precise flow of execution for a while statement:
Ø Evaluate the condition at line 5, yielding a value which is either False or True.
Ø 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.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


27 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

3.1.5 The Collatz 3n + 1 sequence


It works like this:
1. Start with any positive integer n.
2. If n is even, divide it by 2.
3. If n is odd, multiply it by 3 and add 1.
4. Repeat until you reach 1.
Implementation:
def collatz_sequence(n):
sequence = [n] # store the sequence
while n != 1:
if n % 2 == 0: # even
n = n // 2
else: # odd
n=3*n+1
[Link](n)
return sequence
Output:
[6, 3, 10, 5, 16, 8, 4, 2, 1]
Explanation: n = 6
• Start: sequence = [6]
• 6 is even → 6 // 2 = 3 → sequence = [6, 3]
• 3 is odd → 3*3+1 = 10 → [6, 3, 10]
• 10 is even → 10 // 2 = 5 → [6, 3, 10, 5]
• 5 is odd → 3*5+1 = 16 → [6, 3, 10, 5, 16]
• 16 → 8 → 4 → 2 → 1 → [6, 3, 10, 5, 16, 8, 4, 2, 1]

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


28 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

3.1.6 Tables
Creating a table in Python involves structuring data into rows and columns for clear
representation.
Tables can be displayed in various formats, including plain text, grids or structured layouts.
Python provides multiple ways to generate tables, depending on the complexity and data size.
Example:
# Multiplication table (from 1 to 10) in Python

num = 12

# To take input from the user


# num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Output:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Ø Here, we have used the for loop along with the range() function to iterate 10 times.
Ø The arguments inside the range() function are (1, 11). Meaning, greater than or equal
to 1 and less than 11.
Ø We have displayed the multiplication table of variable num (which is 12 in our case).
You can change the value of num in the above program to test for other values.
3.1.7 Two-dimensional tables
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.
Let’s say you want to print a multiplication table for the values from 1 to 6.
A good way to start is to write a loop that prints the multiples of 2, all on one line:
1 for i in range(1, 7):
2 print(2 * i, end=" ")
3 print()
Ø Here 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.
Ø 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.
Ø Again, the extra end=" " argument in the print function suppresses the newline, and
uses three spaces instead.
Ø After the loop completes, the call to print at line 3 finishes the current line, and starts a
new line.
The output of the program is:
2 4 6 8 10 12

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


29 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

3.1.8 The break statement


Ø The break statement in Python is used to exit a loop immediately, regardless of the
loop’s condition.
Ø Once a break is executed, the loop stops running and the program continues with the
next statement after the loop.
Ø It can be used inside for or while loops, often with a conditional check.
Syntax:
Using for loop:
for item in sequence:
if condition:
break
Example:
for num in range(1, 10):
if num == 5:
break
print(num)

Output:
1
2
3
4
Ø The loop stops when num becomes 5

Using while loop:


while condition:
if condition2:
break
Example:
i=1
while i <= 10:
if i == 6:
break
print(i)
i += 1

Output:
1
2
3
4
5
Ø The loop breaks when i is 6

3.1.9 The continue statement:


Ø The continue statement in Python is a loop control statement used to skip the rest of the
code within the current iteration of a loop and move directly to the next iteration.
Ø When Python encounters a continue statement inside a for loop or a while loop:
Current iteration skipped: The execution of the remaining statements in the current
iteration of the loop is immediately terminated.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


30 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Next iteration begins: The control flow jumps back to the beginning of the loop, and the
next iteration starts.
Example in a for loop:
for i in range(5):
if i == 2:
continue # Skip printing for i = 2
print(i)
Output:
0
1
3
4
Ø In this example, when i is 2, the continue statement is executed, and the print(i)
statement for that iteration is skipped. The loop then proceeds to the next value of i
Example in a while loop:
count = 0
while count < 5:
count += 1
if count == 3:
continue # Skip printing for count = 3
print(count)
Output:
1
2
4
5
Ø Here, when count becomes 3, the continue statement is executed, and the print(count)
statement for that iteration is skipped. The while loop then re-evaluates its condition
and proceeds.
3.1.10 Paired Data:
Ø With paired data, every observation in one group has a matching observation in the
other group.
Ø Making a pair of things in Python is as simple as putting them into parentheses, like
this:
1 year_born = ("Harish", 1981)
We can put many pairs into a list of pairs:
1 celebs = [("Ravi", 1963), ("Akash", 1937),
2 ("Virat", 1994)]
Ø Here is a quick sample of things we can do with structured data like this. First, print
all the celebs:
1 print(celebs)
2 print(len(celebs))
[("Ravi", 1963), ("Akash", 1937), ("Virat", 1994)]
Notice that the celebs list has just 3 elements, each of them pairs.
Now we print the names of those celebrities born before 1980:
1 for name, year in celebs:
2 if year < 1980:
3 print(name)
Ravi
Akash

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


31 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

Here, we’ve used a pair of variable names, (name, year).


3.1.11 Nested Loops for Nested Data
Nested loops in Python are used to iterate over nested data structures, such as lists of lists,
dictionaries containing lists, or other multi-dimensional data.
How Nested Loops Work:
Ø A nested loop consists of an "outer" loop and one or more "inner" loops.
Ø For every single iteration of the outer loop, the inner loop completes all of its iterations.
Ø Once the inner loop finishes, the outer loop proceeds to its next iteration, and the inner
loop resets and begins iterating again.
Ø This process continues until both the outer and inner loops have completed their cycles.
Example:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Example 2:
people = [
{"name": "Alice", "scores": [85, 90, 95]},
{"name": "Bob", "scores": [70, 80, 90]}
]
for person in people:
print(f"{person['name']} scores:")
for score in person["scores"]:
print(" -", score)
Output:
Alice scores:
- 85
- 90
- 95
Bob scores:
- 70
- 80
- 90

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


32 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

CHAPTER 4 FUNCTIONS
4.4 Functions with Arguments
4.5 Functions return values
Ø In Python, a function is a named, reusable block of code designed to perform a specific
task.
Ø Functions promote code organization, reusability, and modularity, making programs
easier to understand, debug, and maintain.
Defining a Function:
Functions are defined using the def keyword, followed by the function name, parentheses
(which may contain parameters), and a colon.
def my_function(parameter1, parameter2):
# Function body - code to be executed when the function is called
result = parameter1 + parameter2
return result
Calling a Function:
To execute a function, you call it by its name followed by parentheses, optionally passing
arguments if the function expects parameters.
output = my_function(5, 3) # Calling the function with arguments 5 and 3
print(output) # Output: 8
4.4 Functions with arguments
Most functions require arguments: the arguments provide for generalization.
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:
>>> abs(5)
5
>>> abs(-5)
5
In this example, the arguments to the abs function are 5 and -5.
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.
>>> pow(2, 3)
8
>>> pow(7, 4)

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE


33 PYTHON PROGRAMMIMG (1BPCL105B/205B) MODULE 1

2401
Another built-in function that takes more than one argument is max.
>>> max(7, 11)
11
>>> max(4, 1, 17, 2, 12)
17
>>> max(3 * 11, 5**3, 512 - 9, 1024**0)
503
Ø 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.
4.5 Functions that return values
Ø In Python, a function with a return statement is used to send a value or values back to
the part of the code that called the function.
Ø This allows the function to produce a result that can then be used in other parts of your
program.
Example:
def add_numbers(a, b):
"""This function takes two numbers and returns their sum."""
sum_result = a + b
return sum_result

def get_person_details(name, age):


"""This function returns a person's name and age as a tuple."""
return name, age

# Calling the functions and using their return values


result = add_numbers(5, 3)
print(f"The sum is: {result}")

person_name, person_age = get_person_details("Alice", 30)


print(f"{person_name} is {person_age} years old.")

Output:
The sum is: 8
Alice is 30 years old.

Dr. Lubna Taranum, Dept of AIML, KNSIT B’LORE

You might also like