Python Functions
Python Functions
input, functions, and conditions. By the end of this lesson you will be able
to identify the parts of a basic function in python.
Python Variables
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even
change type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with
casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
User Input
Python allows for user input.
The following example asks for the username, and when you entered the
username, it gets printed on the screen:
Python 3.6
username = input("Enter username:")
print("Username is: " + username)
Python Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
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
def my_function(fname):
print(fname + " Marulanda")
my_function("Oscar")
my_function("Marla")
my_function("Gustavo")
Explaining a process:
● First, we…
● Second, we…
● Then, we…
● Then, we…
● …
● Finally, we…
Exercise:
Find out how to use conditions in python and write a function
that receives one argument as user input and then decides if the
person is old enough to drink or not. Then, use the vocabulary from this
lesson to give a brief explanation of your code.