0% found this document useful (0 votes)
12 views15 pages

Python Control Structures & Functions

This document covers control structures and functions in Python, detailing their importance and usage. It explains concepts such as indentation, comments, loops, and function definitions, along with examples of conditional statements and argument handling. By the end, students should be able to write and understand basic Python code involving these elements.

Uploaded by

amnouyporn-pra67
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)
12 views15 pages

Python Control Structures & Functions

This document covers control structures and functions in Python, detailing their importance and usage. It explains concepts such as indentation, comments, loops, and function definitions, along with examples of conditional statements and argument handling. By the end, students should be able to write and understand basic Python code involving these elements.

Uploaded by

amnouyporn-pra67
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

03 - Control structures and functions

Control structures and functions

Learning Outcomes
By the end of this lecture, students will be able to:
Explain basics understanding of control structures and functions.
Identify benefits of control structures and functions in Python.
Write control structures and functions in Python.

Choose with if
In this lecture, you learn how to structure Python code, not just data.
Many computer languages use characters such as curly braces ( { and } ) or
keywords such as begin and end to mark off sections of code.
In those languages, it’s good practice to use consistent indentation to make your
program more readable for yourself and others.
Rossum decided that the indentation itself was enough to define a program’s
structure, and avoided typing all those parentheses and curly braces.

Comment with #
A comment is a piece of text in your program that is ignored by the Python interpreter.
You might use comments to clarify nearby Python code, make notes to yourself to fix
something someday.
You mark a comment by using the # character; everything from that point on to the
end of the current line is part of the comment.
The # character has many names: hash, sharp, pound, or the sinister 1 2 sounding
octothorpe.

1 # 60 sec/min * 60 min/hr * 24 hr/day


2 seconds_per_day = 86400

or
1 seconds_per_day = 86400 # 60 sec/min * 60 min/hr * 24 hr/day

Continue Lines with `\


Programs are more readable when lines are reasonably short.
The recommended (not required) maximum line length is 80 characters.
If you can’t say everything you want to say in that length, you can use the continuation
character: \ (backslash).
Just put \ at the end of a line, and Python will suddenly act as though you’re still on
the same line.

1 sum = 0
2 sum += 1
3 sum += 2
4 sum += 3
5 sum += 4
6 print(sum)

10

1 sum = 1 + \
2 2 + \
3 3 + \
4 4
5 print(sum)

10

Compare with if , elif , and else


Now, we finally take our first step into the code structures that weave data into
programs.

1 disaster = True
2 if disaster:
3 print("Woe!")
4 else:
5 print("Whee!")

Woe!
You can have tests within tests, as many levels deep as needed.
In Python, indentation determines how the if and else sections are paired.

1 furry = True
2 large = True
3 if furry:
4 if large:
5 print("It's a yeti.")
6 else:
7 print("It's a cat!")
8 else:
9 if large:
10 print("It's a whale!")
11 else:
12 print("It's a human. Or a hairless cat.")

It's a yeti.

Note that two equals signs ( == ) are used to test equality; remember, a single equals
sign ( = ) is what you use to assign a value to a variable.
If you need to make multiple comparisons at the same time, you use the logical (or
boolean) operators and , or , and not to determine the final boolean result.
Logical operators have lower precedence than the chunks of code that they’re
comparing.
This means that the chunks are calculated first, and then compared.

1 (5 < x) and (x < 10) # True


2 5 < x or x < 10 # True
3 5 < x and x > 10 # False
4 5 < x and not x > 10 # True
5 5 < x < 10 # True

Do Multiple Comparisons with in


One way would be to write a long if statement:

1 letter = 'o'
2 if letter == 'a' or letter == 'e' or letter == 'i' \
3 or letter == 'o' or letter == 'u':
4 print(letter, 'is a vowel')
5 else:
6 print(letter, 'is not a vowel')

o is a vowel
Whenever you need to make a lot of comparisons like that, separated by or , use
Python’s membership operator in , instead.

1 vowels = 'aeiou'
2 letter = 'o'
3 print(letter in vowels)
4 if letter in vowels:
5 print(letter, 'is a vowel')

True
o is a vowel

New: I Am the Walrus


Arriving in Python 3.8 is the walrus operator, which looks like this:

1 name := expression

See the walrus? (Like a smiley, but tuskier.)


Normally, an assignment and test take two steps:

1 tweet_limit = 280
2 tweet_string = "Blah" * 50
3 diff = tweet_limit - len(tweet_string)
4 if diff >= 0:
5 print("A fitting tweet")
6 else:
7 print("Went over by", abs(diff))

A fitting tweet

With our new tusk power (aka assignment expressions) we can combine these into one
step:

1 tweet_limit = 280
2 tweet_string = "Blah" * 50
3 if diff := tweet_limit - len(tweet_string) >= 0:
4 print("A fitting tweet")
5 else:
6 print("Went over by", abs(diff))

A fitting tweet
Loop with while and for
Testing with if , elif , and else runs from top to bottom.
Sometimes, we need to do something more than once.
We need a loop, and Python gives us two choices: while and for .

Repeat with while


The simplest looping mechanism in Python is while .
Try this example, which is a simple loop that prints the numbers from 1 to 5:

1 count = 1
2 while count <= 5:
3 print(count)
4 count += 1

12345

Cancel with break


If you want to loop until something occurs, but you’re not sure when that might happen.
You can use an infinite loop with a break statement.

1 while True:
2 stuff = input("String to capitalize [type q to quit]: ")
3 if stuff == "q":
4 break
5 print([Link]())

String to capitalize [type q to quit]: test


Test
String to capitalize [type q to quit]: hey, it works
Hey, it works
String to capitalize [type q to quit]: q

Skip Ahead with continue


Sometimes, you don’t want to break out of a loop but just want to skip ahead to the next
iteration for some reason.
1 while True:
2 value = input("Integer, please [q to quit]: ")
3 if value == 'q':
4 break # quit
5 number = int(value)
6 if number % 2 == 0: # an even number
7 continue
8 print(number, "squared is", number*number)

Integer, please [q to quit]: 1


1 squared is 1
Integer, please [q to quit]: 2
Integer, please [q to quit]: 3
3 squared is 9
Integer, please [q to quit]: 4
Integer, please [q to quit]: 5
5 squared is 25
Integer, please [q to quit]: q

Check break Use with else


If the while loop ended normally (no break call), control passes to an optional else.
This use of else might seem nonintuitive. Consider it a break checker.

1 numbers = [1, 3, 5]
2 position = 0
3 while position < len(numbers):
4 number = numbers[position]
5 if number % 2 == 0:
6 print('Found even number', number)
7 break
8 position += 1
9 else: # break not called
10 print('No even number found')

No even number found

Iterate with for and in


Python makes frequent use of iterators, for good reason.
They make it possible for you to traverse data structures without knowing how large
they are or how they are implemented.
You can even iterate over data that is created on the fly, allowing processing of data
streams that would otherwise not fit in the computer’s memory all at once.
In a for loop, continue and break can be used as they are used for a while loop.
else also performs the same as for a while loop.

1 word = 'thud'
2 for letter in word:
3 print(letter)

t
h
u
d

Generate Number Sequences with range()


The range() function returns a stream of numbers within a specified range without
first having to create and store a large data structure such as a list or tuple.
This lets you create huge ranges without using all the memory in your computer and
crashing your program.
You use range() similar to how to you use slices: range(start, stop, step) .
If you omit start , the range begins at 0. The only required value is stop ; as with slices,
the last value created will be just before stop.
The default value of step is 1 , but you can go backward with -1.
range() returns an iterable object, so you need to step through the values with for
... in , or convert the object to a sequence like a list .

1 for x in range(0,3):
2 print(x)
3
4 print(list(range(0, 3)))

012
[0, 1, 2]

Define a Function with def


To define a Python function, you type def , the function name, parentheses enclosing
any input parameters to the function, and then finally, a colon ( : ).
Function names have the =same rules= as variable names (they must start with a
letter or and contain only letters, numbers, or ).

1 def do_nothing():
2 pass

1 function do_nothing() {
2 }

Even for a function with no parameters like this one, you still need the parentheses and
the colon in its definition.
The =next line needs to be indented=, just as you would indent code under an if
statement.
Python requires the =pass statement= to show that this function does nothing.
It’s the equivalent of This page intentionally left blank (even though it isn’t anymore)

Call a Function with Parentheses


You call this function just by typing its name and parentheses.
It works as advertised, doing nothing, but doing it very well:

1 do_nothing()

Now let’s define and call another function that has no parameters but prints a single
word:

1 def make_a_sound():
2 print('quack')
3
4 make_a_sound()

quack

Let’s try a function that has no parameters but returns a value.


You can call this function and test its returned value by using if :

1 def agree():
2 return True
3
4 if agree():
5 print('Splendid!')
6 else:
7 print('That was unexpected.')

Splendid!

The combination of functions with tests such as if and loops such as while make it
possible for you to do things that you could not do before.

Arguments and Parameters


It’s time to put something between those parentheses.
Let’s define the function echo() with one parameter called anything.
It uses the return statement to send the value of anything back to its caller twice, with a
space between:

1 def echo(anything):
2 return anything + ' ' + anything
3
4 echo('Rumplestiltskin')

'Rumplestiltskin Rumplestiltskin'

The values you pass into the function when you call it are known as arguments.
When you call a function with arguments, the values of those arguments are copied to
their corresponding parameters inside the function.

1 def commentary(color):
2 if color == 'red':
3 return "It's a tomato."
4 elif color == "green":
5 return "It's a green pepper."
6 elif color == 'bee purple':
7 return "I don't know what it is, but only bees can see
it."
8 else:
9 return "I've never heard of the color " + color + "."
10
11 comment = commentary('blue')
12 print(comment)

I've never heard of the color blue.

A function can take any number of input arguments (including zero) of any type.
It can return any number of output results (also including zero) of any type.
If a function doesn’t call return explicitly, the caller gets the result None .

1 print(do_nothing())

None

None Is Useful
None is a special Python value that holds a place when there is nothing to say.
It is not the same as the boolean value False , although it looks false when evaluated
as a boolean.

1 thing = None
2 if thing:
3 print("It's some thing")
4 else:
5 print("It's no thing")

It's no thing

1 thing = None
2 if thing is None:
3 print("It's nothing")
4 else:
5 print("It's something")

It's nothing

It’s important in Python. You’ll need None to distinguish a missing value from an empty
value.
Remember that zero-valued integers or floats, empty strings ( '' ), lists ( [] ), tuples
( (,) ), dictionaries ( {} ), and sets ( set() ) are all False , but are not the same as
None .
Let’s write a quick function that prints whether its argument is None , True , or False :

1 def whatis(thing):
2 if thing is None:
3 print(thing, "is None")
4 elif thing:
5 print(thing, "is True")
6 else:
7 print(thing, "is False")
8
9 whatis(None) # None
10 whatis(True) # True
11 whatis(False) # False

You may try these:

1 whatis(0)
2 whatis(0.0)
3 whatis('')
4 whatis("")
5 whatis('''''')
6 whatis(())
7 whatis([])
8 whatis({})
9 whatis(set())
10 whatis(0.00001)
11 whatis([0])
12 whatis([''])
13 whatis(' ')

Positional Arguments
Python handles function arguments in a manner that’s very flexible, when compared to
many languages.
The most familiar types of arguments are positional arguments, whose values are
copied to their corresponding parameters in order.

1 def menu(wine, entree, dessert):


2 return {'wine': wine, 'entree': entree, 'dessert': dessert}
3
4 menu('chardonnay', 'chicken', 'cake')

{'wine': 'chardonnay', 'entree': 'chicken', 'dessert': 'cake'}

Although very common, a downside of positional arguments is that you need to


remember the meaning of each position.
If we forgot and called menu() with wine as the last argument instead of the first, the
meal would be very different:

1 menu('beef', 'bagel', 'bordeaux')

{'wine': 'beef', 'entree': 'bagel', 'dessert': 'bordeaux'}


Keyword Arguments
To avoid positional argument confusion, you can specify arguments by the names of
their corresponding parameters, even in a different order from their definition in the
function:

1 menu(entree='beef', dessert='bagel', wine='bordeaux')

{'wine': 'bordeaux', 'entree': 'beef', 'dessert': 'bagel'}

You can mix positional and keyword arguments.


Let’s specify the wine first, but use keyword arguments for the entree and dessert:

1 menu('frontenac', dessert='flan', entree='fish')

{'wine': 'frontenac', 'entree': 'fish', 'dessert': 'flan'}

If you call a function with both positional and keyword arguments, the positional
arguments need to come first.

Specify Default Parameter Values


You can specify default values for parameters.
The default is used if the caller does not provide a corresponding argument.
This bland-sounding feature can actually be quite useful. Using the previous example:
This time, try calling menu() without the dessert argument:

1 def menu(wine, entree, dessert='pudding'):


2 return {'wine': wine, 'entree': entree, 'dessert': dessert}
3
4 menu('chardonnay', 'chicken')

{'wine': 'chardonnay', 'entree': 'chicken', 'dessert': 'pudding'}

If you do provide an argument, it’s used instead of the default:

1 menu('dunkelfelder', 'duck', 'doughnut')

{'wine': 'dunkelfelder', 'entree': 'duck', 'dessert': 'doughnut'}

Default parameter values are calculated when the function is defined, not when it is run.
A common error with new (and sometimes not-so-new) Python programmers is to use a
mutable data type such as a list or dictionary as a default parameter.
1 def buggy(arg, result=[]):
2 [Link](arg)
3 print(result)
4
5 buggy('a')
6 buggy('b') # expect ['b']

['a']
['a', 'b']

It would have worked if it had been written like this:

1 def works(arg):
2 result = []
3 [Link](arg)
4 print(result)
5
6 works('a')
7 works('b')

['a']
['b']

The fix is to pass in something else to indicate the first call:

1 def nonbuggy(arg, result=None):


2 if result is None:
3 result = []
4 [Link](arg)
5 print(result)
6
7 nonbuggy('a')
8 nonbuggy('b')

['a']
['b']

This is sometimes a Python job interview question.

Explode/Gather Positional Arguments with *


If you’ve programmed in C or C++, you might assume that an asterisk ( * ) in a Python
program has something to do with a pointer.
Nope, Python doesn’t have pointers.
When used inside the function with a parameter, an asterisk groups a variable number
of positional arguments into a single tuple of parameter values.

1 def print_args(*args):
2 print('Positional tuple:', args)
3
4 print_args()
5 print_args(3, 2, 1, 'wait!', 'uh...')

Positional tuple: ()
Positional tuple: (3, 2, 1, 'wait!', 'uh...')

This is useful for writing functions such as print() that accept a variable number of
arguments.
If your function has required positional arguments, as well, put them first; *args goes
at the end and grabs all the rest:

1 def print_more(required1, required2, *args):


2 print('Need this one:', required1)
3 print('Need this one too:', required2)
4 print('All the rest:', args)
5
6 print_more('cap', 'gloves', 'scarf', 'monocle', 'mustache wax')

Need this one: cap


Need this one too: gloves
All the rest: ('scarf', 'monocle', 'mustache wax')

When using ` , you don’t need to call the tuple argument args , but it’s a
common idiom in Python. It’s also common to use args inside the function, as
in the preceding example, although technically it’s called a parameter and
could be referred to as params`.

Explode/Gather Keyword Arguments with **


You can use two asterisks ( ** ) to group keyword arguments into a dictionary, where
the argument names are the keys, and their values are the corresponding dictionary
values.
The following example defines the function print_kwargs() to print its keyword
arguments:
Now try calling it with some keyword arguments:

1 def print_kwargs(**kwargs):
2 print('Keyword arguments:', kwargs)
3
4 print_kwargs()
5 print_kwargs(wine='merlot', entree='mutton', dessert='macaroon')

Keyword arguments: {}
Keyword arguments: {'dessert': 'macaroon', 'wine': 'merlot', 'entree': 'mutton'}

Inside the function, kwargs is a dictionary parameter.


Argument order is:
Required positional arguments
Optional positional arguments ( *args )
Optional keyword arguments ( **kwargs )

References
Lubanovic, B. (2019). Introducing Python: Modern Computing in Simple Packages.
O’Reilly Media.

You might also like