Skip to content

Commit 20faaee

Browse files
author
Rai Muhammad Haider
committed
Function
1 parent 6220588 commit 20faaee

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

Functions.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
# Function with default parameter
2+
def default_parameter(city='Lahore'):
3+
print(city, 'is Your city')
4+
5+
default_parameter('Okara')
6+
7+
8+
# Function with unknown number of positional arguments (*args)
9+
def unknown_parameters(*name):
10+
print('The name of the winner is', name[1])
11+
12+
unknown_parameters('Ali', 'Haider', 'Hafiz')
13+
14+
15+
# Function with keyword arguments
16+
def my_function(child3, child2, child1):
17+
print("The youngest child is", child1)
18+
19+
my_function(child1="Emil", child2="Tobias", child3="Linus")
20+
21+
22+
# Passing a dictionary to a function
23+
students = {
24+
'name': 'Ali',
25+
'age': 21,
26+
}
27+
28+
def passing_dict(info):
29+
for key in info:
30+
print(key, ':', info[key])
31+
32+
passing_dict(students)
33+
34+
35+
# Basic function returning square
36+
def square(number):
37+
return number ** 2
38+
39+
print(square(9))
40+
41+
42+
# Function for multiplication
43+
def multiply(q, w):
44+
return q * w
45+
46+
print(multiply(8, 2))
47+
print(multiply('a', 2))
48+
print(multiply(2, 'a'))
49+
50+
51+
# Function to calculate area and circumference of a circle
52+
import math
53+
54+
def circle(radius):
55+
area = math.pi * (radius ** 2)
56+
circumference = 2 * math.pi * radius
57+
return area, circumference
58+
59+
a, c = circle(3)
60+
print('Area:', round(a, 2), 'Circumference:', round(c, 2))
61+
62+
63+
# Function with default greeting
64+
def default_greeting(greet='Good morning'):
65+
print('Hey Sir!', greet)
66+
67+
default_greeting()
68+
69+
70+
# Lambda function (anonymous function)
71+
cube = lambda x: x ** 3
72+
print(cube(2))
73+
74+
75+
# Sum using *args
76+
def sum_all(*args):
77+
return sum(args)
78+
79+
print(sum_all(2, 4, 5, 2))
80+
81+
82+
# Function with keyword arguments (**kwargs)
83+
def print_kwargs(**kwargs):
84+
for key, value in kwargs.items():
85+
print(f"{key}: {value}")
86+
87+
print_kwargs(name='Ali', age=21, power='Lazer')
88+
89+
90+
# Generator function using yield
91+
def even_generator(limit):
92+
for i in range(2, limit + 1, 2):
93+
yield i
94+
95+
for num in even_generator(10):
96+
print(num)
97+
98+
99+
# Recursive function to calculate factorial
100+
def factorial(n):
101+
if n == 0:
102+
return 1
103+
else:
104+
return n * factorial(n - 1)
105+
106+
print(factorial(4))

0 commit comments

Comments
 (0)