A function is just specific peace of code that will do one thing, and do it well. Think about them as workers that will do only one task.
We can write our own functions, or we can grab them from Internet because they are distributed in dedicated files - modules.
When we install Python, we have at our disposal dedicated modules, with many functions.
Don't forget parentheses and def
keyword when creating functions:
def my_function():
print("Line 1")
print("Line 2")
print("Line 3")
my_function()
Result:
Line 1
Line 2
Line 3
>>>
Our custom triple()
function can call multiple times other functions, in this case we are calling function my_function()
three times:
def my_function():
print("Line 1")
print("Line 2")
print("Line 3")
def triple():
my_function()
my_function()
my_function()
triple()
Result:
Line 1
Line 2
Line 3
Line 1
Line 2
Line 3
Line 1
Line 2
Line 3
>>>
This is how to create function that will ask for IP so we can Ping it with other function that is in os module:
import os
def ping_something():
x = input("Enter IP: ")
os.system("ping " + x)
ping_something()
We can have loops inside functions, too:
def while_in_function():
x = 0
while x < 3:
print(x)
x = x + 1
while_in_function()
Result:
0
1
2
>>>
This is how to have while loop inside function that will have option to stop if you enter "QUIT":
def get_out():
while True:
x = input("Enter something: ")
print(x)
if x == "QUIT":
break
get_out()
Result:
Enter something: Something
Something
Enter something: Again
Again
Enter something: QUIT
QUIT
>>>
So far so good. In next tutorial we will learn how to provide some data to functions, so functions can grab it and do something with data we provided.
No comments:
Post a Comment