for i in range(3):
print('hello')
hello
hello
hello
Control flow, exceptions
Chi Zhang
December 5, 2024
The indentation can be either 2 or 4. In a loop, it has to be indented. The :
also is necessary.
for (i in 1:3){
print('hello')
}
Combined with lists
89
77
91
Combined with counter
In R
n <- 4
while(n>0){
print('continue')
n <- n-1
}
Conditions
True
True
break
needs to be inside the loop. Typically used with while
songs = ["Hello", "Yesterday", "Happy", "Hallelujah"]
for song in songs:
print("Searching")
if song == "Happy":
print("Playing " + song)
break
Searching
Searching
Searching
Playing Happy
continue
skips when the condition is not met
Types of exceptions:
NameError
SyntaxError
ValueError
IndexError
TypeErorr
try
block: test a block of code for errors
except
block: handle the error
If we do not know what kind of exception we are expecting,
Something is wrong
try:
print(k)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Variable x is not defined
try:
print(3 + "3")
except ValueError:
print("Cannot add different types")
except TypeError:
print("Type mismatch error")
Type mismatch error
else
block: execute code when there is no error
finally
block: execute code regardless of result of the try/except blocks
books = ['HP', 'dune']
try:
print(books[5])
except IndexError:
print('out of range')
finally:
print('happy reading')
out of range
happy reading
Raise an exception
Raise a type error