python day 8
python day 8
Day 8
topic – 72
day -10 Goals : what we will make by the end of the day
functions with outputs
build a calculator
topic – 73
Functions with outputs
def camelCase(st):
output = ''.join(x for x in st.title() if x.isalnum())
return output[0].lower() + output[1:]
https://stackoverflow.com/questions/8347048/how-to-convert-string-to-title-case-in-python
We've seen functions with only an execution body, functions with inputs that allow for variation in execution of the
function body and now we'll see the final form of functions. Functions that can have outputs.
PAUSE 1
Create a function called format_name() that takes two inputs: f_name and `l_name'.
PAUSE 2
Use the title() function to modify the f_name and l_name parameters into Title Case.
Syntax
You can create a function with a body, input and output like this:
def function_name(input_parameter):
<body of function that uses input_argument>
return output
Functions terminate at the return keyword. If you write code below the return statement that code will not be executed.
However, you can have multiple return statements in one function. So how does that work?
Conditional Returns
When we have control flow, as in the code will behave differently (go down different execution paths) depending on
certain conditional checks, we can end up with multiple endings (returns).
e.g.
def canBuyAlcohol(age):
if age >= 18:
return True
else:
return False
Empty Returns
You can also write return without anything afterwards, and this just tells the function to exit.
e.g.
def canBuyAlcohol(age):
# If the data type of the age input is not a int, then exit.
if type(age) != int:
return
https://replit.com/@appbrewery/day-10-end#main.py
practice
This is how you work out whether if a particular year is a leap year.
- on every year that is divisible by 4 with no remainder
- except every year that is evenly divisible by 100 with no remainder
- unless the year is also divisible by 400 with no remainder
If English is not your first language, or if the above logic is confusing, try using
this flow chart.
Warning
Your return should be a boolean and match the Example Output format exactly,
including spelling and punctuation.
Example Input 1
2400
Example Return 1
True
Example Input 2
1989
Example Return 2
False
How to test your code and see your output?
def is_leap_year(year): # your code here # Call your function with hard coded
valuesis_leap_year(2024)
topic – 75
Docstrings
You can use docstrings to write multiline comments that document your code.
Syntax
Just enclose your text inside a pair of three double quotes.
e.g.
"""
My
Multiline
Comment
"""
Documenting Functions
A neat feature of docstrings is you can use it just below the definition of a function and that text will be displayed when
you hover over a function call. It's a good way to remind yourself what a self-created function does.
e.g.
def my_function(num):
"""Multiplies a number by itself."""
return num * num
practicecode
quiz
def add(n1 , n2):
return n1 + n2
def subtract(n1 ,n2):
return n1 - n2
def multiply(n1 ,n2):
return n1 / n2
def divide(n1 ,n2 ):
return n1 / n2
print(add(2,multiply(5,divide(8, 4))))
#________________________________________________________________________________
____________________
def outer_function(a,b):
def inner_function(c,d):
return c +d
return inner_function(a,b)
result = outer_function(5,10)
print(result)
#________________________________________________________________________________
________________
def my_function(a):
if a < 40:
return
print("Terrible")
if a < 80:
return "pass"
else:
return "Great"
print(my_function(25))
Demo
https://appbrewery.github.io/python-day10-demo/
my_favourite_calculation = add
my_favourite_calculation(3, 5) # Will return 8
In the starting file, you'll see a dictionary that references each of the mathematical calculations that can be performed by
our calculator. Try it out and see if you can get it to perform addition, subtraction, multiplication and division.
PAUSE 1
TODO: Write out the other 3 functions - subtract, multiply and divide.
PAUSE 2
TODO: Add these 4 functions into a dictionary as the values. Keys = "+", "-", "*", "/"
PAUSE 3
TODO: Use the dictionary operations to perform the calculations. Multiply 4 * 8 using the dictionary.
Functionality
•Program asks the user to type the first number.
•Program asks the user to type a mathematical operator (a choice of "+", "-", "*" or "/")
•Program asks the user to type the second number.
•Program works out the result based on the chosen mathematical operator.
•Program asks if the user wants to continue working with the previous result.
•If yes, program loops to use the previous result as the first number and then repeats the calculation process.
•If no, program asks the user for the fist number again and wipes all memory of previous calculations.
•Add the logo from art.py
Hint 1
Hint 2
To call multiplication from the operations dictionary, you would write your code like this:
https://appbrewery.github.io/python-day10-demo/
import art
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
}
# print(operations["*"](4, 8))
def calculator():
print(art.logo)
should_accumulate = True
num1 = float(input("What is the first number?: "))
while should_accumulate:
for symbol in operations:
print(symbol)
operation_symbol = input("Pick an operation: ")
num2 = float(input("What is the next number?: "))
answer = operations[operation_symbol](num1, num2)
print(f"{num1} {operation_symbol} {num2} = {answer}")
choice = input(f"Type 'y' to continue calculating with {answer}, or type
'n' to start a new calculation: ")
if choice == "y":
num1 = answer
else:
should_accumulate = False
print("\n" * 20)
calculator()
calculator()