23. Functions | Python Tutorial (2024)

By Bernd Klein. Last modified: 29 Jun 2022.

On this page

syntax

The concept of a function is one of the most important in mathematics. A common usage of functions in computer languages ​​is to implement mathematical functions. Such a function is computing one or more results, which are entirely determined by the parameters passed to it.

This is mathematics, but we are talking about programming and Python. So what is a function in programming? In the most general sense, a function is a structuring element in programming languages ​​to group a bunch of statements so they can be utilized in a program more than once. The only way to accomplish this without functions would be to reuse code by copying it and adapting it to different contexts, which would be a bad idea. Redundant code - repeating code in this case - should be avoided! Using functions usually enhances the comprehensibility and quality of a program. It also lowers the cost for development and maintenance of the software.

Functions are known under various names in programming languages, eg as subroutines, routines, procedures, methods, or subprograms.

23. Functions | Python Tutorial (1)

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Motivating Example of Functions

Let's look at the following code:

print ( "Program starts" )print ( "Hi Peter" ) print ( "Nice to see you again!" ) print ( "Enjoy our video!" )# some lines of codes the_answer  =  42 print ( "Hi Sarah" ) print ( "Nice to see you again!" ) print ( "Enjoy our video!" )width ,  length  =  3 ,  4 area  =  width  *  lengthprint("Hi Dominque")print("Nice to see you again!")print("Enjoy our video!")

OUTPUT:

Program startsHi PeterNice to see you again!Enjoy our video!Hi SarahNice to see you again!Enjoy our video!Hi DominqueNice to see you again!Enjoy our video!

Let us have a closer look at the code above:

23. Functions | Python Tutorial (3)

You can see in the code that we are greeting three persons. Every time we use three print calls which are nearly the same. Just the name is different. This is what we call redundant code. We are repeating the code the times. This shouldn't be the case. This is the point where functions can and should be used in Python.

We could use wildcards in the code instead of names. In the following diagram we use a piece of the puzzle. We only write the code once and replace the puzzle piece with the corresponding name:

23. Functions | Python Tutorial (4)

Of course, this was no correct Python code. We show how to do this in Python in the following section.

Functions in Python

The following code uses a function with the name greet. The previous puzzle piece is now a parameter with the name "name":

def greet(name): print("Hi " + name) print("Nice to see you again!") print("Enjoy our video!")print("Program starts")greet("Peter") # some lines of codesthe_answer = 42 greet("Sarah") width, length = 3, 4area = width * lengthgreet("Dominque") 

OUTPUT:

Program startsHi PeterNice to see you again!Enjoy our video!Hi SarahNice to see you again!Enjoy our video!Hi DominqueNice to see you again!Enjoy our video!

23. Functions | Python Tutorial (5)

We used a function in the previous code. We saw that a function definition starts with the def keyword. The general syntax looks like this:

def function-name(Parameter list): statements, i.e. the function body

The parameter list consists of none or more parameters. Parameters are called arguments, if the function is called. The function body consists of indented statements. The function body gets executed every time the function is called. We demonstrate this in the following picture:

23. Functions | Python Tutorial (6)

The code from the picture can be seen in the following:

def f(x, y): z = 2 * (x + y) return zprint("Program starts!")a = 3res1 = f(a, 2+a)print("Result of function call:", res1)a = 4b = 7res2 = f(a, b)print("Result of function call:", res2)

OUTPUT:

Program starts!Result of function call: 16Result of function call: 22

We call the function twice in the program. The function has two parameters, which are called x and y. This means that the function f is expecting two values, or I should say "two objects". Firstly, we call this function with f(a, 2+a). This means that a goes to x and the result of 2+a (5) 'goes to' the variable y. The mechanism for assigning arguments to parameters is called argument passing. When we reach the return statement, the object referenced by z will be return, which means that it will be assigned to the variable res1. After leaving the function f, the variable z and the parameters x and y will be deleted automatically.

23. Functions | Python Tutorial (7)

The references to the objects can be seen in the next diagram:

23. Functions | Python Tutorial (8)

The next Python code block contains an example of a function without a return statement. We use the pass statement inside of this function. pass is a null operation. This means that when it is executed, nothing happens. It is useful as a placeholder in situations when a statement is required syntactically, but no code needs to be executed:

def doNothing(): pass

A more useful function:

def fahrenheit(T_in_celsius): """ returns the temperature in degrees Fahrenheit """ return (T_in_celsius * 9 / 5) + 32for t in (22.6, 25.8, 27.3, 29.8): print(t, ": ", fahrenheit(t))

OUTPUT:

22.6 : 72.6825.8 : 78.4427.3 : 81.1429.8 : 85.64

""" returns the temperature in degrees Fahrenheit """ is the so-called docstring. It is used by the help function:

help(fahrenheit)

OUTPUT:

Help on function fahrenheit in module __main__:fahrenheit(T_in_celsius) returns the temperature in degrees Fahrenheit

23. Functions | Python Tutorial (9)

Our next example could be interesting for the calorie-conscious Python learners. We also had an exercise in the chapter Conditional Statements of our Python tutorial. We will create now a function version of the program.

The body mass index (BMI) is a value derived from the mass (w) and height (l) of a person. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed

$BMI = {w \over {l ^ 2}}$

The weight is given in kg and the length in metres.

def BMI(weight, height): """ calculates the BMI where  weight is in kg and height in metres""" return weight / height**2

We like to write a function to evaluate the bmi values according to the following table:


23. Functions | Python Tutorial (10)

The following shows code which is directly calculating the bmi and the evaluation of the bmi, but it is not using functions:

height = float(input("What is your height? "))weight = float(input("What is your weight? "))bmi = weight / height ** 2print(bmi)if bmi < 15: print("Very severely underweight")elif bmi < 16: print("Severely underweight")elif bmi < 18.5: print("Underweight")elif bmi < 25: print("Normal (healthy weight)")elif bmi < 30: print("Overweight")elif bmi < 35: print("Obese Class I (Moderately obese)")elif bmi < 40: print("Obese Class II (Severely obese)")else: print("Obese Class III (Very severely obese)")

OUTPUT:

23.69576446280992Normal (healthy weight)

Turn the previous code into proper functions and function calls.

def BMI(weight, height): """ calculates the BMI where  weight is in kg and height in metres""" return weight / height**2def bmi_evaluate(bmi_value): if bmi_value < 15: result = "Very severely underweight" elif bmi_value < 16: result = "Severely underweight" elif bmi_value < 18.5: result = "Underweight" elif bmi_value < 25: result = "Normal (healthy weight)" elif bmi_value < 30: result = "Overweight" elif bmi_value < 35: result = "Obese Class I (Moderately obese)" elif bmi_value < 40: result = "Obese Class II (Severely obese)" else: result = "Obese Class III (Very severely obese)" return result

Let us check these functions:

height = float(input("What is your height? "))weight = float(input("What is your weight? "))res = BMI(weight, height)print(bmi_evaluate(res))

OUTPUT:

Normal (healthy weight)

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Upcoming online Courses

Enrol here

Default arguments in Python

When we define a Python function, we can set a default value to a parameter. If the function is called without the argument, this default value will be assigned to the parameter. This makes a parameter optional. To say it in other words: Default parameters are parameters, which don't have to be given, if the function is called. In this case, the default values are used.

We will demonstrate the operating principle of default parameters with a simple example. The following function hello, - which isn't very useful, - greets a person. If no name is given, it will greet everybody:

def hello(name="everybody"): """ Greets a person """ result = "Hello " + name + "!")hello("Peter")hello()

OUTPUT:

Hello Peter!Hello everybody!

The Defaults Pitfall

In the previous section we learned about default parameters. Default parameters are quite simple, but quite often programmers new to Python encounter a horrible and completely unexpected surprise. This surprise arises from the way Python treats the default arguments and the effects steming from mutable objects.

Mutable objects are those which can be changed after creation. In Python, dictionaries are examples of mutable objects. Passing mutable lists or dictionaries as default arguments to a function can have unforeseen effects. Programmer who use lists or dictionaries as default arguments to a function, expect the program to create a new list or dictionary every time that the function is called. However, this is not what actually happens. Default values will not be created when a function is called. Default values are created exactly once, when the function is defined, i.e. at compile-time.

Let us look at the following Python function "spammer" which is capable of creating a "bag" full of spam:

def spammer(bag=[]): bag.append("spam") return bag

Calling this function once without an argument, returns the expected result:

spammer()

OUTPUT:

['spam']

The surprise shows when we call the function again without an argument:

spammer()

OUTPUT:

['spam', 'spam']

Most programmers will have expected the same result as in the first call, i.e. ['spam']

To understand what is going on, you have to know what happens when the function is defined. The compiler creates an attribute __defaults__:

def spammer(bag=[]): bag.append("spam") return bagspammer.__defaults__

OUTPUT:

([],)

Whenever we will call the function, the parameter bag will be assigned to the list object referenced by spammer.__defaults__[0]:

for i in range(5): print(spammer()) print("spammer.__defaults__", spammer.__defaults__)

OUTPUT:

['spam']['spam', 'spam']['spam', 'spam', 'spam']['spam', 'spam', 'spam', 'spam']['spam', 'spam', 'spam', 'spam', 'spam']spammer.__defaults__ (['spam', 'spam', 'spam', 'spam', 'spam'],)

Now, you know and understand what is going on, but you may ask yourself how to overcome this problem. The solution consists in using the immutable value None as the default. This way, the function can set bag dynamically (at run-time) to an empty list:

def spammer(bag=None): if bag is None: bag = [] bag.append("spam") return bagfor i in range(5): print(spammer()) print("spammer.__defaults__", spammer.__defaults__)

OUTPUT:

['spam']['spam']['spam']['spam']['spam']spammer.__defaults__ (None,)

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Docstring

The first statement in the body of a function is usually a string statement called a Docstring, which can be accessed with the function_name.__doc__. For example:

def hello(name="everybody"): """ Greets a person """ print("Hello " + name + "!")print("The docstring of the function hello: " + hello.__doc__)

OUTPUT:

The docstring of the function hello: Greets a person 

Keyword Parameters

Using keyword parameters is an alternative way to make function calls. The definition of the function doesn't change. An example:

def sumsub(a, b, c=0, d=0): return a - b + c - dprint(sumsub(12, 4))print(sumsub(42, 15, d=10))

OUTPUT:

817

Keyword parameters can only be those, which are not used as positional arguments. We can see the benefit in the example. If we hadn't had keyword parameters, the second call to function would have needed all four arguments, even though the c argument needs just the default value:

print(sumsub(42,15,0,10))

OUTPUT:

17

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Return Values

In our previous examples, we used a return statement in the function sumsub but not in Hello. So, we can see that it is not mandatory to have a return statement. But what will be returned, if we don't explicitly give a return statement. Let's see:

def no_return(x, y): c = x + yres = no_return(4, 5)print(res)

OUTPUT:

None

If we start this little script, None will be printed, i.e. the special value None will be returned by a return-less function. None will also be returned, if we have just a return in a function without an expression:

def empty_return(x, y): c = x + y returnres = empty_return(4, 5)print(res)

OUTPUT:

None

Otherwise the value of the expression following return will be returned. In the next example 9 will be printed:

def return_sum(x, y): c = x + y return cres = return_sum(4, 5)print(res)

OUTPUT:

9

Let's summarize this behavior: Function bodies can contain one or more return statements. They can be situated anywhere in the function body. A return statement ends the execution of the function call and "returns" the result, i.e. the value of the expression following the return keyword, to the caller. If the return statement is without an expression, the special value None is returned. If there is no return statement in the function code, the function ends, when the control flow reaches the end of the function body and the value None will be returned.

Returning Multiple Values

A function can return exactly one value, or we should better say one object. An object can be a numerical value, like an integer or a float. But it can also be e.g. a list or a dictionary. So, if we have to return, for example, 3 integer values, we can return a list or a tuple with these three integer values. That is, we can indirectly return multiple values. The following example, which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return value is immediately stored via unpacking into the variables lub and sup:

def fib_interval(x): """ returns the largest fibonacci number smaller than x and the lowest fibonacci number higher than x""" if x < 0: return -1 old, new = 0, 1 while True: if new < x: old, new = new, old+new else: if new == x: new = old + new return (old, new) while True: x = int(input("Your number: ")) if x <= 0: break lub, sup = fib_interval(x) print("Largest Fibonacci Number smaller than x: " + str(lub)) print("Smallest Fibonacci Number larger than x: " + str(sup))

OUTPUT:

Largest Fibonacci Number smaller than x: 5Smallest Fibonacci Number larger than x: 8

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Local and Global Variables in Functions

Variable names are by default local to the function, in which they get defined.

def f(): print(s) # free occurrence of s in f s = "Python"f()

OUTPUT:

Python
def f(): s = "Perl" # now s is local in f print(s) s = "Python"f()print(s)

OUTPUT:

PerlPython
def f(): print(s) # This means a free occurrence, contradiction to bein local s = "Perl" # This makes s local in f print(s)s = "Python" f()print(s)

OUTPUT:

---------------------------------------------------------------------------UnboundLocalError Traceback (most recent call last)<ipython-input-25-81b2fbbc4d42> in <module> 6  7 s = "Python"----> 8 f() 9 print(s)<ipython-input-25-81b2fbbc4d42> in f() 1 def f():----> 2 print(s) 3 s = "Perl" 4 print(s) 5 UnboundLocalError: local variable 's' referenced before assignment

If we execute the previous script, we get the error message: UnboundLocalError: local variable 's' referenced before assignment.

The variable s is ambigious in f(), i.e. in the first print in f() the global s could be used with the value "Python". After this we define a local variable s with the assignment s = "Perl".

def f(): global s print(s) s = "dog" print(s) s = "cat" f()print(s)

OUTPUT:

catdogdog

We made the variable s global inside of the script. Therefore anything we do to s inside of the function body of f is done to the global variable s outside of f.

def f(): global s print(s) s = "dog" # globally changed print(s) def g(): s = "snake" # local s print(s) s = "cat" f()print(s)g()print(s)

OUTPUT:

catdogdogsnakedog

Arbitrary Number of Parameters

There are many situations in programming, in which the exact number of necessary parameters cannot be determined a-priori. An arbitrary parameter number can be accomplished in Python with so-called tuple references. An asterisk "*" is used in front of the last parameter name to denote it as a tuple reference. This asterisk shouldn't be mistaken for the C syntax, where this notation is connected with pointers. Example:

def arithmetic_mean(first, *values): """ This function calculates the arithmetic mean of a non-empty arbitrary number of numerical values """ return (first + sum(values)) / (1 + len(values))print(arithmetic_mean(45,32,89,78))print(arithmetic_mean(8989.8,78787.78,3453,78778.73))print(arithmetic_mean(45,32))print(arithmetic_mean(45))

OUTPUT:

61.042502.327538.545.0

This is great, but we have still have one problem. You may have a list of numerical values. Like, for example,

x = [3, 5, 9]

You cannot call it with

 arithmetic_mean(x)

because "arithmetic_mean" can't cope with a list. Calling it with

arithmetic_mean(x[0], x[1], x[2])

OUTPUT:

5.666666666666667

is cumbersome and above all impossible inside of a program, because list can be of arbitrary length.

The solution is easy: The star operator. We add a star in front of the x, when we call the function.

 arithmetic_mean(*x)

OUTPUT:

5.666666666666667

This will "unpack" or singularize the list.

A practical example for zip and the star or asterisk operator: We have a list of 4, 2-tuple elements:

my_list = [('a', 232), ('b', 343), ('c', 543), ('d', 23)]

We want to turn this list into the following 2 element, 4-tuple list:

 [('a', 'b', 'c', 'd'), (232, 343, 543, 23)] 

This can be done by using the *-operator and the zip function in the following way:

list(zip(*my_list))

OUTPUT:

[('a', 'b', 'c', 'd'), (232, 343, 543, 23)]

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Arbitrary Number of Keyword Parameters

In the previous chapter we demonstrated how to pass an arbitrary number of positional parameters to a function. It is also possible to pass an arbitrary number of keyword parameters to a function as a dictionary. To this purpose, we have to use the double asterisk "**"

def f(**kwargs): print(kwargs)
f()

OUTPUT:

{}
f(de="German",en="English",fr="French")

OUTPUT:

{'de': 'German', 'en': 'English', 'fr': 'French'}

One use case is the following:

def f(a, b, x, y): print(a, b, x, y)d = {'a':'append', 'b':'block','x':'extract','y':'yes'}f(**d)

OUTPUT:

append block extract yes

Exercises with Functions

Exercise 1

Rewrite the "dog age" exercise from chapter Conditional Statements as a function.

The rules are:

  • A one-year-old dog is roughly equivalent to a 14-year-old human being
  • A dog that is two years old corresponds in development to a 22 year old person.
  • Each additional dog year is equivalent to five human years.

Exercise 2

Write a function which takes a text and encrypts it with a Caesar cipher. This is one of the simplest and most commonly known encryption techniques. Each letter in the text is replaced by a letter some fixed number of positions further in the alphabet.

What about decrypting the coded text?

The Caesar cipher is a substitution cipher.

23. Functions | Python Tutorial (16)

Exercise 3

We can create another substitution cipher by permutating the alphet and map the letters to the corresponding permutated alphabet.

Write a function which takes a text and a dictionary to decrypt or encrypt the given text with a permutated alphabet.

Exercise 4

Write a function txt2morse, which translates a text to morse code, i.e. the function returns a string with the morse code.

Write another function morse2txt which translates a string in Morse code into a „normal“ string.

The Morse character are separated by spaces. Words by three spaces.

23. Functions | Python Tutorial (17)

Exercise 5

Perhaps the first algorithm used for approximating $\sqrt{S}$ is known as the "Babylonian method", named after the Babylonians, or "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first explicit description of the method.

If a number $x_n$ is close to the square root of $a$ then

$$x_{n+1} = \frac{1}{2}(x_n + \frac{a}{x_n})$$ will be a better approximation.

Write a program to calculate the square root of a number by using the Babylonian method.

Exercise 6

Write a function which calculates the position of the n-th occurence of a string sub in another string s. If sub doesn't occur in s, -1 shall be returned.

Exercise 7

Write a function fuzzy_time which expects a time string in the form hh: mm (e.g. "12:25", "04:56"). The function rounds up or down to a quarter of an hour. Examples:

fuzzy_time("12:58") ---> "13

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Solutions

Solution to Exercise 1

def dog_age2human_age(dog_age): """dog_age2human_age(dog_age)""" if dog_age == 1: human_age = 14 elif dog_age == 2: human_age = 22 else: human_age = 22 + (dog_age-2)*5 return human_ageage = int(input("How old is your dog? "))print(f"This corresponds to {dog_age2human_age(age)} human years!")

OUTPUT:

This corresponds to 37 human years!

Solution to Exercise 2

import stringabc = string.ascii_uppercasedef caesar(txt, n, coded=False): """ returns the coded or decoded text """ result = "" for char in txt.upper(): if char not in abc: result += char elif coded: result += abc[(abc.find(char) + n) % len(abc)] else: result += abc[(abc.find(char) - n) % len(abc)] return resultn = 3x = caesar("Hello, here I am!", n)print(x)print(caesar(x, n, True))

OUTPUT:

EBIIL, EBOB F XJ!HELLO, HERE I AM!

In the previous solution we only replace the letters. Every special character is left untouched. The following solution adds some special characters which will be also permutated. Special charcters not in abc will be lost in this solution!

import stringabc = string.ascii_uppercase + " .,-?!"def caesar(txt, n, coded=False): """ returns the coded or decoded text """ result = "" for char in txt.upper(): if coded: result += abc[(abc.find(char) + n) % len(abc)] else: result += abc[(abc.find(char) - n) % len(abc)] return resultn = 3x = caesar("Hello, here I am!", n)print(x)print(caesar(x, n, True))x = caesar("abcdefghijkl", n)print(x)

OUTPUT:

EBIILZXEBOBXFX-J,HELLO, HERE I AM!-?!ABCDEFGHI

We will present another way to do it in the following implementation. The advantage is that there will be no calculations like in the previous versions. We do only lookups in the decrypted list 'abc_cipher':

import stringshift = 3abc = string.ascii_uppercase + " .,-?!"abc_cipher = abc[-shift:] + abc[:-shift]print(abc_cipher)def caesar (txt, shift): """Encodes the text "txt" to caesar by shifting it 'shift' positions """ new_txt="" for char in txt.upper(): position = abc.find(char) new_txt +=abc_cipher[position] return new_txtn = 3x = caesar("Hello, here I am!", n)print(x)x = caesar("abcdefghijk", n)print(x)

OUTPUT:

-?!ABCDEFGHIJKLMNOPQRSTUVWXYZ .,EBIILZXEBOBXFX-J,-?!ABCDEFGH

Solution to Exercise 3

import stringfrom random import samplealphabet = string.ascii_letterspermutated_alphabet = sample(alphabet, len(alphabet))encrypt_dict = dict(zip(alphabet, permutated_alphabet))decrypt_dict = dict(zip(permutated_alphabet, alphabet))def encrypt(text, edict): """ Every character of the text 'text' is mapped to the value of edict. Characters which are not keys of edict will not change""" res = "" for char in text: res = res + edict.get(char, char) return res# Donald Trump: 5:19 PM, September 9 2014txt = """Windmills are the greatest threat in the US to both bald and golden eagles. Media claims fictional ‘global warming’ is worse."""ctext = encrypt(txt, encrypt_dict)print(ctext + "\n")print(encrypt(ctext, decrypt_dict))

OUTPUT:

OQlerQGGk yDd xVd nDdyxdkx xVDdyx Ql xVd Fz xo hoxV hyGe yle noGedl dynGdk. gdeQy HGyQrk EQHxQolyG ‘nGohyG MyDrQln’ Qk MoDkd.Windmills are the greatest threat in the US to both bald and golden eagles. Media claims fictional ‘global warming’ is worse.

Alternative solution:

import stringalphabet = string.ascii_lowercase + "äöüß .?!\n"def caesar_code(alphabet, c, text, mode="encoding"): text = text.lower() coded_alphabet = alphabet[-c:] + alphabet[0:-c] if mode == "encoding": encoding_dict = dict(zip(alphabet, coded_alphabet)) elif mode == "decoding": encoding_dict = dict(zip(coded_alphabet, alphabet)) print(encoding_dict) result = "" for char in text: result += encoding_dict.get(char, "") return result txt2 = caesar_code(alphabet, 5, txt)caesar_code(alphabet, 5, txt2, mode="decoding")

OUTPUT:

{'a': ' ', 'b': '.', 'c': '?', 'd': '!', 'e': '\n', 'f': 'a', 'g': 'b', 'h': 'c', 'i': 'd', 'j': 'e', 'k': 'f', 'l': 'g', 'm': 'h', 'n': 'i', 'o': 'j', 'p': 'k', 'q': 'l', 'r': 'm', 's': 'n', 't': 'o', 'u': 'p', 'v': 'q', 'w': 'r', 'x': 's', 'y': 't', 'z': 'u', 'ä': 'v', 'ö': 'w', 'ü': 'x', 'ß': 'y', ' ': 'z', '.': 'ä', '?': 'ö', '!': 'ü', '\n': 'ß'}{' ': 'a', '.': 'b', '?': 'c', '!': 'd', '\n': 'e', 'a': 'f', 'b': 'g', 'c': 'h', 'd': 'i', 'e': 'j', 'f': 'k', 'g': 'l', 'h': 'm', 'i': 'n', 'j': 'o', 'k': 'p', 'l': 'q', 'm': 'r', 'n': 's', 'o': 't', 'p': 'u', 'q': 'v', 'r': 'w', 's': 'x', 't': 'y', 'u': 'z', 'v': 'ä', 'w': 'ö', 'x': 'ü', 'y': 'ß', 'z': ' ', 'ä': '.', 'ö': '?', 'ü': '!', 'ß': '\n'}'windmills are the greatest \nthreat in the us to both bald \nand golden eagles. media claims \nfictional global warming is worse.'

Solution to Exercise 4

latin2morse_dict = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.','H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'...--', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ',':'--..--', '.':'.-.-.-', '?':'..--..', ';':'-.-.-', ':':'---...', '/':'-..-.', '-':'-....-', '\'':'.----.', '(':'-.--.-', ')':'-.--.-', '[':'-.--.-', ']':'-.--.-', '{':'-.--.-', '}':'-.--.-', '_':'..--.-'}# reversing the dictionary:morse2latin_dict = dict(zip(latin2morse_dict.values(), latin2morse_dict.keys()))print(morse2latin_dict)

OUTPUT:

{'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '.----': '1', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0', '--..--': ',', '.-.-.-': '.', '..--..': '?', '-.-.-': ';', '---...': ':', '-..-.': '/', '-....-': '-', '.----.': "'", '-.--.-': '}', '..--.-': '_'}
def txt2morse(txt, alphabet): morse_code = "" for char in txt.upper(): if char == " ": morse_code += " " else: morse_code += alphabet[char] + " " return morse_codedef morse2txt(txt, alphabet): res = "" mwords = txt.split(" ") for mword in mwords: for mchar in mword.split(): res += alphabet[mchar] res += " " return resmstring = txt2morse("So what?", latin2morse_dict)print(mstring)print(morse2txt(mstring, morse2latin_dict))

OUTPUT:

... --- .-- .... .- - ..--.. SO WHAT? 

Solution to Exercise 5

def heron(a, eps=0.000000001): """ Approximate the square root of a""" previous = 0 new = 1 while abs(new - previous) > eps: previous = new new = (previous + a/previous) / 2 return newprint(heron(2))print(heron(2, 0.001))

OUTPUT:

1.4142135623730951.4142135623746899

Solution to exercise 6

def findnth(s, sub, n): num = 0 start = -1 while num < n: start = s.find(sub, start+1) if start == -1: break num += 1 return starts = "abc xyz abc jkjkjk abc lkjkjlkj abc jlj"print(findnth(s,"abc", 3))

OUTPUT:

19
def fuzzy_time(time): hours, minutes = time.split(":") minutes = int(minutes) hours = int(hours) minutes = minutes / 60 # Wandlung in Dezimalminutes # Werte in 0.0, 0.25, 0.5, 0.75: minutes = round(minutes * 4, 0) / 4 if minutes == 0: print("About " + str(hours) + " o'clock!") elif minutes == 0.25: print("About a quarter past " + str(hours) + "!") else: if hours == 12: hours = 1 else: hours += 1 if minutes == 0.50: print("About half past " + str ( hours )  +  "!" )  elif  minutes  ==  0.75 :  print ( "About a quarter to "  +  str ( hours )  +  "!" )  elif  minutes  ==  1.00 :  print ( "About "  +  str ( hours )  +  " o'clock!" ) hour  =  "12" for  x  in  range ( 0 ,  60 ,  3 ):  fuzzy_time ( hour  + ":"  +  f " { x : 02d } " )

OUTPUT:

About 12 o'clock!About 12 o'clock!About 12 o'clock!About a quarter past 12!About a quarter past 12!About a quarter past 12!About a quarter past 12!About a quarter past 12!It's about half past one!It's about half past one!It's about half past one!It's about half past one!It's about half past one!About a quarter to 1!About a quarter to 1!About a quarter to 1!About a quarter to 1!About a quarter to 1!About 1 o'clock!About 1 o'clock!

Live Python training

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Upcoming online Courses

Enrol here

23. Functions | Python Tutorial (2024)

FAQs

How to learn functions in Python? ›

In Python, you create a function by using the def keyword. Let's look at an example of this. The def keyword only creates and defines a function. To call the function, use the function name, followed by parentheses.

How do you impress a Python code? ›

  1. Select the Right Built-In Function for the Job. Iterate With enumerate() Instead of range() ...
  2. Leverage Data Structures Effectively. Store Unique Values With Sets. ...
  3. Take Advantage of Python's Standard Library. Handle Missing Dictionary Keys With collections.defaultdict() ...
  4. Conclusion: Coding Interview Superpowers.

How to learn Python coding for beginners? ›

How to Learn Python (Step-By-Step) in 2023
  1. Step 1: Understand Why Most Fail. ...
  2. Step 2: Identify What Motivates You. ...
  3. Step 3: Learn the Basic Syntax, Quickly. ...
  4. Step 4: Make Structured Projects. ...
  5. Step 5: Work on Python Projects on Your Own. ...
  6. Step 6: Keep Working on Harder (and Harder) Projects.
Apr 25, 2023

How long does it take to learn functions in Python? ›

On average, it can take anywhere from five to 10 weeks to learn the basics of Python programming, including object-oriented programming, basic Python syntax, data types, loops, variables, and functions.

What is a function in Python for beginners? ›

Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example: def my_function(): print("Hello From My Function!")

How do I become strong in Python coding? ›

How to Become a Python Developer?
  1. Tip 1: Build Your GitHub Repository. ...
  2. Tip 2: Write Readable Code. ...
  3. Tip 3: Create Proper Documentation. ...
  4. Tip 4: Read Other People's Code Around Your Skill Level. ...
  5. Tip 5: Read books on Python Coding. ...
  6. Tip 6: Grow Your Python Skillset. ...
  7. Tip 7: Master AI and Machine Learning with Python.
Jan 17, 2023

Why do people love Python so much? ›

Python is an open-sourced language, and in recent years has increased in popularity due to its use in data science. Python also has a strong community around machine learning, data modeling, data analysis and artificial intelligence (AI), with extensive resources and libraries built for these purposes.

Can you make money knowing Python? ›

You can make a career as a freelance Python developer. One of the legal ways to earn money using Python expertise is to work as a freelancer. You can earn money by joining any freelancing platform. Freelancing, in particular, gives you an immediate boost in your profession by making you feel special and worthy.

Can I self teach myself Python? ›

Can You Teach Yourself Python? Yes, it's very possible to learn Python on your own. There are many learning resources available on the web to help you learn Python for everything from web development to artificial intelligence.

What is the easiest way to learn Python quickly? ›

11 Beginner Tips for Learning Python Programming
  1. Make It Stick. Tip #1: Code Everyday. Tip #2: Write It Out. ...
  2. Make It Collaborative. Tip #6: Surround Yourself With Others Who Are Learning. Tip #7: Teach. ...
  3. Make Something. Tip #10: Build Something, Anything. Tip #11: Contribute to Open Source.
  4. Go Forth and Learn!

How to learn Python in 30 days? ›

Days 1-9: Introduction to Python
  1. Day 1: Introduction to Python Programming. ...
  2. Day 7: Python Dictionaries. ...
  3. Day 10: Working with External Libraries. ...
  4. Day 16: How to Sort Data in a Pandas DataFrame. ...
  5. Day 22: Data Cleaning and Preparation. ...
  6. Day 24: Plotting in Python with Matplotlib. ...
  7. Day 26: Introduction to Machine Learning in Python.

What is OOPs in Python? ›

OOPs concepts in Python) Object Oriented Programming is a way of computer programming using the idea of “objects” to represents data and methods. It is also, an approach used for creating neat and reusable code instead of a redundant one. the program is divided into self-contained objects or several mini-programs.

What is __ init __ in Python? ›

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What are the most basic Python functions? ›

Q1. What are the most useful functions in Python? Some of the most useful functions in Python are print(), abs(), round(), min(), max(), sorted(), sum(), and len().

What is the hardest programming language to learn? ›

Malbolge. This language is so hard that it has to be set aside in its own paragraph. Malbolge is by far the hardest programming language to learn, which can be seen from the fact that it took no less than two years to finish writing the first Malbolge code.

Can I learn Python in 2 months to get a job? ›

It's possible to learn the basics of Python in two to six months, though this could be much more or much less, depending on how much time you dedicate to learning.

How many hours a day to learn Python? ›

Time devoted to learning:

The answer to how much time it takes to learn python depends on the time you spent learning. Ask yourself how much time you can dedicate to learning and practicing Python. Generally, it is recommended to dedicate one hour every day to Python learning.

How many methods are there in Python? ›

In a Python class, we can define three types of methods: Instance methods. Class methods. Static methods.

What is an example of a function in Python? ›

In Python, standard library functions are the built-in functions that can be used directly in our program. For example, print() - prints the string inside the quotation marks. sqrt() - returns the square root of a number.

What is the salary of Python programmer? ›

The national average salary for a Python Developer is ₹4,50,000 in India.

What is the most difficult thing to learn in Python? ›

Understanding the complexities of OOP, Decorators, Generators, Multithreading, Exception Handling, Regular Expressions, Async/Await, Functional Programming, Meta-Programming, and Network Programming in Python. These are arguably the most difficult concepts to learn with Python.

What is a Python weakness? ›

Some of the disadvantages of Python include its slow speed and heavy memory usage. It also lacks support for mobile environments, database access, and multi-threading. However, it is a good choice for rapid prototyping, and is widely used in data science, machine learning, and server-side web development.

Is Python still relevant 2023? ›

Yes, Python is a programming language worth learning in 2023. Python is an easy-to-learn and versatile language that boosts the coding skills of developers. As per a Statista survey, 48.2 percent of developers worldwide use Python.

Which one is better Python or C++? ›

C++ is faster than Python because it is statically typed, which leads to a faster compilation of code. Python is slower than C++, it supports dynamic typing, and it also uses the interpreter, which makes the process of compilation slower.

What is the future of Python? ›

Moreover, Python web development has the potential of performing various functions ranging from developing a website to managing cloud infrastructures. Machine Learning: Python is a very flexible language and hence is used by Machine Learning Developers to develop machine learning projects.

Do hackers know Python? ›

Hackers can use other scripting languages such as BASH, Perl, and Ruby, but Python has an advantage. The language includes pre-built libraries as well as over 1000 modules. A Python-based tool attacks 77% of all websites on the internet.

Is learning Python alone worth it? ›

Python training is still important. One of the simplest programming languages to learn, Python is flexible and in demand. Python may be used in virtually every area of software development, including machine learning, data science, artificial intelligence (AI), web development, and many more.

What jobs are available if I know Python? ›

Now that you know how easy it can be to learn, here are our top 7 jobs you can get knowing Python:
  • Python Developer. ...
  • Full Stack Developer. ...
  • Data Scientist / Data Analyst. ...
  • Data Engineer. ...
  • Machine Learning Engineer. ...
  • Product Manager. ...
  • Performance Marketer.
Feb 8, 2023

Am I too old to learn Python? ›

Whether you are making a career change or just want to learn something new, it is never too late to start coding!

Can I get a job with Python as a beginner? ›

Yes, getting a job in Python development is a good career move. Python is one of the most popular programming languages in the world. According to Statista, in 2021, Python was the third most popular language in the world, behind JavaScript and HTML/CSS.

Can I study Python in 2 days? ›

You will not be able to master all the fundamentals of Python in any two-day course. However, upon completion of this course, you will be given a direct path towards mastering these fundamentals. Completing this path will earn you a certificate of completion.

How long does it take to learn Python 4 hours a day? ›

Depending on your prior experience, you can learn enough Python relatively quickly that you'll have the ability to work with the language.
...
From Awareness to Ability.
Time RequirementApproximately four months of four hours each day
WorkloadApproximately ten large projects
2 more rows

Can you learn Python in 3 hours? ›

Learn Python in 3 hours is a fast-paced, action-packed course that maximizes your time; it's designed from the ground up to bring you from zero to hero in the shortest time. The course is based on many years of Python development experience in both large enterprises and nimble startups.

How do you become a master in Python? ›

  1. 7 Steps to Mastering Python for Data Science. ...
  2. Step 1: Learn the Fundamentals. ...
  3. Step 2: Practice Coding Challenges. ...
  4. Step 3: Python for Data Analysis. ...
  5. Step 4: Python for Machine Learning. ...
  6. Step 5: Python for Data Collection. ...
  7. Step 6: Projects. ...
  8. Step 7: Build a Portfolio That Stands Out.
Sep 14, 2022

Can I learn Python in 24 hours? ›

Purchase options and add-ons. In just 24 sessions of one hour or less, Sams Teach Yourself Python in 24 Hours will help you get started fast, master all the core concepts of programming, and build anything from websites to games.

Can I learn Python in 5 hours? ›

Description. Learn Python from the beginning and become proficient in 5 hours. Python is easy to learn and this course is hands-on with lots of practice task which allows you solidify your knowledge coding in Python. This course does not require any prior knowledge or specific academic background.

Is Python 100% object-oriented? ›

Python is an object-oriented programming language, but it also supports functional programming. It is, however, intended to prioritize object-based programming.

Why is Python a high-level language? ›

According to Abel, Python is a programming language that is easy to understand and read by humans. “So, it is called high-level programming because it is easy for humans to understand and the coding is also quite easy,” Abel said. Due to this, Python is very popular among programming languages.

What are the 3 pillars of OOPS in Python? ›

What are the four pillars of OOPS in Python?
  • Encapsulation.
  • Inheritance.
  • Polymorphism.
  • Abstraction.

What is main () in Python? ›

The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.

What is polymorphism in Python? ›

❮ Previous Next ❯ The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.

What is a constructor in Python? ›

A constructor is a unique function that gets called automatically when an object is created of a class. The main purpose of a constructor is to initialize or assign values to the data members of that class. It cannot return any value other than none.

What are the 15 list function in Python? ›

  • type() function. For the type() function, it returns the class type of an object. ...
  • append() method. The append() method will add some elements you enter to the end of the elements you specified. ...
  • index() method. ...
  • max() function. ...
  • len() function. ...
  • clear() method. ...
  • insert() method. ...
  • count() method.
Jun 12, 2021

What is the most used command in Python? ›

Some common Python commands are input, print, range, round, pip install, len, sort, loop commands like for and while so on and so forth.

What are the 5 math functions used in Python? ›

For straightforward mathematical calculations in Python, you can use the built-in mathematical operators, such as addition ( + ), subtraction ( - ), division ( / ), and multiplication ( * ). But more advanced operations, such as exponential, logarithmic, trigonometric, or power functions, are not built in.

How many functions are there in Python? ›

There are 68 built-in python functions. These functions perform a specific task and can be used in any program, depending on the requirement of the user. 1 What are Python Functions?

How do you get help in Python for a function? ›

Python help() function

If no argument is given, the interactive help system starts on the interpreter console. If you want to get out of help console, type quit . We can also get the help documentation directly from the python console by passing a parameter to help() function.

How do you do math functions in Python? ›

Learn about all the mathematical functions available in Python and how you can use them in your program.
...
Functions in Python Math Module.
FunctionDescription
pow(x, y)Returns x raised to the power y
sqrt(x)Returns the square root of x
acos(x)Returns the arc cosine of x
asin(x)Returns the arc sine of x
40 more rows

What are the 3 basic functions of Python? ›

Now, let's discuss each of the above functions one-by-one with some examples:
  • print( ) function. The print() function prints the specified message to the screen or another standard output device. ...
  • type( ) function. ...
  • input( ) function. ...
  • abs( ) function. ...
  • pow( ) function. ...
  • dir( ) function. ...
  • sorted( ) function. ...
  • max( ) function.
Jul 8, 2021

How do you list all functions in Python? ›

How to list all functions in a Python module?
  1. Using dir() to get functions in a module. Python dir() function is used to display the names of all the functions and variables present in a module. ...
  2. Using __all__ to get functions in a module. ...
  3. Using inspect to get functions in a module.
Dec 19, 2022

What is loops in Python? ›

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

What is the main function in Python? ›

The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.

How large can an integer in Python be? ›

These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.)

How do you call a function in Python step by step? ›

To call a function in Python, write the function name followed by parentheses. If the function accepts arguments, pass the arguments inside the parentheses as you call the function.

Can we solve equation in Python? ›

The Python package SymPy can symbolically solve equations, differential equations, linear equations, nonlinear equations, matrix problems, inequalities, Diophantine equations, and evaluate integrals.

References

Top Articles
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 5632

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.