0% found this document useful (0 votes)
16 views11 pages

What Is Debugging?

Uploaded by

abdulrihan8905
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)
16 views11 pages

What Is Debugging?

Uploaded by

abdulrihan8905
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

Python Programming (1BPLC105B/205B)

What is a program?
A program is a set of instructions written in a programming language that tells a computer what to do.
For example, a program can add numbers, display text, or control a robot.
(or)
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.

What is debugging?
Debugging is the process of finding and fixing errors (bugs) in a program. Bugs prevent programs from
running correctly.
(or)
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. It is
useful to distinguish between them in order to track them down more quickly.

1. Syntax errors:

The errors which occur because of invalid syntax are called syntax errors.
(or)
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.

Example: 1
print ("Hello" # Missing closing parenthesis
The program won’t run at all until corrected.

Example: 2
x=10
if x==10 print("Hello")
SyntaxError: invalid syntax
Note:
Programmer is responsible to correct these syntax errors. Once all syntax errors are corrected then
only program execution will be started.

2. Runtime errors:

Errors that occur when the program is running.


(or)
The second type of error is a 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.
Example:1
x = 10 / 0 # Division by zero error

Murthy S L , PDIT,Hosapete Page 2


Python Programming (1BPLC105B/205B)
Steps in Experimental Debugging

1. Form a Hypothesis
o Guess what might be wrong in the program.
Example: ―Maybe the loop runs one time too many.‖

2. Modify the Code


o Add print() statements or temporarily change parts of the program to test your idea.
3. Run and Observe
o Execute the program and check if the behavior matches your expectation.
4. Refine and Repeat
o If the hypothesis is wrong, form a new one and try again until the bug is found.

Murthy S L , PDIT,Hosapete Page 4


Python Programming (1BPLC105B/205B)
Strings in Python can be enclosed in either single quotes (') or double quotes ("), or three of each (''' or
""")

>>> type('This is a string.')

<class 'str'>

>>> type("And so is this.")

<class 'str'>

>>> type("""and this.""")

<class 'str'>

>>> type('''and even this...''')

<class 'str'>

>>> 42000

42000

Variables:

What is a Variable?

A variable is like a labeled box in your computer’s memory where you can store a value.
(or)
One of the most powerful features of a programming language is the ability to manipulate variables. A
variable is a name that refers to a value.
The assignment statement gives a value to a variable:

Ex:

>>> message = "What's up, Doc?"

>>> n = 17

>>> pi = 3.14159

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. Basically, an assignment is an order, and the equals operator can be read as a question mark. This
is why you will get an error if you enter:

>>> 17 = n

File "<interactive input>", line 1

SyntaxError: can't assign to literal

Tip: When reading or writing code, say to yourself ―n is assigned 17‖ or ―n gets the value 17‖. Don’t

say ―n equals 17‖.

>>> message

Murthy S L , PDIT,Hosapete Page 6


Python Programming (1BPLC105B/205B)
Keywords:
It turns out that class is one of the Python keywords. Keywords define the language’s syntax rules and structure, and they
cannot be used as variable names.

Python has thirty-something keywords (and every now and again improvements to Python introduce or eliminate one or two):

and as assert break class continue


def del elif else except exec
finally for from global if import
in is lambda nonlocal not or
pass raise return try while with
yield True False None

Statements:
A statement is an instruction that the Python interpreter can execute. We have only seen the assignment
statement so far. Some other kinds of statements that we’ll see shortly are while statements, for
statements, if statements, and import statements.

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:

Ex:

>>> 1 + 1

>>> len("hello")

In this example len is a built-in Python function that returns the number of characters in a string.
We’ve previously seen the print and the type functions, so this is our third example of a function!

The evaluation of an expression produces a value, which is why expressions can appear on the right
hand side of assignment statements. A value all by itself is a simple expression, and so is a variable.

>>> 17

17

>>> y = 3.14

>>> x = len("hello")
>>> x
5
>>> y
3.14

Murthy S L , PDIT,Hosapete Page 8


Python Programming (1BPLC105B/205B)
This last case doesn’t look like a number — what do we expect?
Traceback (most recent call last):

File "<interactive input>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '23 bottles'

The type converter floatcan turn an integer, a float, or a syntactically legal string into a float:
>>> float(17)
17.0

>>> float("123.45")
123.45

The type converter strturns its argument into a string:


>>> str(17)
'17'

>>> str(123.45)
'123.45'

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 PEM- DAS 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. (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.)

Murthy S L , PDIT,Hosapete Page 10


Python Programming (1BPLC105B/205B)

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 print("The


4
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.

r = float( input("What is your radius? ") )


1

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.

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 % yis zero, then xis divisible by y.
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.

Murthy S L , PDIT,Hosapete Page 12


Python Programming (1BPLC105B/205B)
Chapter 3: 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. Because iteration is so common,
Python provides several language features to make it easier. We’ve already seen the for statement.
This is the form of iteration you’ll likely be using most often. But here we’re going to look at the
while statement — another way to have your program do iteration, useful in slightly different
circumstances.
Assignment:
As we have mentioned previously, 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 (and stop referring to the old
value).
airtime_remaining = 15
1
print(airtime_remaining)
2

3
airtime_remaining = 7
print(airtime_remaining)
4

The output of this program is:

15

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.

1 n = 5

2 n = 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, nwill point/refer to the integer 16.

If you try to get the value of a variable that has never been assigned to, you’ll get an error:

>>> w = x + 1

Traceback (most recent call last):

File "<interactive input>", line 1,


in NameError: name 'x' is not defined

The for loop:

Murthy S L , PDIT,Hosapete Page 14


Python Programming (1BPLC105B/205B)
The while statement:

The while loop starts with the while keyword and ends with a colon. With a while statement, the first
thing that happens is that the Boolean expression is evaluated before the statements in the while loop block is
executed. If the Boolean expression evaluates to False, then the statements in the while loop block are never
executed. If the Boolean expression evaluates to True, then the while loop block is executed. After each
iteration of the loop block, the Boolean expression is again checked, and if it is True, the loop is iterated
again.

Each repetition of the loop block is called an iteration of the loop. This process continues until the Boolean
expression evaluates to False and at this point the while statement exits. Execution then continues with the
first statement after the while loop

Example:

i=0
while i < 5:
print("Current value of i is ",i)
i=i+1

Output :
Current value of i is 0
Current value of i is 1
Current value of i is 2
Current value of i is 3
Current value of i is 4

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.

Example :
n=10
while n != 1:
print(n, end=",")
if n % 2 == 0: # n is even
n = n // 2
else: # n is odd
n=n*3+1
print(n, end=".\n")

Murthy S L , PDIT,Hosapete Page 16


Python Programming (1BPLC105B/205B)

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:
for i in [12, 16, 17, 24, 29]:
1
2 if i % 2 == 1: # If the number is odd
3 break # ... immediately exit the loop
4 print(i)
5 print("done")

This prints:

12

16

The continue statement:


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:
1 for i in [12, 16, 17, 24, 29, 30]:
2
if i % 2 == 1: # If the number is odd
3

4
continue # Don't process it

5 print(i)
print("done")

This prints:
12

16

24

Paired Data
We’ve already seen lists of names and lists of numbers in Python. We’re going to peek ahead in
the textbook a little, and show a more advanced way of representing our data. Making a pair of
things in Python is as simple as putting them into parentheses, like this:
1 year_born = ("Paris Hilton", 1981)

We can put many pairs into a list of pairs:


1 celebs = [("Brad Pitt", 1963), ("Jack Nicholson", 1937),
2
("Justin Bieber", 1994)]

Murthy S L , PDIT,Hosapete Page 18


Python Programming (1BPLC105B/205B)
Chapter 4: Functions

In Python, 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:

def <NAME>( <PARAMETERS> ):

<STATEMENTS>

We can make up any names we want for the functions we create, except that we can’t use a name
that is a Python keyword, and the names must follow the rules for legal identifiers.
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

>>> abs(5)
5

>>> abs(-5)
5

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:
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)

>>> 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 can be passed any number of arguments, separated by commas, and will return the largest

Murthy S L , PDIT,Hosapete Page 20


Python Programming (1BPLC105B/205B)
we’ve used the float type converter function to parse the string and return a float.
• Notice how we entered the arguments for 8% interest, compounded 12 times per year, for 5
years.
• When we run this, we get the output
At the end of the period you’ll have 14898.457083

This is a bit messy with all these decimal places, but remember that Python doesn’t
understand that we’re working with money: it just does the calculation to the best of its
ability, without rounding. Later we’ll see how to format the string that is printed in such a
way that it does get nicely rounded to two decimal places before printing.
• The line toInvest = float(input("How much do you want to invest?")) also shows yet another
example of composition — we can call a function like float, and its arguments can be the
results of other function calls (like input) that we’ve called along the way.
Notice something else very important here. The name of the variable we pass as an argument —
toInvest — has nothing to do with the name of the parameter — p. It is as if p = toInvest is executed
when final_amount is called. It doesn’t matter what the value was named in the caller, in final
amountits name is p.

Murthy S L , PDIT,Hosapete Page 22

You might also like