Function Python
Function Python
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
def my_function():
print("Hello from a function")
Calling a Function
my_function()
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:
Example
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 can take any number of arguments but only have one expression.
Syntax
Example
This function:
... return x + y
...
>>> add(5, 3)
#8
>>> add(5, 3) # 8
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
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:
result = sum_two_numbers(7, 8)
print(result)
# 15
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.
...
>>> print(local_variable)
Tuples vs Lists
>>> 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.
# ('cat', 'dog', 5)
# ['cat', 'dog', 5]
>>> list('hello')
Python Dictionaries
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'
>>> my_cat = {
... }
>>> my_cat['age_years'] = 2
>>> print(my_cat)
...
>>> my_cat = {
... }
>>> print(my_cat['size'])
...
# fat
>>> print(my_cat['eye_color'])
# KeyError: 'eye_color'
values()
... print(value)
...
# red
# 42
keys()
... print(key)
...
# color
# age
There is no need to use .keys() since by default you will loop through keys:
... print(key)
...
# color
# age
items()
The items() method gets the items of a dictionary and returns them as a Tuple:
... 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.
...
get()
The get() method returns the value of an item with the given key. If the key doesn’t exist, it
returns None:
You can also change the default None value to one of your choice:
Using the setdefault method, we can make the same code more short:
>>> wife
pop()
The pop() method removes and returns an item based on a given key.
>>> wife.pop('age')
# 33
>>> wife
popitem()
The popitem() method removes the last item in a dictionary and returns it.
>>> wife.popitem()
# ('hair', 'brown')
>>> wife
del()
>>> wife
clear()
>>> wife
# {}
# True
# False
# False
# True
>>> 33 in person.values()
# True
Pretty Printing
>>> pprint.pprint(wife)
# {'age': 33,
# 'eye_color': 'brown',
# 'hair_color': 'brown',
# 'has_hair': True,
# 'height': 1.6,
# 'name': 'Rose'}
>>> dict_c
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}
>>> type(s)
# <class 'dict'>
>>> s = {1, 2, 3, 2, 3, 4}
>>> s
# {1, 2, 3, 4}
>>> s = {1, 2, 3}
>>> s[0]
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
# {1, 2, 3, 4, 5, 6}
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)
# KeyError: 3
>>> 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}
# {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}
# {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}
# {1}
# {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}
# {1, 4}