Control statements
Judgementโ
ifโ
To construct branch structures in Python you can use the if
, elif
and else
keywords.
"""
User authentication
Version: 0.1
Author: ``Luo Hao
"""
username = input('Please enter username: ')
password = input('Please enter the password: ')
# If username is admin and password is 123456 then authentication is successful otherwise authentication fails
if username == 'admin' and password == '123456':
print('Authentication successful!')
else:
print('Authentication failed!')
Of course if you want to construct more branches, you can use if... . .elif... .else...
structure or nested if... .else...
structures.
matchโ
The match statement takes an expression and compares its value with a series of patterns given as one or more case blocks. This is superficially similar to the switch statement in C, Java or JavaScript (and many other languages), but it can also extract subparts (sequence elements or object properties) from the value and assign them to variables.
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
The last block: "variable name" _
is used as a wildcard and will always match. If no case statement matches, then no branch will be executed.
You can use |
(" or ") to combine several literal values in a pattern:
case 401 | 403 | 404:
return "Not allowed"
Loopโ
forโ
Python's for statement differs from those in C or Pascal. instead of iterating over arithmetically increasing values (as in Pascal), or giving the user the ability to define iteration steps and pause conditions (as in C), Python's for statement iterates over arbitrary sequences such as lists or strings, with elements iterated over in the same order as they appear in the sequence.
"""
Summing 1 to 100 with a for loop
Version: 0.1
Author: ้ชๆ
"""
sum = 0
for x in range(101):
sum += x
print(sum)
range(101)
can be used to construct a range from 1 to 100, and when we put such a range into a for-in
loop, we can retrieve the integers from 1 to 100 in turn by using the preceding loop variable x
. Of course, the use of range
is very flexible and an example is given below.
range(101)
: can be used to produce integers in the range 0 to 100, with the caveat that 101 is not fetched.range(1, 101)
: can be used to produce integers in the range 1 to 100, equivalent to a closed interval followed by an open interval.range(1, 101, 2)
: can be used to generate odd numbers from 1 to 100, where 2 is the step size, i.e. the value incremented each time.range(100, 0, -2)
: can be used to produce an even number from 100 to 1, where -2 is the step size, i.e. the value decremented each time the number is decremented.
whileโ
If you want to construct a loop structure that does not know the exact number of loops, then use the while
loop to control the loop by an expression that produces or converts a bool
value, with a value of True
continuing the loop and a value of False
ending it.
"""
Guess the number game
Version: 0.1
Author: ``Luo Hao
"""
import random
answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
number = int(input('Please enter: '))
if number < answer:
print('Bigger')
elif number > answer:
print('smaller')
else:
print('Congratulations on your correct guess!')
break
print('You made %d guesses' % counter)
if counter > 7:
print('Your IQ balance is clearly low')
breakโ
The break statement is similar to the one in C and is used to jump out of the most recent for or while loop.
continueโ
The continue statement, also borrowed from C, indicates that the loop is to be continued to the next iteration.
elseโ
The else clause is supported in the loop statement; it is executed when all the elements in the for loop are looped through, or when the condition of the while loop is false; it is not executed when the break statement terminates the loop.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
"""
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
"""
Exceptionsโ
try, except, finallyโ
except
statements are not required, nor arefinally
statements, but there must be one of them, otherwise there is no point intry
.- There can be more than one
except
statement, Python will match the exceptions you specify in order of theexcept
statement, and if the exception has already been handled it will not go to the nextexcept
statement. - The
except
statement can specify multiple exceptions at once as a tuple, see the example code. - If you do not specify an exception type after the
except
statement, all exceptions are caught by default and you can get the current exception through logging or the sys module. - If you want to catch an exception and then throw it repeatedly, use
raise
without any arguments or information afterwards. - It is not recommended to catch and throw the same exception, consider refactoring your code.
- It is not advisable to catch all exceptions without clear logic, it is possible that you are hiding a serious problem.
- Try to use built-in exception handling statements instead of
try/except
statements, such aswith
statements andgetattr()
methods.
def div(a, b):
try:
print(a / b)
except ZeroDivisionError:
print("Error: b should not be 0 !!!")
except Exception as e:
print("Unexpected Error: {}".format(e))
else:
print('Run into else only when everything goes well')
finally:
print('Always run into finally block.')
# tests
div(2, 0)
div(2, 'bad type')
div(1, 2)
# Mutiple exception in one line
try:
print(a / b)
except (ZeroDivisionError, TypeError) as e:
print(e)
# Except block is optional when there is finally
try:
open(database)
finally:
close(database)
# catch all errors and log it
try:
do_work()
except:
# get detail from logging module
logging.exception('Exception caught!')
# get detail from sys.exc_info() method
error_type, error_value, trace_back = sys.exc_info()
print(error_value)
raise
raiseโ
The raise
statement supports forcing the specified exception to be raised. For example.
raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
Otherโ
passโ
The pass statement does not perform any action. This statement can be used when a statement is syntactically required but the program does not actually perform any action. For example.
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
# The smallest class
class MyEmptyClass:
pass
delโ
The deletion of the target list will recursively delete each target from left to right
del a
del b[]
returnโ
return leaves the current function call with a list of expressions (or None) as the return value.
yieldโ
Generating iterators
def foo(num):
print("starting...")
while num<10:
num=num+1
yield num
for n in foo(0):
print(n)
# Output
starting...
1
2
3
4
5
6
7
8
9
10
importโ
The basic import statement (without the from clause) is executed in two steps:
Find a module and, if necessary, load and initialise it.
Define one or more names in a local namespace for the scope in which the import statement occurs.
import foo # foo imported and bound locally
import foo.bar.baz # foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
from foo.bar import baz # foo.bar.baz imported and bound as baz
from foo import attr # foo imported and foo.attr bound as attr
The from form is a little more complicated to use:
find the module specified in the from clause, and load and initialize it if necessary.
for each identifier specified in the import clause.
- check if the module being imported has an attribute of that name
- if not, try importing a sub-module with that name and then check again if the imported module has that attribute
- if the attribute is not found, then raise an ImportError. 4.
- otherwise, store a reference to the value in the local namespace, using the name specified by the as clause if it exists, otherwise use the name of the attribute
globalโ
The global statement is a declaration that acts on the entire current block of code. It means that the identifiers listed will be interpreted as global variables.
nonlocalโ
The nonlocal statement causes the listed name to point to a variable other than the global variable previously bound in the most recent containing scope.