5.71M

Lecture 3 - Controlling structures and functions

1.

ADVANCED
PROGRAMMING I
Lecture 3 – Controlling structures
and functions
Shynggys Kairatuly Alshynov
MSc in IT
[email protected]

2.

OBJECTIVES
• Conditionals
• Loops
• For
• While
• Nested Loops
• Error (exception) handling
• Try-Except statments
• Own exceptions
• Functions
• Names and documenting
• Parameters and document extraction
• Recursion
• Nested functions
• Global variables access
• Lambda functions
• Asserts
• Code examples

3.

LEARNING OUTCOMES
• At the end of this loop of despair you will be able to use:
• Loops
• Handle errors
• Create and call functions

4.

IF-ELSE STATEMENTS (CONDITIONALS)
• Hope you know what is a condition in programming
• For those who do not know, it is «Пойдешь гулять, если закончишь
домашнее задание», got it?
• If statement and its examples:
• Example 1:
• a=5
• if a < 10:
print(“{0} is less than {1}”.format(“a”, 10))

5.

IF-ELSE STATEMENTS (CONDITIONALS)
• Example 2: Nested if
•a=5
b=6
c = 100
if a>4:
if b>a:
if c>b:
print("%2d < %2d < %2d" % (a,b,c))

6.

IF-ELSE STATEMENTS (CONDITIONALS)
• If + else statements: you use “else” only after “if” statement
• Example 3
a=51
if a>50:
print("You passed with a score %d" %a)
else:
print("Welcome to summer semester")

7.

IF-ELSE STATEMENTS (CONDITIONALS)
• If + elif + else statements: elif is an analogue of else-if in c++ and java
• Example 4
a=50
b=85
if a>=50:
print("You passed with a score %d" %a)
elif b>=80 and b<=100:
print("Someone passed with a merit or distinction, his/her mark is
{}".format(a))
else:
print("Welcome to summer semester")

8.

IF-ELSE STATEMENTS (CONDITIONALS)
• Complicated if statements: several conditions
• Example 5
a=50
b=70
if a>=50 and b<75:
print(“Your mark is between %d and %d" % (a, b))
else:
print("Welcome to summer semester")

9.

THANK YOU FOR THE IDEA OF LOOPS,
DEAR ADA LOVELACE!
Ada Lovelace
• “A gifted mathematician, Ada Lovelace is considered to have
written instructions for the first computer program in the mid-1800s.”
• “She also theorized a method for the engine to repeat a series of
instructions, a process known as looping that computer programs use
today. Ada also offered up other forward-thinking concepts in the
article.”
Biography.com Editors, (2014) Ada Lovelace Biography. Online:
[https://www.biography.com/people/ada-lovelace-20825323]

10.

FOR LOOPS
• The for statement in Python differs a bit from what you may be
used to in C or Pascal. Rather than always iterating over an
arithmetic progression of numbers (like in Pascal), or giving the user
the ability to define both the iteration step and halting condition (as
C), Python’s for statement iterates over the items of any sequence (a
list or a string), in the order that they appear in the sequence.
• for i in <sequence>:
• do something
• https://docs.python.org/3.6/tutorial/controlflow.html

11.

EXAMPLES OF FOR LOOPS
• Simple for loop:
• for i in range(10):
• print(i)
• Nested for loop:
• for i in range(10):
• for j in range(5):
• print(“i is {} and j is {}”.format(i,j))

12.

WHILE LOOPS (CAN BE NESTED TOO)
• The while statement is used for repeated execution as long as an
expression is true:
• while <true expression>:
• do something
• Simple example:
• while i < 5:
• print(“i is %i” % i)
• i+=1
https://docs.python.org/3/reference/compound_stmts.html#the-forstatement

13.

LOOPS - BREAK
• Break is to stop your loop
• for i in range(10):
• if i is 6:
• print("Now i is %d and we stop this loop" % i)
• break
• else:
• print("I is not 6 yet")

14.

CONTINUE A LOOP
• Continue is used to keep on a loop
• while True: # infinite loop
• user_input = input("Write hello, if you do not do it, I won't stop asking you! \t")
• print("You typed: ", user_input)
• if user_input.lower() != "hello":
• continue
• else:
• print("Good boy/girl! I knew that you will give up!")
• break

15.

ELSE STATEMENT IN LOOPS (NOT A JOKE)
• Loop statements may have an else clause.
• a=10
• while a is not 0:
• print("a is %i" % a)
• a -=1
• else:
• print("a has become %d :(" % a)
• 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')
• https://docs.python.org/3/tutorial/controlflow.html

16.

ERROR (EXCEPTION) HANDLING
• An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.
• Common Errors: SyntaxError, TypeError, NameError
• SyntaxError
• A structure or tokens in the code are wrong
• TypeError
• An operation is applied to a datum of a wrong type
• NameError
• Referring to variable that has not been assigned value or was deleted
• https://docs.python.org/3.6/tutorial/errors.html
• https://docs.python.org/3.6/library/exceptions.html#bltin-exceptions

17.

ERROR (EXCEPTION) HANDLING
• The try statement specifies exception handlers and/or cleanup code
for a group of statements. The except clause(s) specify one or more
exception handlers. When no exception occurs in the try clause, no
exception handler is executed. When an exception occurs in the try
suite, a search for an exception handler is started.
• a = input("Input anything you want: ")
• try:
a = int(a)
• except ValueError:
print("You entered a value that cannot be converted to an integer value!")

18.

ERROR (EXCEPTION) HANDLING
• The raise statement allows the programmer to force a specified
exception to occur. For example:
• try:
• raise NameError('HiThere')
• except NameError:
• ('An exception flew by!')
• raise
• Defining Clean-up Actions

19.

ERROR (EXCEPTION) HANDLING
• Defining Clean-up Actions
• The try statement has another optional clause which is intended to define
clean-up actions that must be executed under all circumstances. For
example:
• try:
• raise KeyboardInterrupt
• finally:
• print('Goodbye, world!')

20.

LET’S BEGIN FUNCTIONS

21.

FUNCTION
• Defining functions starts with a keyword def and must be
followed by the function name and the parenthesized list of
parameters. The statements that form the body of the function
start at the next line, and must be indented.
• def function_name(parameter(s)/argument(s)):
• Statements
• Drawback is that errors can be found only after calling a
function. Remember to check your functions!
• https://docs.python.org/3.6/tutorial/controlflow.html#definingfunctions

22.

BUILT-IN FUNCTIONS IN PYTHON
(GENERAL)
• https://docs.python.org/3.6
/library/functions.html
Use this link to get a full
description of all functions
listed in the pic

23.

FUNCTION
• Documentation Strings:
• def my_function():
• """Do nothing, but document it.
No, really, it doesn't do anything.
"""
pass
• print(my_function.__doc__)

24.

FUNCTION RETURN VS PRINT()
• return is needed in function to get results of your calculations
• def ret_func():
• return "This year is going to be the best in my life!\nHah, just joking“
• print() function just prints the resulst but cannot be stored in a
variable
• def print_func():
• print( "This year is going to be the best in my life!\nHah, just joking")
• As you understood, using return statement helps to store results in a
variable
• Some_variable = ret_func()

25.

GLOBAL VARIABLES
• Global variable is a variable that is available for operations on itself
inside of functions, classes. Analogue of public variables in c++ and
java.
• a = []
• def some_func():
• global a
• for i in ["red", "green", "blue", "black", "orange", "yellow", "white"]:
• a.append(i)
• return a

26.

FUNCTION YIELDS
• The yield statement enables us to write functions that are generators
Such functions may be similar to coroutines, since they may "yield"
multiple times and are resumed.
• # using yield
• def yield_smth():
• for i in range(10):
if i%2==0:
yield i
• for i in yield_smth():
• print(i)

27.

FUNCTION YIELDS
• Another example of yield
• def iter_smth(someList = [], maxNum = 100):
• for i in someList:
if i >= maxNum:
return
yield i
• for i in yield_smth():
• print(i)

28.

FUNCTION ARGUMENTS
• When calling a function, values may be passed to a function with position
al arguments or keyword arguments.
• # funciton with an argument
• def func_with_arg(myIntArg):
• myIntArg = myIntArg**2
• return myIntArg
• # function with more than one argument
• def func_more_args(myIntArg, myStrArg):
• return myIntArg*( myStrArg)
• Order of arguments:
• 1. Normal arguments. 2. Arguments with default values. 3. Argument list (*args). 4.
Keyword arguments (**kwargs).

29.

FUNCTION WITH *ARGS
• The special syntax *args in function definitions in python is used to
pass a variable number of arguments to a function. It is used to pass
a non-keyworded, variable-length argument list.
• # function with *args, **kwargs
• # *args is used for tuples
• # **kwargs for dicts
• def my_args_func(*args):
• for i in args:
print(i)

30.

FUNCTION WITH **KWARGS
• The special syntax **kwargs in function definitions in python is used
to pass a keyworded, variable-length argument list. We use the
name kwargs with the double star.
• def my_kwargs_func(**kwargs):
• for k,v in kwargs.items():
print("Key is {} and its value is {}".format(k,v))
• my_kwargs_func(idBir='Alshynov', idEki="Myrzaliyev")

31.

FUNCTION PARAMETERS
• Parameters are needed to set a default values for your arguments.
• Do not use mutable objects as default values.
• # function with a default value
• def func_def_val(myString = "Python"):
• return myString
• Normal arguments must come before default arguments which
must come before keyword arguments.
• # function with arguments and a default value
• def add_hello(name, surname, greet = "Hello"):
• return greet + " " + str(name) + " " +str(surname)

32.

FUNCTION INSIDE OF A FUNCTION
• You can create functions inside of a function
• def outside_func():
• def inside_func():
• print("This is inside func")
• print("This is outside func")
• return inside_func()

33.

RECURSION
• Recursion is an elegant way of avoiding loops.
• Recursion is a way of programming or coding a problem, in which a function calls itself one or
more times in its body.
• A recursive function has to terminate to be used in a program.
• # Recursion
• def rec_func(n):
if n == 0:
return [0]
else:
return [n] + rec_func(n-1)
• def func_factorial(n):
if n ==1:
return 1
else:
return n*func_factorial(n-1)

34.

LAMBDA OPERATOR (FUNCTION)
• Lambda operator is needed to create anonymous functions or
unnamed functions. Was created due to the demand of Lisp
programmers.
• General syntax of lambda functions:
• lambda argument: expression (body)
• Example of lambda function:
• (lambda x: x**2)(5)
• Or better to store it as a function:
squareX=lambda x: x**2
• Paragraph 1.7.2 Kuhlman D, 2009

35.

LAMBDA OPERATOR (CONT.)
• More examples for lambda:
• anotherEx = lambda x, y: x+y
• fn1 = lambda x,y: (x**2, y**3)
• fn2 = lambda x: [i for i in range(x)]

36.

MAP FUNCTION
• A function that has two arguments:
• map(func_name, <sequence>)
• func_name() is applied to all elements in the <sequence>
• Examples:
• ex13 = list(map(lambda x: x**2, range(1,10)))
• ex14 = list(map(lambda x,y: x+y, range(10), range(20)))

37.

FILTER FUNCTION
• The function filter(function_name, <sequence>) offers an elegant way
to filter out all the elements of a list, for which the function
function_name(Boolean function) returns True.
• Examples:
• ex15 = list(filter(lambda x: x%2==1, range(10)))
• ex16 = list(filter(lambda x: x%3==0 and x%5!=0, range(20, 51)))

38.

REDUCE FUNCTION
• reduce() is a really useful function for performing some computation
on a list and returning the result. It applies a rolling computation to
sequential pairs of values in a list.
• Example:
• import functools # makes available reduce()
• ex17 = functools.reduce(lambda x, y: x*y, range(1,10)) # built-in
reduce() was removed from python 3

39.

SUMMARY
• Now you look happier and can do these things:
• Use conditionals
• Use loops
• Create functions
• Define arguments and parameters
of a function
• Elegantly avoid loop
You are happier, aren’t you?

40.

THANK YOU FOR YOUR ATTENTION!
Python is as free as you are free to go!
English     Русский Rules