-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions_intro.py
More file actions
51 lines (43 loc) · 1.39 KB
/
functions_intro.py
File metadata and controls
51 lines (43 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
demo of a function for help in understanding the online textbook
FUNCTION - a named sequence of statements that belong together and accomplish a task.
The syntax for a function definition is:
def name( parameters (optional) ):
statements
return statement(optional)
"""
# FUNCTION DEFIITION - creating your own function
import random
def roll(sides):
"""rolls a sides-sided die and returns the resulting value"""
num = random.randint(1,sides)
return num # returns a value and ends function execution
# using (CALLING) our new function
print(roll(6))
print(roll(6))
print(roll(12))
print(roll(12))
# example 2
def calc_grade(percentage):
"""takes in a percentage and returns the appropriate letter grade"""
if(percentage >= 90):
letter_grade = "A"
# this overchecks the value of percentage
# We know that percentage must be < 90 if the
# elif is executed.
#elif(percentage >= 80 and percentage < 90):
elif(percentage >= 80):
letter_grade = "B"
elif(percentage >= 70):
letter_grade = "C"
elif(percentage >= 60):
letter_grade = "D"
else:
letter_grade = "F"
# return keyword returns a value from the function, ending the function's execution
return letter_grade
# using (CALLING) our new function
grade1 = calc_grade(85)
grade2 = calc_grade(91)
print("Grade 1", grade1)
print("Grade 2", grade2)