This topic contains 0 replies, has 1 voice, and was last updated by  utterz 2 months, 3 weeks ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #717

    utterz
    Keymaster

    In this post we will be looking at how to create and create different functions in python.

    Here is some commented code to help you better understand how functions work.

     

    #continue (Important for functions)
    NumberTaken = [2, 5,12,20,19] #this creates a list of numbers
    print("Here are the number that are still available")
    for n in range (1, 20):
        if n in NumberTaken: #Checks to see if number in N is in list or not.
            continue #Continue means if statement true goes back to the start of the loop
        print(n) #If number is not in list then prints.
    
    #functions
    def apple(): #def is used to define new function
        print("Hello world!")
    apple() #this runs apple function else nothing would happen.
    def pounds_to_usd (pounds): #You can create a variable inside () for example pounds
        amount = pounds * 2 #you can then use this variable to do calculations
        print(amount) #Prints amount calculated
    pounds_to_usd (4) #You can then add a number to the pounds variable within the () when calling the function. It will then use this number when running the function.
    pounds_to_usd (8) #Runs the function again but uses 8*2 instead of 4*2 in the function.
    #Function with a variable containing a default value
    def get_gender(sex ='unknown'): #this creates a function get gender with the default value of sex set as unknown
        if sex is 'm': #This if statement checks to see if is get_gender('m')
            sex = "male" #if is true then sets sex as male
        elif sex is 'f': #checks to see if get_gender('f')
            sex = "female" #if true then then set sex as female
        print(sex)
    get_gender('m')
    get_gender('f')
    get_gender() #this calls function with no value to sex variable this means that default value unknown will be used as opposed to doing nothing.
    
    #Variable scope
    a = 3454654 #if variable outside of function then all functions can use it, however if variable is contained within a function only the function that it is contained in can use that variable.
    def apple():
        print (a)
    def orange():
        print(a)
    apple()
    orange()
    
    #keyword arguments
    def silly_sentence(name="james", action='ate', item='cheese'): #creates a function with variables named name, action and item with default strings values attached.
        print(name, action, item) #prints variables name action and item with there passed value or default value
    silly_sentence() #uses function as is without any changes
    silly_sentence('Bill', 'smells', 'funny') #passes in strings to the variables of the function in order
    .silly_sentence(item='grapes')#pass in limited arguments or in different order then need to use keyword or variable instead.
    #Flexible Number of Arguments
    ef add_number(*args):#creates a bunch of keyword arguments without knowing how many arguments needed. For example a user can input as many as they want and python will use them all without having to list each and every variable argument in the function.
        total = 0
        for a in args:
            total += a
        print(total)
    add_number(3) #passing just one number argument to function
    add_number(3,444) #passing just two arguments to function
    add_number(2334,43,59,8958,2,349,89,9,33,2394) #sends tons of different arguments to function at once.
    
    #unpacking arguments
    def health_calculator(fruit, veg, age, cigs_smoked): #creates a function with arguments fruit, veg age and cigs smoked
        answer =(100-age) + (fruit + veg * 3.5) -(cigs_smoked * 2) #this creates an answer based upon how old you are adding extra points for number of fruit and veg you eat and taking away points if smoke cigs
        print(answer)
    james_health = [24, 8, 8, 0]
    health_calculator(james_health[0],james_health[1],james_health[2],james_health[3]) #this is the slow way where you pass in the argument values one by one
    health_calculator(*james_health)#type name of list and add * before to unpack argument list. Takes the list and passes each item in one at a time. So no need to keep on typing out each argument after each other.
    #creating a set
    groceries ={'bread','pasta', 'beer', 'pizza', 'fruit', 'beer'}
    print (groceries) #beer is listed twice but python thinks this is pointless so will only print beer once!
    if 'pasta' in groceries:#checks to see if you have pasta in your list
        print("pasta is in the list! no need to add again!") #if you have pasta display message
    else:
        print("No pasta in list you need pasta!") #if no pasta in list then print message saying you need pasta!
    
    #what's a dictionary keys and values. Not limited to just words but also numbers
    classmates = {'peter ':'boring and dull','James ':'Really cool dude','Lucy ':'Smells really bad'}#dictionary has keys and values. In this case the key is the name and the value is something about that person.
    for k, v in classmates.items(): #this is a for loop that uses variables k and v (which stands for keys and values)
        print(k + v) #This prints the key and value.
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.