Calling a function that's inside another function from a function - python

To be more specific, I want to call the function get_hours_worked from inside
calc_gross_pay. I realize that another way to do this is to just pass arguments into calc_gross_pay, but I was wondering if what I was trying to do is possible. I have a feeling it's not. Thanks for any help.
def main():
#
print("This employee's gross pay for two weeks is:",calc_gross_pay())
def get_input():
def get_hours_worked():
#get_hours_worked
x = float(input("How many hours worked in this two week period? "))
return x
def get_hourly_rate():
#get_hourly_rate()
y = float(input("What is the hourly pay rate for this employee? "))
return y
def calc_gross_pay():
#
gross = get_input(get_hours_worked) * get_input(get_hourly_rate)
return gross
main()

Here's a reorganized version of your code. Rather than defining get_hours_worked and get_hourly_rate inside get_input we define them as separate functions that call get_input.
def get_input(prompt):
return float(input(prompt))
def get_hours_worked():
return get_input("How many hours worked in this two week period? ")
def get_hourly_rate():
return get_input("What is the hourly pay rate for this employee? ")
def calc_gross_pay():
return get_hours_worked() * get_hourly_rate()
def main():
print("This employee's gross pay for two weeks is:", calc_gross_pay())
main()
demo
How many hours worked in this two week period? 50
What is the hourly pay rate for this employee? 20.00
This employee's gross pay for two weeks is: 1000.0

As PM 2Ring pointed out, its better to change the hierarchy itself. But in case you want the same still, proceed as follows :
def get_input():
def get_hours_worked():
x = float(input("How many hours worked in this two week period? "))
return x
def get_hourly_rate():
y = float(input("What is the hourly pay rate for this employee? "))
return y
return get_hours_worked, get_hourly_rate # IMP
def calc_gross_pay():
call_worked, call_rate = get_input() # get the functions
gross = call_worked() * call_rate() # call them
return gross
def main():
print("This employee's gross pay for two weeks is:",calc_gross_pay())
#How many hours worked in this two week period? 3
#What is the hourly pay rate for this employee? 4
#This employee's gross pay for two weeks is: 12.0
main()

Related

How do I replicate this try/except for all other inputs in the code?

How do I replicate the same try/except you see for the first input in every other input?
import math
import sys
import time
while True:
try:
Money = float(input("How much are you depositing?"))
except:
print("please enter numbers")
continue
AIR = float(input("What is the annual interest rate?"))
#Annual Interest Rate
n = int(input("How many times a year do you want the interst compounded for?"))
# number of times the interst compounds
t = int(input("How many years are you investing/borrowing the money?"))
# total number of years the money is being invested/borrowed for
CCI = Money *(1+AIR/n)**(n*t)
# Calculated Compound Interest
print(math.trunc(CCI));
# main program
Extract that logic into a function which you can then reuse:
def read(type_, prompt): # using "type_" not to shadow built-in "type"
while True:
try:
return type_(input(prompt))
except (TypeError, ValueError):
print("Please enter a {}".format(type_.__name__))
Money = read(float, "How much are you depositing?\n")
AIR = read(float, "What is the annual interest rate?\n")
n = read(int, "How many times a year do you want the interst compounded for?\n")
t = read(int, "How many years are you investing/borrowing the money?\n")
CCI = Money *(1+AIR/n)**(n*t)
print(math.trunc(CCI))
you can add them in the same try-except or write multiple times. if you do it in same you will be having the same error message but If you write multiple try-except then you can have different error messages
import math
import sys
import time
while True:
try:
Money = float(input("How much are you depositing?"))
n = int(input("How many times a year do you want the interst compounded for?"))
# number of times the interst compounds
t = int(input("How many years are you investing/borrowing the money?"))
AIR = float(input("What is the annual interest rate?"))
#Annual Interest Rate
except:
print("please enter numbers")
continue
# total number of years the money is being invested/borrowed for
CCI = Money *(1+AIR/n)**(n*t)
# Calculated Compound Interest
print(math.trunc(CCI));
# main program
You can do something like this:
app.py
while True:
try:
Money = float(input("How much are you depositing?"))
AIR = float(input("What is the annual interest rate?"))
#Annual Interest Rate
n = int(input("How many times a year do you want the interst compounded for?"))
# number of times the interst compounds
t = int(input("How many years are you investing/borrowing the money?"))
# total number of years the money is being invested/borrowed for
CCI = Money *(1+AIR/n)**(n*t)
# Calculated Compound Interest
print(math.trunc(CCI));
# main program
break
except:
print("please enter numbers")money?"))
The break tells python to get out of the loop
so if the code reaches break it means that it didn't throw any exceptions and that it is indeed a number
You put all your calculations in the try block so that it throws an exception when there's a mistake

Why is my function not getting called properly?

I'm writing a program that will greet somebody (given name) and then ask them how many hours they worked and how much their hourly pay is. The program runs but is not spitting back the correct math. I'm getting this for my answer... you earned<function wage at 0x00EA9540>
I have already tried calling payment but not getting an answer with that either.
def greet(greeting):
name = input("Hi, whats your name?")
return greeting + name
print(greet ("Hey "))
hourly = input("How much is your hourly wage?")
hours = input("How many hours did you work this week?")
def wage(hourly, hours):
if hours > 40:
payment = 40 * hourly
payment = payment + hourly * (hours-40) * 1.5
return payment
else:
return hours * hourly
print("you earned" + str(wage))
You missed the parameters to the wage function.
in your case, it just prints the memory address of the function wage...
you need to change the print call with the correct parameters to the wage function:
print("you earned" + str(wage(hourly, hours)))
You need to call the wage function with the parameters:
print("you earned" + str(wage(hourly, hours)))
Otherwise you are simply printing the string representation of the wage function object, and that doesn't really make much sense.

How to add interest to a bank account balance once a month?

I have to create a bankaccount class that has functions such as: deposit, withdraw, getbalance; all that beginner stuff. All very easy and I finished it no problem. However, there is a function called Interest that takes in an interest_rate where I am running into a lot of trouble. To explain, this function is supposed to add interest per the user's request only once a month to the balance of the bankaccount. So let's say I decide to add 5% interest on today's date (Oct 13) to my balance. The function would execute and spit out my new balance. Then let's say I want to add 10% interest the next day (Oct 14th), the function would not execute and would spit out something like "Cannot add interest until Nov.1", which is the first of the next month. On Nov.1, if I tried to add 10% interest, I would succeed and then if on Nov. 2 I tried to add interest again, it would say "Cannot add interest until Dec.1" so on and so forth. I'm having a very hard time with this. Below is the code that I wrote, however it would not only ever execute because the date will always be ahead a month, but it would also always add interest to the balance.
Here's what I have so far, but it's a mess. Anyone have any tips on what I should do? I know it's not inside a function the way it's supposed to be in the assignment but I thought I would figure out the main picture of the program first and then worry about incorporating it into the rest of my class.
from datetime import *
from dateutil.relativedelta import *
rate = 0.10
balance = 1000.00 # i just made up a number for the sake of the code but the
# balance would come from the class itself
balancewInterest = rate*balance
print(balancewInterest)
# this is where I'm having the most trouble
todayDate = date.today()
print(todayDate)
todayDay = todayDate.day
todayMonth = todayDate.month
if todayDay == 1: # if it's the first of the month, just change the month
# not the day
nextMonth = todayDate + relativedelta(months=+1)
else: # if not the 1st of the month, change day to 1, and add month
nextMonth = todayDate + relativedelta(months=+1, days=-(todayDay-1))
print(nextMonth)
difference = (todayDate - nextMonth)
print(difference.days)
if todayDate >= nextMonth: # add interest only when it's the first of the next
# month or greater
interestPaid = rate*balance
print(interestPaid)
else:
print("You can add interest again in " + str(abs(difference.days)) \
+ " days.")
I have now completed how to do it.
import datetime
import os
import time
x = datetime.datetime.now()
try:
s = open("Months.txt","r")
ss = s.read()
s.close()
except IOError:
s = open("Months.txt","w")
s.write("Hello:")
s.close()
try:
Mo = open("Deposit and interest.txt","r")
Mon = Mo.read()
Mo.close()
except IOError:
Deposit = input("How much do you wish to deposit")
M = open("Deposit and interest.txt","w")
M.write(Deposit)
M.close()
s1 = open("Months.txt","r")
s2 = s1.read()
s1.close()
Mone = open("Deposit and interest.txt","r")
Money = Mone.read()
Mone.close()
if s2 != x.strftime("%B"):
Rate = input("How much interest do you want?")
Deposit1 = int(Money)/int(100)
Deposit2 = Deposit1*int(Rate)
Deposit = int(Money) + int(Deposit2)
print("Calculation of interest")
time.sleep(2)
print("The final total is: "+str(Deposit))
os.remove("Months.txt")
file_one=open("Months.txt","w")
file_one.write(x.strftime("%B"))
file_one.close()
os.remove("Deposit and interest.txt")
file_one=open("Deposit and interest.txt","w")
file_one.write(str(Deposit))
file_one.close()
print("Used up this month, try again next month")
else:
print("Sorry, you have used this months intrest limit, try again next month")
def calculate_interest(amount_deposited, time):
rate_of_interest = 5
int rest = (amount_deposited*time*rate)
return int rest
print(calculate_interest(1000, 2))
''' for eg: here 1000 is the amount deposited and for 2 years at the rate of interest 5.'''

How to give an error msg based on user input in my program?

So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work correctly.
I've tried something like:
hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.
An optimized version of #JamesRusso code :
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = int(input("Enter the watts of appliance, or total watts of appliances"))
hours = int(input("Enter the number of hours that appliance(s) run per day"))
# Check that the hours number is good before getting to the cost
while (hours > 24) or (hours < 0):
print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
hours = int(input("Enter the number of hours that appliance(s) run per day "))
cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
# We don't need an auxiliary variable x here
total = (watts * hours / 1000.0 * 30) * cost
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
if __name__ == '__main__':
playagain = 'yes'
while playagain == 'yes':
main()
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
# Checking that the user's input is whether yes or no
while playagain not in ['yes', 'no']:
print "It's a yes/no question god damn it"
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
I put your error message in an if statment, and the calculation code in an else. This way it won't do the calculation when the hour isn't correct and instead will exit main and go back to the while loop and ask the user if they will like to play again. Also as other user's have pointed out following what I did below you should add more error testing and messages for negative numbers, etc.
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
My python skills are a little rusty, but when I have to do stuff like checking input, I usually use a structure something like this:
hours = 0
while True:
hours = input("How many hours per day? ")
#first make sure they entered an integer
try:
tmp = int(hours) #this operaion throws a ValueError if a non-integer was entered
except ValueError:
print("Please enter an integer")
continue
#2 checks to make sure the integer is in the right range
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
continue
if hours < 1:
print("Enter a positive integer")
continue
#everything is good, bail out of the loop
break
Basically, it starts by going into an 'infinite' loop. It gets the input, goes through all the checks to see if it is valid, and hits the break (leaving the loop) if everything went okay. If the data was bad in any way, it informs the user and restarts the loop with the continue. hours = 0 is declared outside the loop so it is still accessible in the scope outside, so it can be used elsewhere.
Edit: adding an idea to the example code that I thought of after seeing #Ohad Eytan's answer
The input you get from the user is a string type, but you compare it to int type. That's an error. You should cast the string to int first:
hours = int(input("How many hours per day? "))
# ----^---
Then you can do something like:
while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
If you don't sure the user will input a number you should use a try/catch statemant.
Except from this you should validate you indent the code correctly

Python car sales code issue

Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))

Categories