0% found this document useful (0 votes)
0 views

python day 8

The document outlines a Python programming lesson focused on functions with outputs, including how to create a calculator. It covers topics such as converting strings to Title Case, using multiple return values, and implementing a leap year checker. Additionally, it provides a detailed guide on building a calculator program that performs basic arithmetic operations and allows for continuous calculations.

Uploaded by

Tushar Chandel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

python day 8

The document outlines a Python programming lesson focused on functions with outputs, including how to create a calculator. It covers topics such as converting strings to Title Case, using multiple return values, and implementing a leap year checker. Additionally, it provides a detailed guide on building a calculator program that performs basic arithmetic operations and allows for continuous calculations.

Uploaded by

Tushar Chandel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Python

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

How to convert string to Title Case in


Python?

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

Print vs. Output


Return vs. Display: The return statement is used to give back a value from a function, which can be used later, while print
is used to display a value to the console only for the programmer to see.
def format_name(f_name, l_name):
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"{formated_f_name} {formated_l_name}"
print(format_name("AnGeLa", "YU"))
def function_1(text):
return text + text
def function_2(text):
return text.title()
output = function_2(function_1("hello"))
print(output)

Topic – Multiple return value

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

if age >= 18:


return True
else:
return False

https://replit.com/@appbrewery/day-10-end#main.py
practice

def format_name(f_name, l_name):


if f_name == "" or l_name == "":
return "You did not provide valid inputs"
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"Result: {formated_f_name} {formated_l_name}"
print(format_name(input("What is your first name?"), input("What is your last
name?")))
coading exercise
Leap Year

? This is a difficult challenge! ?ᅡᅠ


Write a program that returns True or False whether if a given year is a leap
year.
A normal year has 365 days, leap years have 366, with an extra day in
February. The reason why we have leap years is really fascinating, this
video does it more justice

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.

e.g. The year 2000:


2000 ÷ 4 = 500 (Leap) 2000 ÷ 100 = 20 (Not Leap) 2000 ÷ 400 = 5 (Leap!)
So the year 2000 is a leap year.

But the year 2100 is not a leap year because:


2100 ÷ 4 = 525 (Leap) 2100 ÷ 100 = 21 (Not Leap) 2100 ÷ 400 = 5.25 (Not Leap)

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?

Udemy coding exercises do not have a console, so you cannot use


the input() function. You will need to call your function with hard-coded values
like so:

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

def format_name(f_name, l_name):


"""Take a first and last name and format it to return the
title case version of the name."""
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"{formated_f_name} {formated_l_name}"
formatted_name = format_name("AnGeLa", "YU")
length = len(formatted_name)

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))

Topic 76 – The calculator Project

The goal is to build a calculator program.

Demo
https://appbrewery.github.io/python-day10-demo/

Storing Functions as a Variable Value


You can store a reference to a function as a value to a variable. e.g.

def add(n1, n2):


return n1 + n2

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

Try writing out a flowchart to plan your program.

Hint 2

To call multiplication from the operations dictionary, you would write your code like this:

result = operations["*"](n1= 5, n2= 3)

result would then be equal to 15.

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()

You might also like