Skip to article frontmatterSkip to article content

Basics of Functions

Kaggle

print("Hello World!")
Hello World!
def add_three(input): # add_three() - user difined function
    output = input + 3
    if output < 15:
        print("smaller than 20")
    else:
        print("larger than 20")
    return output

result = add_three(20)
print(result)

larger than 20
23

Basics of Functions

  1. A Funtion is a reusable block of code that performs a specific task.

  2. Defined using the def keyword.

  3. Parameter: variable in function defination.

  4. kaggel image.png

  5. Aurgument: value passed to the function when calling it.

  6. return statement

Swift function

func greet(_ person: String, on day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")

Swift code

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)
// Prints "11"
def happy_birthday():
    print("happy birthday to you!")
    print("may god bless you!")
    print()

happy_birthday()
happy_birthday()
happy birthday to you!
may god bless you!

happy birthday to you!
may god bless you!

def add(a, b):
    return a + b

print(add(9, 14))
23
def display(name, age):
    print(name, age)

display(age=18, name="Hansika")
Hansika 18
x = -92
print(x)
print(type(x))
-92
<class 'int'>
deci_point = 92.5897554565655635
print(deci_point)
print(type(deci_point))
92.58975545656557
<class 'float'>
print(99 > 100)
print(type(99 > 100))
False
<class 'bool'>
# Example for "if" condition:
def evaluate_temp(temp):
    # Set an initial message
    message = "Normal temperature."
    # Update value of message only if temperature greater than 38
    if temp > 38:
        message = "Fever!"
    return message

Conditions and Conditional statements

Common symbols to construct conditions

  Symbol	Meaning
==	equals
!=	does not equal
<	less than
<=	less than or equal to
>	greater than
>=	greater than or equal to

Important Note: When you check two values are equal, make sure you use the == sign, and not the = sign.

var_one==1 checks if the value of var_one is 1, but var_one=1 sets the value of var_one to 1.

def average_marks(marks):
    #initial message for the above function
    message = "Fail!"
    #update value of message when the marks are higher than 27
    if marks > 27:
        message = "Pass!"
    return message

print(average_marks(19))
print(average_marks(58))
Fail!
Pass!
def average_marks_with_else(marks):
    if marks > 27:
        message = "Pass!"
    else: 
        message = "Fail!"
    return message

print(average_marks_with_else(14))
print(average_marks_with_else(68))
Fail!
Pass!

Example - Calculations

In this next example, say you live in a country with only two tax brackets. Everyone earning less than 12,000 pays 25% in taxes, and anyone earning 12,000 or more pays 30%. The function below calculates how much tax is owed.

def get_taxes(earnings):
    if earnings < 12000:
        tax_owed = .25 * earnings
    else:
        tax_owed = .30 * earnings
    return tax_owed

The next code cell uses the function.

ana_taxes = get_taxes(9000)
bob_taxes = get_taxes(15000)

print(ana_taxes)
print(bob_taxes)

The Answer:

2250.0 4500.0

Example - Multiple “elif” statements

For instance, the next block of code calculates the dose of medication (in milliliters) to give to a child, based on weight (in kilograms).

def get_dose(weight):
    # Dosage is 1.25 ml for anyone under 5.2 kg
    if weight < 5.2:
        dose = 1.25
    elif weight < 7.9:
        dose = 2.5
    elif weight < 10.4:
        dose = 3.75
    elif weight < 15.9:
        dose = 5
    elif weight < 21.2:
        dose = 7.5
    # Dosage is 10 ml for anyone 21.2 kg or over
    else:
        dose = 10
    return dose

The next code cell runs the function. Make sure that the output makes sense to you!

In this case, the “if” statement was False, and all of the “elif” statements evaluate to False, until we get to weight < 15.9, which is True, and dose is set to 5. Once an “elif” statement evaluates to True and the code block is run, the function skips over all remaining “elif” and “else” statements. After skipping these, all that is left is the return statement, which returns the value of dose. The order of the elif statements does matter here! Re-ordering the statements will return a very different result.

The Answer:

print(get_dose(12))

5

Fruits = "Cherry, Plum, Avocado, Tomato, Kiwi, Pineapple, Passion fruit, Lychee"
print(type(Fruits))
print(Fruits)

#Fruits in list
Fruits_list = ["Cherry", "Plum", "Avocado", "Tomato", "Kiwi", "Pineapple", "Passion fruit", "Lychee"]
print(type(Fruits_list))
print(Fruits_list)

#Length of the Fruits_list
print(len(Fruits_list))

#Indexing
print("First entry:", Fruits_list[0])
print("Second entry:", Fruits_list[1])
print("Last entry:", Fruits_list[7])

#Slicing
print("First four entries:", Fruits_list[:4])
print("Last one entry:", Fruits_list[-1:])

#Removing items
Fruits_list.remove("Tomato")
print(Fruits_list)

#Adding items
Fruits_list.append("Blueberry")
print(Fruits_list)
<class 'str'>
Cherry, Plum, Avocado, Tomato, Kiwi, Pineapple, Passion fruit, Lychee
<class 'list'>
['Cherry', 'Plum', 'Avocado', 'Tomato', 'Kiwi', 'Pineapple', 'Passion fruit', 'Lychee']
8
First entry: Cherry
Second entry: Plum
Last entry: Lychee
First four entries: ['Cherry', 'Plum', 'Avocado', 'Tomato']
Last one entry: ['Lychee']
['Cherry', 'Plum', 'Avocado', 'Kiwi', 'Pineapple', 'Passion fruit', 'Lychee']
['Cherry', 'Plum', 'Avocado', 'Kiwi', 'Pineapple', 'Passion fruit', 'Lychee', 'Blueberry']

Lists

Introduction: When doing data science, you need a way to organize your data so you can work with it efficiently. Python has many data structures available for holding your data, such as lists, sets, dictionaries, and tuples. In this tutorial, you will learn how to work with Python lists.

Length

We can count the number of entries in any list with len(), which is short for “length”. You need only supply the name of the list in the parentheses.

Indexing

We can refer to any item in the list according to its position in the list (first, second, third, etc). This is called indexing.

Note that Python uses zero-based indexing, which means that:

to pull the first entry in the list, you use 0, to pull the second entry in the list, you use 1, and to pull the final entry in the list, you use one less than the length of the list.

Slicing

You can also pull a segment of a list (for instance, the first three entries or the last two entries). This is called slicing. For instance:

to pull the first x entries, you use [:x], and to pull the last y entries, you use [-y:].

Removing items

Remove an item from a list with .remove(), and put the item you would like to remove in parentheses.

Adding items

Add an item to a list with .append(), and put the item you would like to add in parentheses.

Lists are not just for strings

Lists can have items with any data type, including booleans, integers, and floats.
  *You can also get the minimum with min() and the maximum with max().
  *To add every item in the list, use sum().
  *You can actually use Python to quickly turn this string into a list with .split(). In the parentheses, we need to provide the character should be used to mark the end of one list item and the beginning of another, and enclose it in quotation marks. In this case, that character is a comma. For example: print(flowers.split(","))