8000 Functions · dsabhrawal/python-examples@cf5e03c · GitHub
[go: up one dir, main page]

Skip to content

Commit cf5e03c

Browse files
committed
Functions
1 parent a5fca5c commit cf5e03c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Functions/Functions.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Function is a piece of code of sequence of statements
2+
# Function is executed when it is called
3+
# Function works strictly with indentation
4+
# Function may or may not return a value
5+
# Function can have zero or more arguments passed
6+
# Function has to be defined before using it
7+
# Example:
8+
# def addition(a,b):
9+
# return a+b
10+
#
11+
# Calling function addition(2,4)
12+
# Multiple parameters can be passed.
13+
# Example: def my_fun(*a)
14+
# my_fun(1,2) or my_fun(3,4,5,6)
15+
16+
# Function without a body is defined as
17+
def do_nothing():
18+
pass
19+
20+
do_nothing() # Calling function
21+
22+
# Print sum of two numbers
23+
def sum(a,b):
24+
return a+b
25+
26+
x = sum(2,3) #Calling function and assign value to x
27+
print(x) #Prints 5
28+
29+
#Multiple Parameters
30+
def do_multiply(*a):
31+
result = 1
32+
for i in a:
33+
print(type(a)) #prints <class 'tuple'> a is a tuple here
34+
result *=i
35+
return result
36+
37+
print(do_multiply(2,4)) #Prints 8
38+
print(do_multiply(3,'Hi')) #Prints HiHiHi
39+
40+
41+
# Keyword argument to paas the values
42+
43+
def ex_keyword_arg(a,b,c):
44+
print('Value of a:',a)
45+
print('Value of b:',b)
46+
print('Value of c:',c)
47+
print('Sum of abc: ', (a+b+c))
48+
49+
ex_keyword_arg(2,4,5) #a=2, b=4, c=5 and sum is 11
50+
ex_keyword_arg(2,c=4,b=5) #a=2, b=5 , c=4 and sum is 11
51+
52+
# Function with default argument values
53+
def ex_default_arg(a,b=2,c=6):
54+
print('Value of a:',a)
55+
print('Value of b:',b)
56+
print('Value of c:',c)
57+
print('Sum of abc: ', (a+b+c))
58+
59+
ex_default_arg(2) # sum of abc: 10
60+
ex_default_arg(2,5) # sum of abc: 13 (5 is assigned to b)

0 commit comments

Comments
 (0)
0