Bertelsmann Tech Scholarship Challenge, Python, Udacity

Python Functions

We have already used some functions, such as the print() function.

Functions have brackets after their name. This is where we supply arguments separated by commas. Some functions don’t need arguments.

The print function takes in arguments.

print("Hello world!")

There are many functions in Python, but we can also create our own.

To create a function we start off with the def keyword.

def greet(name):
   print("Hello, {}!".format(name))

greet("Claudia")

-> Hello, Claudia!

This is a simple function that prints out a greeting.

When we create or use a function that does not require any arguments, we still put empty brackets after it’s name like:

my_function()

The is executed when the function is called, not when the function is first defined.

In code a function call is just he functions name followed by parentheses with the arguments in between the parentheses.

Return Values and Return Statements

When we use the len() function and pass it an argument such as “Claudia”. The function returns an integer such as 6. We can build our functions to return a value, and not just print it to the console window.

Our function needs to use the return keyword and the value or expression that the function should return.

def multiply(x, y):
   return(x*y)

square_area = multiply(8, 10)
print(square_area)

-> 80

 

Local and Global Scope

Variables that are created inside a function are said to exist in that function’s local scope. What that means is that a variable created inside a function cannot be used outside of the function.

def sum_of_nums(num):
   sum = 0
   for x in range( num):
      sum += x
   print( sum)

sum_of_nums(10)
--> 45

print(sum)
-> error

 

A variable that is created outside of the body of the function is knows as a global variable. This variable can be used in the function but it cannot be changed in the function

sum = 0
def sum_of_nums(num):
   for x in range( num):
      sum += x
   print( sum)

sum_of_nums(10)
--> error

We could reference the number we declare such as this

age = 18
def sum_of_nums(num):
   sum = 0
   for x in range( num):
      sum += x
   print( sum)

sum_of_nums(age)
--> 153
Bertelsmann Tech Scholarship Challenge Course – Data Track Nanodegree Program. Lesson 24: Videos 1 – 7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s