Python Programming Basics and Debugging
Python Programming Basics and Debugging
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
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
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
Ø 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.
a, b, c = 10, 20, 30
average = a + b + c / 3 # + wrong
print("Average:", average)
Output:
Average: 40.0
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
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
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'>
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 = []
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])
Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Output
Tuple with the use of String: ('Geeks', 'For')
Output
1
5
3
Output:
<class ‘bool’>
<class ‘bool’>
NameError: name 'true' is not defined
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
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)
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’.
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'}
Output
For
Geeks
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
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.
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.
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]()
# Addition
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
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
Output
False
True
False
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.
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
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.
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
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.
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.
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.
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:
512
64
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)
Ø 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
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.
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
Ø 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.
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
Output:
1
2
3
4
Ø The loop stops when num becomes 5
Output:
1
2
3
4
5
Ø The loop breaks when i is 6
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
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)
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
Output:
The sum is: 8
Alice is 30 years old.