#3 – LEARN PYTHON WITH PRACTICE – Functions

#3 – LEARN PYTHON WITH PRACTICE – Functions

As we saw in the last article, we use functions to do something like print text, count string length, get data type.

In fact, Python offers us as any other programming language a large list of functions that we can use to do amazing things.

Let’s firstly review functions we talked about in the previous article, type(…).

When you write some code lines, that’s a script and it is executed directely when you lunch the program ($ python main.py).

type(…) too is a script in fact, wrote somewhere by some developer and everything you need to use that program inside yours is call that function.

Inside parenthesis we specify some value called parameter or argument.

The argument can be a value (data) or a variable name, for example :

The parameter can also be a call for another function, that’s the case with print(type(user_name)), here the argument of print function is a call to type() function.

I know it’s not clear a much for you … you will understand more at the end of this article, be patient !

Python offers us a large list of functions, we will inctroduce them by next chapters.

Create your own functions

You can create your own function and name it whatever you want, you have just to give it identifier that contains characters from a to z (or A to Z), numbers (0 to 9) and underscore « _ ».

Before start talking about how to create your own function, I’d like to tell you a particular principe or code writing in Python : Indentation.

As I promised you, you will learn everything with practice so, create a new file and name it indentation.py.

Copy and paste in that file the following code

print("Hello, World !")
print("Let's discover indentation in Python")
	print("I think my program has an error, where is it ?")

When you run this program, you will get an error like : IndentationError : unexpexted intend.

The error is coming from the line number 3 because we didn’t respect indentation principe of Python.

This program is running inside the scope of our program (or script), and in every scope, the number of spaces from left of an line should be the same.

Copy and paste the following code in a file named functions.py

 def print_name(name):
 	print("My name is :", name)
    
print_name("Adel")

If you run this script you will get this result : My name is Adel, change Adel to your name and try to understand what is happening.

print_name is a function that we created. To create your functions, you have to use the same syntax like me.

Use the keyword def before your function name, if your function has parameter, write its name inside parenthisis, otherwise just open and close parenthisis ().

Starting from the first line after def and your function name def print(name), all lines of your functions should start with one tabulation.

Tabulation is when you click on tab key in your keyboard (a key with two arrows, one to left and another to right)

The function code ends when a line starts where the function name starts two.

# this is the main program
print("length of 'Hello' is ", len("Hello"))

# creating a function that print pretty text
def pretty_name(name):
	print("Nice to meet you ", name)
    print("I really like your name")
# the pretty_name function ends here
user_name = input("What is your name ? ")
pretty_name(user_name)

Run this program in your computer.

Exercice

Modify the pretty_name function and ask the user for his name inside the function and show the same text, run it !

Please try before seeing the solution

# this is the main program
print("length of 'Hello' is ", len("Hello"))

# creating a function that print pretty text
def pretty_name(name):
	user_name = input("What is your name ? ")
    print("Nice to meet you ", name)
    print("I really like your name")
    
# the pretty_name function ends here
pretty_name()

As you can see in exemple above (the solution), you can understand that the function is a program, so we can create programs inside program. We will see later how create programs in seprate files and use them as you need between each other.

What will happen if write the intruction user_name = input(« What is your name ? « ) before the function and let the rest of the code as it is ?

# this is the main program
print("length of 'Hello' is ", len("Hello"))

# creating a function that print pretty text
user_name = input("What is your name ? ")
def pretty_name(name):
    print("Nice to meet you ", name)
    print("I really like your name")
    
# the pretty_name function ends here
pretty_name()

Run the code above in your computer.

It is still working ? We will see why …

In fact, inside functions you can use variables even if there are not declared inside it.

Another example :

age = 20

def print_age():
	print("Your age is : ", age)

# let's call the print_age function
print_age()

This program will show you : Your age is 20

Variables used inside a function and declared outside it are called Global Variables. Because they can be used inside functions and in the main program.

Variable declared inside function can’t be used in the main program:

def print_age():
	age = 20
    print("Your age is : ", age)

print_age()

print(age) # the error will come from this line, check it!

You will get an error of course, because you tried to use age variable inside the main program and it is declared in the print_age function.

Variables declared inside functions are called Local Variables because they can be used only inside the functions where they are declared.

Functions can return values.

user_name = input("What is your name")

print("Your name is : ", user_name)

In the first line, we created a variable named user_name and we saved the result of input function inside that variable. input function is a program as you knwo and it returns a value, that value is the user input.

def get_user_age():
	user_age = input("What is your age ? ")
    return user_age
    
print(get_user_age())

In your own function, if you want to return a value, just use the keyword return.

Notes :

  • function can return a value only one time
  • the code after return statement will not be executed
def get_user_age():
	user_age = input("What is your age ? ")
    return user_age
    print("Maybe we have the same age !")
print(get_user_age())

The code above will not execute the line after return statement, try it!

How to check if the user has the same age as you ? That’s what we will see in the next chapter : Conditional structures

Thank’s for reading this article, I hope really it helped you, you learn meany things already, keep learning and if you are blocked somewhere, please feel free to tell me in comments, I will answer you 🙂

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *