def function_name(arguments):
write commands indented
this is second command
return is optional keyword that is used at the end to return results
And this is the regular code outside function
#Example:
#Let's take the above example and write code for it first:
# Taking input from user:
number1 = int(input("Please enter first number: "))
number2 = int(input("Please enter second number: "))
print(f"The sum of numbers {number1} and {number2} is {number1+number2} ")
# Lets now covert the above code into a function
def get_sum(): #Notice I have not added anything in parenthesis. We'lll discuss it later
number1 = int(input("Please enter first number: "))
number2 = int(input("Please enter second number: "))
print(f"The sum of numbers {number1} and {number2} is {number1+number2} ")
# To call a function, we write its name followed by the parenthesis
get_sum()
def function_name(value_to_be_passed_1,value_to_be_passed_2):
sum = value_to_be_passed_1 + value_to_be_passed_2
# Example:
def get_sum(number1,number2):
print(f"The sum of numbers {number1} and {number2} is {number1+number2} ")
#Now, calling function and passing the values:
get_sum(2,1)
#Example:
#Lets try to create a funciton that returns the division of two integers
def get_division(number1,number2):
print(number2/number1)
get_division(2,1)
get_division(1,2)
# Challenge:
# Create a program, that prints the table of any number inputted by a user.
# User also tells how many rows to print.
def create_table(number,rows):
for i in range(1,rows+1):
print(f"{number} X {i} = {i*number}")
create_table(4,10)
#You can pass annything as argument.
# You can pass an array, a character, a string, a number, anything as argument.
# Lets try a function that gets marks of 5 exams as a list, name of person, his roll number and his GPA and prints all the information
def print_details(marks,name,roll_num,gpa):
print(f"Name: {name}\nMarks: {marks}\nRoll Number: {roll_num}\nGPA: {gpa}")
print_details([2,3,4,5,6],"Ahsan",24442,3.11)
#What if you dont pass a value?
#Here I have removed GPA value and it gave me an error.
print_details([2,3,4,5,6],"Ahsan",24442)
# To overcome this, we can simply add a default value in our function parameters
def print_details(marks,name,roll_num = 12345,gpa = 2.00):
print(f"Name: {name}\nMarks: {marks}\nRoll Number: {roll_num}\nGPA: {gpa}")
print_details(marks=34,roll_num=122,gpa=3.1,name="Ahsan")
print("\n")
print_details(34,122,3.1,"Ahsan")
print("\n")
print_details(34,"ahsan",roll_num=122,gpa=3.1)
#Now, instead of giving error, it gives out a default value.
print_details([2,3,4,5,6],"Ahsan")
#you can also specify the name of parameter when calling function
#this is helpful for the fact that
print_details(name="Ahsan",marks=[2,3,4,5,6])
#TO get any function's parameter names, we can use following command. Replace the print_details with your function name.
print_details.__code__.co_varnames
def print_details(marks,name,roll_num = 12345,gpa = 2.00):
print(f"Name: {name}\nMarks: {marks}\nRoll Number: {roll_num}\nGPA: {gpa}")
print_details(marks=34,roll_num=122,gpa=3.1,name="Ahsan")
print("\n")
print_details(34,122,3.1,"Ahsan")
print("\n")
print_details(34,"ahsan",roll_num=122,gpa=3.1)
def function_name(winner, score, **other_information)
#Example
#Lets get a person's profile and print it. Name and age is must while other things he can optionally add.
def biodata(name,age,**other_information):
print("Name: ",name)
print("Age: ",age)
print(other_information)
for key,value in other_information.items():
print(key+" : "+str(value))
# You can see how the other_information creates a dictionary itself.
# You can either use the for loop to display all values one at a time or you can simply print them all by printing the variable
biodata(name="ahsan",age=12,gender="male",city="Islamabad")
def sumoflist(listname):
sumofnumber = 0
for i in listname:
sumofnumber+=i
return sumofnumber
listofnumbers = [1,2,3,4,5,6,7,8]
totalsum = sumofnumbers(listofnumbers)
print(totalsum)
#Example: Finding sum of lists and returning
def sumoflist(listname):
sumofnumber = 0
for i in listname:
sumofnumber+=i
return sumofnumber
listname = [1,2,3,4,5,6,7,8,9,10]
totalsum = sumofnumbers(listname)
print(totalsum)
#Example. write a program that takes cost price as argument, calculates 17% tax on it and returns the final sale price.
#Then take input from user and return him the value using function call.
def salepricecalculator(costprice):
saleprice = costprice + 0.17*costprice
return saleprice
costprice = float(input("Enter Cost Price"))
print(f"The saleprice of Rs. {costprice} is Rs. {salepricecalculator(costprice)}")
#Notice in this example, we used the salepricecalculator directly in our print function because it is returning a value that we can directly print.
#Here function call acts just like a variable bearing a value calculated.
#Example, Write a program that gets a number and returns a list of top 10 multiples of that number.
#Print the list using for loop with number and its multiple value.
def top10multiples(value):
multiples = []
for i in range(1,11):
multiples.append(value*i)
return multiples
value = 10
for i in top10multiples(value):
print(value,i)
#Example, Write a function that returns a boolean value True if the number is even and false otherwise
#Then use this as a condition in if-else and print in following format:
# Number --> Even or Number --> Odd
def evenorodd(value):
if(value%2==0):
return True
else:
return False
if(evenorodd(7)):
print("Even")
else:
print("Odd")
#Example, modify above function so thhat now, there is no if-else statement inside the function.
def evenorodd(value):
return value%2==0
if(evenorodd(7)):
print("Even")
else:
print("Odd")
# Get a temperature in degress celcius, convert to fahrenheit and kelvin and return both temperatures.
def temp_convert(celcius):
fahrenheit = ((9/5)*celcius) + 32
kelvin = celcius + 273
return fahrenheit,kelvin #Notice here how I returned both values comma-separated.
#Now, at reading, instead of assigning one variable, I can assign 2 variables and the values will be passed accordingly.
# Like in this example f will have fahrenheit's value and k will have kelvin value
f,k = temp_convert(45)
print(f)
print(k)
#Example:
# modify upper example so that now, the user is in command of which value he needs. He may pass a value conversion_type: K for kelvin and F for fahrenheit.
# convrert accordingly.
def temp_convert(celcius,conversion_type="K"): #By default we set Kelvin.
if(conversion_type=="K"):
return celcius + 273
elif (conversion_type=="F"):
return ((9/5)*celcius) + 32
else:
print("ERROR! Check conversion Type and retry...")
print(temp_convert(32)) #No conversion type passed.
print(temp_convert(32,"K")) #kelvin
print(temp_convert(32,"F")) #Fahrenheit
temp_convert(32,"P") #Any other value
Example:
def some_function():
this_variable = "Hi"
print(this_variable)
In the upper example, this_variable is defined inside the function. Hence it will not be accessible from outside the function and once we execute the print statement, it will generate error "NameError: name 'this_variable' is not defined"
However, if we define the variable outside function, then we may be able to access it inside the function as well as outside it.
that_variable = ""
def some_function():
that_variable = "Hello"
print(that_variable)
def some_function1():
this_variable = "Hi"
print(this_variable)
that_variable = "a$5%5%"
def some_function2():
that_variable = "Hello"
print("from inside: ", that_variable)
print("from outside: ", that_variable) #It will still give a blank as the function is not called.
some_function2()
print("from outside after calling function: ", that_variable)
# lets create the main function first:
def main(username, userage, userlocation,usereyesight):
name_valid = validate_name(username) # We took data from user and passed it to validate_name function that responded with a True/False value which we stored in a name_valid function.
age_valid = validate_age(userage)
location_valid = validate_location(userlocation)
eyesight_valid = validate_eyesight(usereyesight)
print_result([name_valid,age_valid,location_valid,eyesight_valid])
# See how easy our main function has become now. in only 5 lines, we are able to call complete function. You can find definitions of each of these functions below.
# See the main function above before looking these functions.
def validate_name(username):
valid_names = ["Ahsan","Ali","Saqib","Dawood","Razzaque","Alina","Ayesha","Hira"]
if(username in valid_names):
return True
else:
return False
def validate_age(userage):
if(userage>=18):
return True
else:
return False
def validate_location(userlocation):
if((userlocation=="Pakistan")| (userlocation=="PK")):
return True
else:
return False
def validate_eyesight(usereyesight):
if(usereyesight>=4):
return True
else:
return False
def print_result(validate):
lookups = ["Your Name is Not Valid","Your Age is not Valid","Your Location is not valid","your eyesight is not valid"]
reasons = [lookups[x[0]] for x in enumerate(validate) if x[1]==False]
if(len(reasons)>0):
print("You are not eligible due to following reasons:")
for x,i in enumerate(reasons):
print(x+1,"-",i)
else:
print("Congrats! you have successfully applied for license")
print("Attempt - 1")
main("Ajaia",18,"Pakistan",5)
print("\nAttempt - 2")
main("Ahsan",17,"India",5)
print("\nAttempt - 3")
main("Ahsan",18,"PK",6)
#While Loop Example.
#Lets create a loop that takes values from user and prints them until the user presses q button
data = ""
while(data!='q'):
data = input("Enter a value")
print(data)
#Example
#Using above example, now take numeric data for students. if the user inputs -1, break the loop and then print the average of the numbers already
marks = [] #initialized a list
value = 0 #initialized a value
while(value!=-1):
value = int(input("Enter marks or -1 to exit: "))
if(value!=-1):
marks.append(value)
average = sum(marks)/len(marks)
print(average)
#Example:
#A user gets $1000 in his account. unless his account is zero or he presses -1, the session terminates and balance is shown.
#It's obvious that if the balance is less than the inputted amount, the amount must be rejected.
balance = 1000
amount = 0
while((balance>0) & (amount!=-1)):
amount = int(input(f"Enter Amount. You currently have ${balance}: "))
if(amount<=balance):
if(amount>=0):
balance = balance-amount
else:
print("Inputted amount is more than the balance")
print(f"Thank you for transactions, Your available balance is: {balance} ")
# further, you can check for a condition without user's input and cancel the loop as well.
# For example, Lets create a pattern from stars that looks like following:
*
* *
* * *
* * * *
* * *
* *
*
# So for this we will break our while loop into two parts
# One part will take care of increasing triangle and other will take care of decreasing triangle.
#we create two separate loops for each area. First to tackle the top triangle and second to create bottom triangle.
#In each loop, see how nested while loops are entering aesteriks and next lines
#Dry run these and you'll have better understanding.
row = 0
while(row<=3):
count = 0
while(count<=row):
print("*",end=" ")
count = count + 1
print("\n")
row = row + 1
row = 2
while(row>=0):
count = 0
while(count<=row):
print("*",end=" ")
count = count + 1
print("\n")
row = row - 1