0% found this document useful (0 votes)
4 views43 pages

6 Whileloop Errors Slides

This document covers the syntax and functionality of while loops in programming, including examples of their use and potential pitfalls such as infinite loops. It also discusses different types of errors encountered in programming, including syntax errors, runtime errors, and logical errors, along with strategies for debugging and raising exceptions. Additionally, the document introduces the concept of doctests for automatically testing functions in Python.

Uploaded by

Adrit Panda
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)
4 views43 pages

6 Whileloop Errors Slides

This document covers the syntax and functionality of while loops in programming, including examples of their use and potential pitfalls such as infinite loops. It also discusses different types of errors encountered in programming, including syntax errors, runtime errors, and logical errors, along with strategies for debugging and raising exceptions. Additionally, the document introduces the concept of doctests for automatically testing functions in Python.

Uploaded by

Adrit Panda
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

COMP 208

Lecture 6

while loop,
errors
Instructors:
Chad Zammar & Mohammadreza Eskandari
Winter 2026
© slides by Giulia Alberini, Jonathan Campbell, Michael Langer
while loop syntax

while condition:
# some code

The block of code is repeatedly executed as long as the


condition evaluates to True.

2
Example

n=3

while n > 0:

print('Value of n is:', n)

n -= 1
Condition Loop body
(boolean expression) (executed repeatedly as long
as the condition is True)

n=3

while n > 0:

print('Value of n is:', n)

n -= 1

Inside loop body, some code must affect the


condition such that the condition becomes
False when we want the loop to end.
Iteration

An iteration is a single execution of the instructions in the


body of the loop.

x=0
while x < 4:
print("Write this again")
x += 1

How many iterations does this loop have ? Answer: 4.

The purpose of the variable x is to act as the loop counter. It


counts how many times the loop has run.

5
if statements vs. while loops
if statements while loops

• The condition is checked • The condition is checked


once, before executing once per iteration of the
the block of code (body). loop, before executing
the block of code (body).

• The block of code is • The block of code is


executed at most once, executed repeatedly,
if the condition evaluates as long as the condition
to True. evaluates to True.

6
Example
What does the following code do?

i=0
while i < 100:
if i % 5 == 0:
print(i)
i += 1

It prints out multiples of 5 from 0 up to (but not including) 100.

7
Example
What does the following code do?

x=0
while x < 4:
print(x)

It prints infinitely many zeros.

8
Infinite loops

The previous code creates an infinite loop.

The block of code will get executed forever since the value of
x is never changed, and so the condition will never evaluate
to False.

Be careful when writing while loops. Make sure that it will


eventually terminate.

9
Infinite loops
Apple campus (1 of 2) in Cupertino, CA

10
How many iterations?

x=4
while x > 4:
print(x)
x += 1

# of iterations
0

11
How many iterations?

x=6
while x > 4:
print(x)
x -= 1

# of iterations
2

12
How many iterations?

x=6
while x > 4:
print(x)
x += 1

# of iterations
infinite!

13
How many iterations?

x=3
while x < 11:
print(x)
x += 2

# of iterations
4

14
How many iterations?

x=3
while x != 10:
print(x)
x += 2

# of iterations
infinite!

15
How to avoid printing multiple lines?

i = 15
while i < 100:
print(i)
i = i+5

Outputs

15
20
25 Printing across many lines is
sometimes inconvenient.
30
etc

16
print() and Keyword Argument end

By default, print adds the newline character ("\n"). That’s why


successive print statements print on successive lines.

We can avoid this by using the (optional) keyword argument end.

i = 15
while i < 100:
print(i, end = ' ')
i = i+5

Output:

15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95

17
print() and Keyword Argument sep

print has another commonly used keyword argument,

Recall by default, print adds a space between arguments.

print("Let", "it", "be" )


print(1, 2.0, 3)

Let it be
1 2.0 3

We can separate the arguments with any string we like using the keyword
argument sep.

print("Let", "it", "be" , sep = "#")


print(1, 2.0, 3 , sep = "__")

Let#it#be
1__2.0__3
18
Examples

print("He has", 8, "cats", sep='_', end = "***")


print("and", 2 + 3 ,"dogs", sep='--', end = "@@")
i=5
print('Yikes!')

Output:

He has_8_cats***and--5--dogs@@Yikes!

19
Errors
Bugs / Debugging

"Bug" is a commonly used term in programming. It refers to


an error.

Debugging refers to the process of removing bugs or errors


from a program.

21
The first “computer bug”

On September 9, 1947, at around


3:30 p.m. EST, a Mark II computer
in the Harvard Computation
Laboratory started to malfunction.

Operators at the lab traced the


error to a moth trapped inside the
computer.

More info here: [Link]


Image from [Link]

22
Bug types

• Syntax errors

• Runtime errors

• Logical errors

23
Syntax errors

When a program is translated from a high level language to a


lower level language (recall lecture 0), there is a parsing phase
that checks that the program satisfies the strict grammar rules of
its language.

If this check fails, then the error is called a syntax error. e.g.

>>> x = 5 8
File "<stdin>", line 1
x=5 8
^
SyntaxError: invalid syntax

24
Another Example of Syntax Error

x = input("Enter your favorite number")


if x > 1000000
print("Wow, that’s a big number!")

This program contains a syntax error (missing colon). If we try to run


the code, nothing will execute (even though the error is on line 2).

Traceback (most recent call last):


File "[Link]", line 2
if x > 100000000
^
SyntaxError: invalid syntax

25
Runtime errors
(also known as exceptions)

A program will only run when there are no syntax errors.

Runtime errors or exceptions are the errors that occur


while a program is running/executing.

They cause the program to stop before it is done.

26
Code execution and errors

Python interpreter

Python Parsing Runtime


source Python validates Python executes
code the code's syntax the code

Syntax error(s) Runtime error


(program does (error during
not execute) execution)

27
Examples - Runtime Errors

print( int("2.4") )

This code raises a ValueError.

x = input("Enter your favourite number")


if x > 10000000:
print("Wow, that’s a big number !")

This code raises a TypeError (comparing string to int).

28
Examples - Runtime Errors

print( y ) # if y has not been assigned a value

This code raises a NameError.

You might think this should be a syntax error because the Python
interpreter should be able to see it is an error without running the
program. The reason it is not a syntax error is that it obeys the
Python language grammar rules.

z=0
print( 5/z )

This code raises a ZeroDivisionError

29
Error traceback

When a runtime error (exception) occurs, Python prints a


traceback which contains useful information for debugging
your program. This info includes error type, message and
line number where the error occurred.

See example on next slide.

30
Example: error traceback

file [Link]
Traceback (in order of calls):
1 def g(): File "[Link]", line 7, in <module>
2 return 5 / 0 f()
3 File "[Link]", line 5, in f
4 def f(): return g()
5 return g() File "[Link]", line 2, in g
6 return 5 / 0
7 f() ZeroDivisionError: division by zero

The traceback shows the chain of function calls ending with


the line containing the error.

31
Logical errors

Logical errors refer to mistakes in the logic of a code, which result in


unexpected output.

IDE’s (Thonny, etc) cannot inform us about logic errors.

To avoid them, we need to be careful writing and documenting code,


and we need to test our code thoroughly.

32
Logical errors

x = input("Enter your favourite number: ")


print("Multiplied by 2: ", x*2)

Enter your favourite number: 5


Multiplied by 2: 55

33
Infinite loop ?

If the program doesn’t finish/exit and seems to be doing nothing, it


might be caught in an infinite loop (a logic error).

ct = 0
while ct < 100:
# ..... but the code block doesn’t increment ct

Or it might just be taking a long time.

ct = 0
while ct < 999999999:
ct += 1
# .....

34
How to check for an infinite loop ?

ct = 0

print('entering while loop #1')

while ct < 100:


# bla bla

print('finished while loop #1')

35
Errors

• types of errors
• syntax errors
• runtime errors
• logical errors

• raising exceptions

• doctest

36
Raising exceptions

Even if a program is correct, runtime errors (exceptions) can still


occur e.g. if inputs contain unexpected values.

There are two strategies for dealing with this:

• “raising an exception” : include instructions in the program


that cause the program to terminate with an appropriate error
message indicating what the error was

• ASIDE: “handling an exception” : cause a program to


continue executing even though an error has occurred
(too advanced -- we will not discuss this – we mention it only in
case you come across the term)

37
Example
def is_prime(n):
if n <= 1:
return False
else:
# code to check for prime

Do we want to return False if the user enters a negative number?


Probably not. Instead we can raise an exception.

See next slide.

38
Example
def is_prime(n):
if n <= 0:
raise ValueError("Primality not defined for numbers <= 0")

Keyword Exception name Message to be displayed

if n == 1:
return False
else:
# code to check for prime

39
Raising exceptions

You can raise any exception you want. e.g.:

• NameError, TypeError, ValueError, IndexError, ZeroDivisionError, …

raise <exception_name>(message)

A message is optional, but highly recommended.

40
Recall docstrings
def add(x, y):
""" (num, num) -> num
Returns the sum of x and y
>>> add(2, 2)
4
>>> add(-2, 3)
1
>>> add(1.2, 3.5)
4.7
"""
summation = x + y
return summation

41
doctest

If you use the given format for the docstring, you can have
the Python interpreter automatically test your functions with
the examples you provide in the docstring.

Add to your module (.py file):

1. import doctest (anywhere in the module)

2. [Link]() (at the end of the module)

42
[Link]()

What does [Link]() do?

• For each function in the module, it will execute each line in the
docstring that begins with '>>>'.

• It will then compare the result obtained, with your expected value.

• If they don't match, it will print that a test has failed, and why.

• If they match, nothing is displayed.

43

You might also like