Python Function
Python Function
Activity: Loop
Provide one example each for a for loop and a while loop, and
identify the logic behind each loop. Alternatively, you may use the
problem below to demonstrate both types of loops.
• Write a program that uses a loop to print numbers from 1 to N,
where N is an input positive integer.
• Write a program in python to display the cube of the number up
to an input integer value.
• Count and print the number of consonants and vowel in a given
string using a loop.
• Write a program in python to display a pattern like a right angle
triangle using an asterisk.
• Write a program in python to display the n terms of a harmonic
series and their sum.
Python Functions
Elezear Repil
Learning Objectives:
*args
• If you do not know how many arguments that will be passed into
your function, add a * before the parameter name in the function
definition.
• This way the function will receive a tuple of arguments, and can
access the items accordingly
• Arbitrary Arguments are often shortened to *args in Python
documentations.
If the number of arguments is unknown, add a * before the parameter
name:
Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
• The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.
Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
• This way the function will receive a dictionary of arguments, and can access
the items accordingly:
Passing a List as an Argument
Recursion
This function counts down from a given number to 1, printing each number
along the way, and then prints "Liftoff!" when it reaches 0.
Example of recursion in Python
This function
calculates the sum
of integers from 1
to a given number
n using recursion.
Activity:
Write a Python function to:
• find the Max of three numbers
• to sum all the numbers in a list
• to multiply all the numbers in a list
• to reverse a string
• to calculate the factorial of a number
• to check whether a number falls in a given range
• that accepts a string and calculate the number of upper case letters
and lower case letters
End