Python LEC 8 Functions
Python LEC 8 Functions
Lecture# 8
Lecture Content
1. Introduction to Functions
2. What is Function?
3. Types of Functions in Python
4. How to Create UDFs?
5. Calling a Function
6. Parameters VS Arguments
7. Global VS Local Variables
8. Types of Arguments
9. Word Guessing Game
Introduction to Functions:
What is Function?
A function is a block of code that performs some specific task and only runs when
it is called.
It can be called and reused multiple times. You can pass information/data and it
can send information back as a result.
Types of Functions in Python:
There are three types of functions in Python:
Built-in functions: These are the functions that are predefined in Python
and we can call them such as help() to ask for help, min() to get the
minimum value, print() to print an object to the terminal.
User-Defined Functions (UDFs): These are the functions created by the
user according to their programming needs.
Calling a Function:
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()
Parameters vs Arguments
The argument is the value that is supplied/sent to a function when it is
called.
The parameter is the variable inside the parenthesis in the definition of the
function.
words = ["orange","purple","python","paper","window","apple","mother","father",
"ock","scissors","room","remote","desktop","draw","design","home","horse",
"cat","cake","character","vowel"]
def shuffled_word(word):
list_of_word = list(word)
random.shuffle(list_of_word)
shuffled_word = "".join(list_of_word)
return shuffled_word
def main():
score=0
while True:
user_input = input("Do you want to play? press y/n for yes/no : ")
user_input= user_input.lower() #to make user input in lower case
if user_input == "y":
word = random.choice(words)
user_guess = input("Guess this shuffled word --- {} :
".format(shuffled_word(word)))
if (user_guess == word):
print("Your Guess is Correct")
score+=1
else:
print("Your Guess is wrong")
else:
break
print("****************************************")
print("You get", score, "scores")
print("GoodBye!!!")
main()
Output:
Exercise:
Write a Python function celsius_to_fahrenheit that takes a temperature in Celsius
as input and returns the corresponding temperature in Fahrenheit. The conversion
formula is:
Fahrenheit = (Celsius * 9/5) + 32
Sample Input:
celsius = 25
Sample Output:
77.0