0% found this document useful (0 votes)
18 views

Function Python

Uploaded by

antomjonas3
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Function Python

Uploaded by

antomjonas3
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

A function is a block of organized code that performs a single task and only runs when called.

You can pass data, known as parameters, into a function. A function can return data as a
result. (They provide reusability of code)

Creating a Function

In Python a function is defined using the def keyword:

def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

my_function()

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:

Arguments are often shortened to args in Python documentations.

Example

def say _hello(fname):


print(“hello ", fname)

say _hello ("Emil")


say _hello("Tobias")
say _hello ("Linus")
LAMBDA

In Python, a lambda function is a single-line, anonymous function, that can have any number
of arguments, but it can only have one expression.

A lambda function is a small anonymous function.

A lambda function can take any number of arguments but only have one expression.

Syntax

lambda arguments: expression

The expression is executed and the result is returned:

Example

This function:

>>> def add(x, y):

... return x + y

...

>>> add(5, 3)

#8

Is equivalent to the lambda function:

>>> add = lambda x, y: x + y

>>> add(5, 3) # 8
Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:


Return Values

When creating a function using the def statement, you can specify what the return value
should be with a return statement. A return statement consists of the following:

 The return keyword.

 The value or expression that the function should return.

def sum_two_numbers(number_1, number_2):

return number_1 + number_2

result = sum_two_numbers(7, 8)

print(result)

# 15

Local and Global Scope


 Code in the global scope cannot use any local variables.

 However, a local scope can access global variables.

 Code in a function’s local scope cannot use variables in any other local scope.

 You can use the same name for different variables if they are in different scopes. That
is, there can be a local variable named spam and a global variable also named spam.

global_variable = 'I am available everywhere'

>>> def some_function():

... print(global_variable) # because is global

... local_variable = "only available within this function"


... print(local_variable)

...

>>> # The following code will throw error because

>>> # 'local_variable' only exists inside 'some_function'

>>> print(local_variable)

Traceback (most recent call last):

File "<stdin>", line 10, in <module>

NameError: name 'local_variable' is not defined

The Tuple data type

Tuples vs Lists

The key difference between tuples and lists is that,


while tuples are immutable objects, lists are mutable. This means that
tuples cannot be changed while the lists can be modified. Tuples are
more memory efficient than the lists.

>>> furniture = ('table', 'chair', 'rack', 'shelf')

>>> furniture[0]

# 'table'

>>> furniture[1:3]

# ('chair', 'rack')
>>> len(furniture)

#4

The main way that tuples are different from lists is that tuples, like
strings, are immutable.

Converting between list() and tuple()

>>> tuple(['cat', 'dog', 5])

# ('cat', 'dog', 5)

>>> list(('cat', 'dog', 5))

# ['cat', 'dog', 5]

>>> list('hello')

# ['h', 'e', 'l', 'l', 'o']

Python Dictionaries

In Python, a dictionary is an ordered collection of key: value pairs.

From the Python 3 documentation

The main operations on a dictionary are storing a value with some key and extracting the
value given the key. It is also possible to delete a key:value pair with del.
Example Dictionary:

my_cat = {

'size': 'fat',

'color': 'gray',

'disposition': 'loud'

Set key, value using subscript operator []

>>> my_cat = {

... 'size': 'fat',

... 'color': 'gray',

... 'disposition': 'loud',

... }

>>> my_cat['age_years'] = 2

>>> print(my_cat)

...

# {'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'age_years': 2}

Get value using subscript operator []

In case the key is not present in dictionary KeyError is raised.

>>> my_cat = {

... 'size': 'fat',

... 'color': 'gray',

... 'disposition': 'loud',

... }

>>> print(my_cat['size'])
...

# fat

>>> print(my_cat['eye_color'])

# Traceback (most recent call last):

# File "<stdin>", line 1, in <module>

# KeyError: 'eye_color'

values()

The values() method gets the values of the dictionary:

>>> pet = {'color': 'red', 'age': 42}

>>> for value in pet.values():

... print(value)

...

# red

# 42

keys()

The keys() method gets the keys of the dictionary:

>>> pet = {'color': 'red', 'age': 42}

>>> for key in pet.keys():

... print(key)

...

# color

# age

There is no need to use .keys() since by default you will loop through keys:

>>> pet = {'color': 'red', 'age': 42}


>>> for key in pet:

... print(key)

...

# color

# age

items()

The items() method gets the items of a dictionary and returns them as a Tuple:

>>> pet = {'color': 'red', 'age': 42}

>>> for item in pet.items():

... print(item)

...

# ('color', 'red')

# ('age', 42)

Using the keys(), values(), and items() methods, a for loop can iterate over the keys, values,
or key-value pairs in a dictionary, respectively.

>>> pet = {'color': 'red', 'age': 42}

>>> for key, value in pet.items():

... print(f'Key: {key} Value: {value}')

...

# Key: color Value: red

# Key: age Value: 42

get()

The get() method returns the value of an item with the given key. If the key doesn’t exist, it
returns None:

>>> wife = {'name': 'Rose', 'age': 33}


>>> f'My wife name is {wife.get("name")}'

# 'My wife name is Rose'

>>> f'She is {wife.get("age")} years old.'

# 'She is 33 years old.'

>>> f'She is deeply in love with {wife.get("husband")}'

# 'She is deeply in love with None'

You can also change the default None value to one of your choice:

>>> wife = {'name': 'Rose', 'age': 33}

>>> f'She is deeply in love with {wife.get("husband", "lover")}'

# 'She is deeply in love with lover'

Adding items with setdefault()

It’s possible to add an item to a dictionary in this way:

>>> wife = {'name': 'Rose', 'age': 33}

>>> if 'has_hair' not in wife:

... wife['has_hair'] = True

Using the setdefault method, we can make the same code more short:

>>> wife = {'name': 'Rose', 'age': 33}

>>> wife.setdefault('has_hair', True)

>>> wife

# {'name': 'Rose', 'age': 33, 'has_hair': True}


Removing Items

pop()

The pop() method removes and returns an item based on a given key.

>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}

>>> wife.pop('age')

# 33

>>> wife

# {'name': 'Rose', 'hair': 'brown'}

popitem()

The popitem() method removes the last item in a dictionary and returns it.

>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}

>>> wife.popitem()

# ('hair', 'brown')

>>> wife

# {'name': 'Rose', 'age': 33}

del()

The del() method removes an item based on a given key.

>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}

>>> del wife['age']

>>> wife

# {'name': 'Rose', 'hair': 'brown'}

clear()

Theclear() method removes all the items in a dictionary.

>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}


>>> wife.clear()

>>> wife

# {}

Checking keys in a Dictionary

>>> person = {'name': 'Rose', 'age': 33}

>>> 'name' in person.keys()

# True

>>> 'height' in person.keys()

# False

>>> 'skin' in person # You can omit keys()

# False

Checking values in a Dictionary

>>> person = {'name': 'Rose', 'age': 33}

>>> 'Rose' in person.values()

# True

>>> 33 in person.values()

# True

Pretty Printing

>>> import pprint


>>> wife = {'name': 'Rose', 'age': 33, 'has_hair': True, 'hair_color': 'brown', 'height': 1.6,
'eye_color': 'brown'}

>>> pprint.pprint(wife)

# {'age': 33,

# 'eye_color': 'brown',

# 'hair_color': 'brown',

# 'has_hair': True,

# 'height': 1.6,

# 'name': 'Rose'}

Merge two dictionaries

>>> dict_a = {'a': 1, 'b': 2}

>>> dict_b = {'b': 3, 'c': 4}

>>> dict_c = {**dict_a, **dict_b}

>>> dict_c

# {'a': 1, 'b': 3, 'c': 4}

Python Sets

Share

Python comes equipped with several built-in data types to help us organize our data. These
structures include lists, dictionaries, tuples and sets.

A set is an unordered collection with no duplicate elements. Basic uses include membership
testing and eliminating duplicate entries.

Initializing a set

There are two ways to create sets: using curly braces {} and the built-in function set()

Empty Sets
When creating set, be sure to not use empty curly braces {} or you will get an empty
dictionary instead.

>>> s = {1, 2, 3}

>>> s = set([1, 2, 3])

>>> s = {} # this will create a dictionary instead of a set

>>> type(s)

# <class 'dict'>

Unordered collections of unique elements

A set automatically remove all the duplicate values.

>>> s = {1, 2, 3, 2, 3, 4}

>>> s

# {1, 2, 3, 4}

And as an unordered data type, they can’t be indexed.

>>> s = {1, 2, 3}

>>> s[0]

# Traceback (most recent call last):

# File "<stdin>", line 1, in <module>

# TypeError: 'set' object does not support indexing

set add and update

Using the add() method we can add a single element to the set.

>>> s = {1, 2, 3}

>>> s.add(4)

>>> s

# {1, 2, 3, 4}
And with update(), multiple ones:

>>> s = {1, 2, 3}

>>> s.update([2, 3, 4, 5, 6])

>>> s

# {1, 2, 3, 4, 5, 6}

set remove and discard

Both methods will remove an element from the set, but remove() will raise a key error if the
value doesn’t exist.

>>> s = {1, 2, 3}

>>> s.remove(3)

>>> s

# {1, 2}

>>> s.remove(3)

# Traceback (most recent call last):

# File "<stdin>", line 1, in <module>

# KeyError: 3

discard() won’t raise any errors.

>>> s = {1, 2, 3}

>>> s.discard(3)

>>> s

# {1, 2}

>>> s.discard(3)

set union

union() or | will create a new set with all the elements from the sets provided.
>>> s1 = {1, 2, 3}

>>> s2 = {3, 4, 5}

>>> s1.union(s2) # or 's1 | s2'

# {1, 2, 3, 4, 5}

set intersection

intersection() or & will return a set with only the elements that are common to all of them.

>>> s1 = {1, 2, 3}

>>> s2 = {2, 3, 4}

>>> s3 = {3, 4, 5}

>>> s1.intersection(s2, s3) # or 's1 & s2 & s3'

# {3}

set difference

difference() or - will return only the elements that are unique to the first set (invoked set).

>>> s1 = {1, 2, 3}

>>> s2 = {2, 3, 4}

>>> s1.difference(s2) # or 's1 - s2'

# {1}

>>> s2.difference(s1) # or 's2 - s1'

# {4}

set symmetric_difference

symmetric_difference() or ^ will return all the elements that are not common between them.

>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}

>>> s1.symmetric_difference(s2) # or 's1 ^ s2'

# {1, 4}

You might also like