Monstera

Functions

Jan 10th, 2023 (edited)
1,104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. # define a function
  2. def my_function():
  3.     print("Hello in my function")
  4.  
  5.  
  6. my_function()  # function call
  7.  
  8.  
  9. # define a function with parameters
  10. def say_hello(name, name2):  # 'name' is a parameters
  11.     print("Hello " + name + " and " + name2)
  12.  
  13.  
  14. say_hello("Ola", "Artur")  # 'Ola' and 'Artur' are arguments
  15.  
  16.  
  17. # define a function with parameters and keywords!
  18. def say_hi(name3, name2, name1):  # 'name1', 'name2' and 'name3' are keywords
  19.     print("Hello " + name1 + ", " + name2 + " and " + name3)
  20.     print("I like the first person so much " + name1)
  21.  
  22.  
  23. say_hi(name2="Ania", name1="Hania", name3="Kasia")
  24.  
  25.  
  26. # define a function with type hint
  27. def person_(name: str, age: int):  # ': str' and ': int' are type hints
  28.     print("Name: " + name)
  29.     print("Age: " + str(age))
  30.  
  31.  
  32. person_("Ola", 18)
  33.  
  34.  
  35. def greet_people(people: list) -> list:  # '-> list[str]' you can find sth like that too
  36.     return [f"Hello {person}! How are you doing today?" for person in people]
  37.  
  38.  
  39. result = greet_people(["James", "Matthew", "Claire"])
  40.  
  41. for item in result:
  42.     print(item)
  43.  
  44.  
  45. # function aliasing
  46. def fruits(fruit: str):
  47.     print(f"I like {fruit}")
  48.  
  49.  
  50. food = fruits  # the same function, but with another name
  51.  
  52. print("ID of food " + str(id(food)))
  53. print(f"ID of fruits {id(fruits)}")
  54.  
  55. fruits("apple")
  56. food("apple")
  57.  
Advertisement
Add Comment
Please, Sign In to add comment