Functions Tutorials
1. Using Built-in Functions
Objective: Use functions like print(), len(), type(), and round().
Steps:
1. Create builtin_functions.py:
2. print("Hello!")
3. print(len("Python"))
4. print(type(3.14))
5. print(round(5.678, 2))
2. Importing and Using math Functions
Objective: Use [Link]() and [Link]().
Steps:
1. Create math_functions.py:
2. import math
3. print([Link](2, 3))
4. print([Link](25))
3. Defining a Function without Arguments
Objective: Create a simple function and call it.
Steps:
1. Create simple_function.py:
2. def greetings():
3. print("Hello everyone!")
4.
5. greetings()
4. Creating a Function with Arguments
Objective: Pass data into a function.
Steps:
1. Create function_args.py:
2. def greet(name):
3. print("Hi", name)
4.
5. greet("Ada")
5. Function that Returns a Value
Objective: Use return to output results.
Steps:
1. Create return_function.py:
2. def square(n):
3. return n * n
4.
5. result = square(5)
6. print("Square:", result)
6. Function to Add Two Numbers
Objective: Create a function with two parameters.
Steps:
1. Create add_numbers.py:
2. def add(a, b):
3. return a + b
4.
5. print("Sum:", add(10, 20))
7. Local vs Global Variables
Objective: Understand variable scope.
Steps:
1. Create scope_test.py:
2. x = "global"
3.
4. def test():
5. x = "local"
6. print("Inside:", x)
7.
8. test()
9. print("Outside:", x)
8. Making a Global Variable Inside a Function
Objective: Use global keyword.
Steps:
1. Create global_keyword.py:
2. def define_global():
3. global name
4. name = "Alice"
5.
6. define_global()
7. print("Global name:", name)
9. Circle Area Function
Objective: Define and use a math-based function.
Steps:
1. Create circle_area.py:
2. def circle_area(radius):
3. return 3.14 * radius * radius
4.
5. r = float(input("Enter radius: "))
6. print("Area:", circle_area(r))
10. Calculate Profit Function
Objective: Use input, processing, and return in a function.
Steps:
1. Create calculate_profit.py:
2. def calculateProfit():
3. cost = float(input("Enter cost price: "))
4. sell = float(input("Enter selling price: "))
5. return sell - cost
6.
7. print("Profit:", calculateProfit())