Module-1
Module-1:
The way of the program: The Python programming language, what is a program? What is debugging? Syntax
errors, Runtime errors, Semantic errors, Experimental debugging.
Variables, Expressions and Statements: Values and data types, Variables, Variable names and keywords,
Statements, Evaluating expressions, Operators and operands, Type converter functions, Order of operations,
Operations on strings, Input, Composition, The modulus operator.
Iteration: Assignment, Updating variables, the for loop, the while statement, The Collatz 3n + 1 sequence, tables,
two-dimensional tables, break statement, continue statement, paired data, Nested Loops for Nested Data.
Functions: Functions with arguments and return values.
MODULE-1
Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution
clearly and accurately.
The Python programming language
Python is an example of a high-level language; other high-level languages you might have heard of are C++, PHP,
Pascal, C#, and Java.
As you might infer from the name high-level language, there are also low-level languages, sometimes referred to
as machine languages or assembly languages. Loosely speaking, computers can only execute programs written in
lowlevel languages. Thus, programs written in a high-level language have to be translated into something more
suitable before they can run.
Advantage of high-level languages:
● It is much easier to program in a high-level language.
● It takes less time to write, they are shorter and easier to read, and they are more likely to be correct.
● High-level languages are portable, meaning that they can run on different kinds of computers with few or
no modifications.
Python Interpreter:The engine that translates and runs Python.
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.
[Link] CSE 1 Prepared by : Ashwitha A Shetty
Module-1
The >>> is called the Python prompt. The interpreter uses the prompt to indicate that it is ready for instructio ns.
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.
Working directly in the interpreter is convenient for testing short bits of code because you get immediate feedback
Script mode:One 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. Scripts have the advantage that they can be saved to disk, printed, and so on.
When you are writing a script you need something like a text editor. A few examples of text editors are Notepad,
Notepad++, vim, emacs and sublime.
For Python (and many other programming languages) there are programs that include both a text editor and a way
to interact with the interpreter. We call these development environments (sometimes Integrated Developme nt
Environment or IDE). For Python these can include (among many others) Spyder, Thonny or IDLE. There are
also development environments that run in your browser. One example of this is Jupyter Notebook.
What is a program?
A program is a sequence of instructions that specifies how to perform a computation.
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.
What is debugging?
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.
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.
[Link] CSE 2 Prepared by : Ashwitha A Shetty
Module-1
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.
Runtime errors
This 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.
Runtime errors are rare in simple programs.
Semantic errors
If there is a semantic error in your program, it will run successfully, in the sense that the computer will not generate
any error messages, but it will not do the right thing. It will do something else. Identifying semantic errors can be
tricky because it requires you to work backward by looking at the output of the program and trying to figure out
what it is doing.
Experimental debugging
It is the systematic process of identifying, analyzing, and resolving errors or "bugs" within Python code to ensure
the program functions correctly and as [Link] is the process of gradually debugging a program
until it does what you want. The idea is that you should start with a program that does something and make small
modifications, debugging them as you go, so that you always have a working program.
Variables, expressions and statements
Values and data types
A value is one of the fundamental things — like a letter or a number ex: “hello world!”,4,2+2
These values are classified into different classes, or data types:
Integers:It is a fundamental numeric data type representing whole numbers without any fractional component.
They can be positive, negative, or [Link]: 4 is an integer,
Strings:it is an immutable sequence of Unicode characters used to represent text. Strings are a fundamental data
type for handling textual information. ex:"Hello, World!"
If you are not sure what class a value falls into, Python has a function called type which can tell you
[Link] CSE 3 Prepared by : Ashwitha A Shetty
Module-1
Strings belong to the class str and integers belong to the class int. Less obviously, numbers with a decimal point
belong to a class called float, because these numbers are represented in a format called floating-point.
Double quoted strings can contain single quotes inside [Link] quoted strings can have double quotes inside
[Link] enclosed with three occurrences of either quote symbol are called triple quoted strings.
Triple quoted strings can even span multiple lines
Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to surround your
strings: once it has parsed the text of your program or command, the way it stores the value is identical in all
cases, and the surrounding quotes are not part of the value. But when the interpreter wants to display a string, it
has to decide which quotes to use to make it look like a string.
When you type a large integer, you might be tempted to use commas between groups of three digits, as in 42,000.
The same goes for entering Dutch-style floating point numbers using a comma instead of a decimal dot. This is
not a legal integer in Python, but it does mean something else, which is legal:
[Link] CSE 4 Prepared by : Ashwitha A Shetty
Module-1
Variables
A variable is a name that refers to a value. The assignment statement gives a value to a variable:
This example makes three assignments. The first assigns the string value "What's up, Doc?" to a variable named
message. The second gives the integer 17 to n, and the third assigns the floating-point number 3.14159 to a
variable called pi. The assignment token, =, should not be confused with equals, which uses the token ==. The
assignment statement binds a name, on the left-hand side of the operator, to a value, on the right-hand side.
A common way to represent variables on paper is to write the name with an arrow pointing to the variable’s value.
This kind of figure is called a state snapshot because it shows what state each of the variables is in at a particular
instant in [Link] diagram shows the result of executing the assignment statements:
If you ask the interpreter to evaluate a variable, it will produce the value that is currently linked to the variable:
Variable names and keywords
Variables
Variable names can be arbitrarily long.
[Link] CSE 5 Prepared by : Ashwitha A Shetty
Module-1
Rules for variable names
● They can contain both letters and digits, but they have to begin with a letter or an underscore.
● It is legal to use uppercase [Link]: Bruce and bruce are different variables.
● The underscore character ( _) can appear in a name. It is often used in names with multiple words, such
as my_name or price_of_tea_in_china. There are some situations in which names beginning with an
underscore have special meaning, so a safe rule for beginners is to start all names with a letter.
If you give a variable an illegal name, you get a syntax error:
76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an ille ga l
character, the dollar sign. But what’s wrong with class?
Keywords
Keywords define the language’s syntax rules and structure, and they cannot be used as variable names. Python
has thirty plus keywords.
List of some important keywords are as follows:
Statements
A statement is an instruction that the Python interpreter can execute.
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:
[Link] CSE 6 Prepared by : Ashwitha A Shetty
Module-1
In this example len is a built-in Python function that returns the number of characters in a [Link] evaluatio n
of an expression produces a value, which is why expressions can appear on the right hand side of assignme nt
statements.
>>> 17
17
>>> y = 3.14
>>> x = len("hello")
>>> x
5
>>> y
3.14
Operators and operands
Operators are special tokens that represent computations like addition, multiplication and division. The values the
operator uses are called operands. The following are all legal Python expressions:
Example:
20+32
Hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
The tokens +, -, and *, and the use of parenthesis for grouping, mean in Python what they mean in mathematics.
The asterisk (*) is the token for multiplication, and ** is the token for exponentiation.
When a variable name appears in the place of an operand, it is replaced with its value before the operation is
performed. Addition, subtraction, multiplication, and exponentiation all do what you expect. Example: so let us
convert 645 minutes into hours:
[Link] CSE 7 Prepared by : Ashwitha A Shetty
Module-1
In Python 3, the division operator always yields a floating point result. What we might have wanted to know was
how many whole hours there are, and how many minutes remain. Python gives us two different flavors of the
division operator. The second, called floor division uses the token //. Its result is always a whole number — and
if it has to adjust the number it always moves it to the left on the number line. So 6 // 4 yields 1, but -6 // 4 yields
-2
Type converter functions
The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it
discards the decimal portion of the number — a process we call truncation towards zero on the number line.
This last case doesn’t look like a number.
The type converter float can turn an integer, a float, or a syntactically legal string into a float:
[Link] CSE 8 Prepared by : Ashwitha A Shetty
Module-1
The type converter str turns its argument into a string:
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. 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.
Operations on strings
One cannot perform mathematical operations on strings, even if the strings look like numbers. The following are
illegal
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:
[Link] CSE 9 Prepared by : Ashwitha A Shetty
Module-1
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.
Input
There is a built-in function in Python for getting input from the user
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.
Composition
One of the most useful features of programming languages is their ability to take small building blocks and
compose them into larger chunks.
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:
● 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
● If we really wanted to be tricky, we could write it all in one statement:
● Such compact code may not be most understandable for humans, but it does illus trate how we can
compose bigger chunks from our building blocks.
The modulus operator
[Link] CSE 10 Prepared by : Ashwitha A Shetty
Module-1
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.
So 7 divided by 3 is 2 with a remainder of 1.
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.
Iteration
Repeated execution of a set of statements is called iteration.
Assignment
The = operator assigns the value of the expression on its right-hand side to the variable on its left-hand side.
Example:
x = 10 # Assigns the value 10 to the variable x
name = "Alice" # Assigns the string "Alice" to the variable name
It is legal to make more than one assignment to the same variable. A new assignment makes an existing variable
refer to a new value.
[Link] CSE 11 Prepared by : Ashwitha A Shetty
Module-1
because the first time airtime_remaining is printed, its value is 15, and the second time, its value is 7.
= = (Equality Operator)
This operator is used to compare the values of two operands. It checks if the values on both sides of the operator
are equal, returning True if they are and False otherwise.
Example1:
a=5
b=5
print(a == b) # Output: True
Example2:
c = 10
d = 20
print(c == d) # Output: False
Updating variables:
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 [Link] of
the most common forms of assignment is an update.
Examples:
n=5
n=3*n+1
If you try to get the value of a variable that has never been assigned to, you’ll get an error:
[Link] CSE 12 Prepared by : Ashwitha A Shetty
Module-1
Before you can update a variable, you have to initialize it to some starting value, usually with a simple assignme nt:
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. Sometimes programmers also talk about bumping a variable, which means
the same as incrementing it by 1. This is commonly done with the += operator.
The for loop
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.
Running through all the items in a list is called traversing the list, or traversal.
The while statement
The general syntax for while statement is as follows:
[Link] CSE 13 Prepared by : Ashwitha A Shetty
Module-1
Here is a fragment of code that demonstrates the use of the while statement:
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.
The body consists of all of the statements indented below the while keyword. Notice that if the loop condition is
False the first time we get loop, the statements in the body of the loop are never executed.
The body of the loop should change the value of one or more variables so that eventually the condition becomes
false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.
The Collatz 3n + 1 sequence
The “computational rule” for creating the sequence is to start from some given n, and to generate the next term
of the sequence from n, either by halving n, (whenever n is even), or else by multiplying it by three and adding 1.
The sequence terminates when n reaches 1.
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
[Link] CSE 14 Prepared by : Ashwitha A Shetty
Module-1
ending the line. So each time something is printed in the loop, it is printed on the same output line, with the
numbers separated by commas.
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. (You’ll cover the \n (newline character) later). The condition for continuing with
this loop is n != 1, so the loop will continue running until it reaches its termination condition, (i.e. n == 1). Each
time through the loop, the program outputs the value of n and then checks whether it is even or odd. If it is even,
the value of n is divided by 2 using integer division. If it is odd, the value is replaced by n * 3 + 1.
Tracing a program
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. 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.
Counting digits
The following snippet counts the number of decimal digits in a positive integer:
This snippet demonstrates an important pattern of computation called a counter. The variable count is initialized
to 0 and then incremented each time the loop body is executed. When the loop exits, count contains the result —
the total number of times the loop body was executed, which is the same as the number of digits.
If we wanted to only count digits that are either 0 or 5, adding a conditional before incrementing the counter will
do the trick:
[Link] CSE 15 Prepared by : Ashwitha A Shetty
Module-1
Tables
One of the things loops are good for is generating [Link] following program outputs a sequence of values in
the left column and 2 raised to the power of that value in the right column:
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.
As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where
the next character will go. After a print function, the cursor normally goes to the beginning of the next line. The
tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns
of text line up, as in the output of the previous program.
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.
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.
[Link] CSE 16 Prepared by : Ashwitha A Shetty
Module-1
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:
The break statement
The break statement is used to immediately leave the body of its loop. The next statement to be executed is the
first one after the body:
The pre-test loop —
standard loop behaviour for and while loops do their tests at the start, before executing any part of the body.
They’re called pre-test loops, because the test happens before (pre) the body.
The continue statement
[Link] CSE 17 Prepared by : Ashwitha A Shetty
Module-1
This is a control flow statement that causes the program to immediately skip the processing of the rest of the body
of the loop, for the current iteration. But the loop still carries on running for its remaining iterations:
Paired Data
Making a pair of things in Python is as simple as putting them into parentheses, like this:
Notice that the celebs list has just 3 elements, each of them pairs. Now we print the names of those celebrities
born before 1980:
[Link] CSE 18 Prepared by : Ashwitha A Shetty
Module-1
Nested Loops for Nested Data
In this 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:
Program 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:
[Link] CSE 19 Prepared by : Ashwitha A Shetty
Module-1
The above code can be simplified as follows:
Functions
A function is a named sequence of statements that belong together. Their primary purpose is to help us organize
programs into chunks that match how we think about the problem. The syntax for a function definition is:
There can be any number of statements inside the function, but they have to be indented from the def. In the
examples in this book, we will use the standard indentation of four spaces. Function definitions are the second of
several compound statements we will see, all of which have the same pattern:
1. A header line which begins with a keyword and ends with a colon.
2. A body consisting of one or more Python statements, each indented the same amount — the Python style guide
recommends 4 spaces — from the header line.
Functions that 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:
[Link] CSE 20 Prepared by : Ashwitha A Shetty
Module-1
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.
Another built- in function that takes more than one argument is max.
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.
Functions that return values
Calling each of these functions generates a value, which we usually assign to a variable or use as part of an
expression.
[Link] CSE 21 Prepared by : Ashwitha A Shetty