I am about a week into Python. I have looked at various other questions regarding this, and have grown fairly frustrated that my attempts to implement those suggestions are falling flat.
I have tried a few means of passing variables through, based on things I have read. For example (this isn't necessarily representative of a coherent attempt... I have tried many variations and have had to walk back to get code worth posting):
def verify_nums():
globhours = hours
globrate = rate
try:
globhours = float(globhours)
globrate = float(globrate)
return globhours,globrate
except:
print("You must provide numbers")
def calc():
globhours = globhours
globrate = globrate
if globhours > 40:
base = 40 * globrate
ot = (globhours - 40) * (globrate * 1.5)
pay = base + ot
print(pay)
else:
pay = globrate * globhours
print(pay)
hours = input("Enter hours worked: ")
rate = input("Enter hourly rate: ")
verify_nums()
calc()
I am supremely confused on how to transfer the hours and rate variables over to the calc() function.
I eventually figured out I could just merge these into one function...
def paycalc(hours,rate):
etc.
etc.
hours = input("Enter hours: ")
hours = input("Enter hours: ")
paycalc(hours,rate)
But for the sake of learning, I really want to get this global/local thing figured out.
Thanks for the help!
You seem to be trying to get Python to guess which functions are supposed to be global and which local based on their names. Python doesn't do that. If you assign to a variable in a function, and you want that assignment to be global, you need a global statement at the top of the function:
def verify_nums():
global globhours
global blograte
globhours = hours
globrate = rate
# ...
Also, globhours = globhours doesn't do anything useful—and, in fact, it causes a problem. If you global globhours in that function as well, the statement is meaningless. Without that, you're creating a local variable, and assigning it… the value of that local variable that doesn't exist yet.
Anyway, if you add the right global declarations to all of your functions, they will work, but it won't be a great design.
You really don't need any global variables here. If you think about values rather than variables, everything gets a lot easier.
Your verify_nums function needs to work on two values. So just pass those values in as parameters. And it needs to return two values—that's easy, you already did that part.
Now the caller has to store those two values that it returned, so it can pass them to the calc function. Which can also take two values as parameters.
Putting that all together:
def verify_nums(hours, rate):
try:
numhours = float(hours)
numrate = float(rate)
return numhours, numrate
except:
print("You must provide numbers")
def calc(hours, rate):
if hours > 40:
base = 40 * rate
ot = (hours - 40) * (rate * 1.5)
pay = base + ot
print(pay)
else:
pay = rate * hours
print(pay)
globhours = input("Enter hours worked: ")
globrate = input("Enter hourly rate: ")
hours, rate = verify_nums(globhours, globrate)
calc(hours, rate)
One problem left: what happens if there's an error with the user's input? Inside verify_nums, you handle the error with an except:, then you print a message and do nothing. That means you return None. So, when the caller tries to do hours, rate = None, it's going to get an error, which you're not handling. And you can't just carry on without values. What can you do?
More generally "return a pair of numbers, or return None" is a confusing contract for a function to fulfill. How do you use that function? With a whole lot of ugly type-checking. But "return a pair of numbers, or raise an exception" is a perfectly good contract. How do you use that function? With a simple try.
That's why it's better to put the exception handling in exactly the right place where you can deal with it. You want to skip calling calc if there's an error, so the except has to be where you call calc.
def verify_nums(hours, rate):
numhours = float(hours)
numrate = float(rate)
return numhours, numrate
def calc(hours, rate):
if hours > 40:
base = 40 * rate
ot = (hours - 40) * (rate * 1.5)
pay = base + ot
print(pay)
else:
pay = rate * hours
print(pay)
try:
globhours = input("Enter hours worked: ")
globrate = input("Enter hourly rate: ")
hours, rate = verify_nums(globhours, globrate)
except ValueError:
print("You must provide numbers")
else:
calc(hours, rate)
Another improvement you might want to consider: Have calc return the pay, instead of printing it, and make the caller print the value it returns.
Related
I'm trying to do a challenge to practice. I'm trying to use an input to decide how much you would pay on a loan. Really basic stuff - but when I print I'm getting whatever was answered in the input repeating over and over again and I can't figure out where I'm going wrong. The code I'm trying to run is:
# $200 a month at 1.7% interest a year. Automate total based on months using user input.
months_given = input("How many months? ")
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)
print(f"You will need to pay: ${round(total, 2)}")
I've tried using for/while loops but I'm not proficient with those yet and am still trying to understand how they work exactly.
You need to parse your input first then use it.
when you use input it return str.
in this total = int(months_given * monthly_total) line. months_given is str and when you use * operator and second operand is an int, str value repeated.
correct:
months_given = input("How many months? ")
months_given = int(months_given) # <-- here
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)
print(f"You will need to pay: ${round(total, 2)}")
#Please help me
def computepay(h, r):
if h>40:
reg=40*r
otp=(h-40.0)*1.5*r
else:
pay = h*r
return pay
hrs = input("Enter Hours:")
rate= input('enter rate per hour: ')
fh = float (hrs)
fr = float (rate)
p = computepay(fh, fr)
print("Pay", p)
If I understand your code correctly, your code is not pasted well, if h > 40 pay is not assigned any value, pay only is assigned a value in the else
That's why you get that error
To answer the the question about "pay" being referenced before being assigned, your code is running through the if statement portion of the line where you define computepay(). You never add reg and otp into a variable called pay, which is what I assume you're trying to do.
Also, in your else statement, you make pay = hr, which does not exist, since python will parse hr as one variable and not two, be sure to use asterisks for everything to parse correctly.
How I would type out the computepay() definition would look like this:
def computepay(h, r):
if h>40:
reg=40*r
otp=(h-40.0)*1.5*r
pay=reg+otp
else: pay = h*r
return pay
The main function below return pay is fine, though. This should run perfectly, good luck!
I'm working with Python 3 on Visual Studio Code and the project I'm working on is to calculate the user's lunar weight after receiving their terrestrial weight, then output how their weight changes overtime given an increase and a period of time.
This is the error message I've received multiple times, no matter how many times I've re-code:
TypeError: can't multiply sequence by non-int of type 'float'
This specifically happens whenever I use the input() and/or sys.stdin.readline() functions, but all of the pertaining variables are integers or floats, whether or not I try to convert them to floats by using the float() function around my inputs.
Here is my code:
# this programs converts your terra weight to your lunar weight, then it takes increase over a period of time
# error whether I use float() or not
terraWeight = float(input("Terra Weight: "))
ask = input("Is this in LBS or KG? ")
# converts pounds to kilograms
# 2.204... is used to convert lbs to kgs
if ask == "lbs" or "LBS":
initial = terraWeight / 2.2046223302272
# didn't need this, but assignment error popped up
x = 0
# or replace input() with sys.stdin.readline()
increase = input("Increase: ")
period = input("Period: ")
# gets lunar weight over time
def lunarWeight():
global increase
global period
global x
global initial
print("Earth Weight = %s kgs." % terraWeight)
year = 0
lunarWeight = initial * 0.165
print("Moon Weight = %s kgs. \n" % lunarWeight)
postIncrease = lunarWeight * increase
for x in range(0, period):
year += 1
lunarWeight += postIncrease
print("Year %s = %s kgs." % (year, lunarWeight))
lunarWeight()
The terminal directs to the this section of my code:
postIncrease = lunarWeight * increase
Which is on line 28. I'm not sure what the problem is, and I tried debugging but I still get the same error messages. I saw other posts with the same problem but they had problems using lists, which I'm pretty sure I'm not using. Any advice please?
Screenshot
I think you should write this lines as:
increase = float(input("Increase: "))
period = int(input("Period: "))
period is used in range() so it should be integer
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.
I'm using python for the very first time and I am stuck on this stinking problem and cant for the life of me figure out why its not working. When I try and run my program I can get an answer for the yearly cost without the modification (even though its wrong and I dont know why) but not the yearly cost with the modification.
I've tried rewriting it in case I missed a colon/parenthesis/ect but that didnt work, I tried renaming it. And I tried taking it completely out (this is the only way I could get rid of that annoying error message)
payoff file
from mpg import *
def main():
driven,costg,costm,mpgbm,mpgam = getInfo(1,2,3,4,5)
print("The number of miles driven in a year is",driven)
print("The cost of gas is",costg)
print("The cost of the modification is",costm)
print("The MPG of the car before the modification is",mpgbm)
print("The MPG of the car afrer the modification is",mpgam)
costWithout = getYearlyCost(1,2)
print("Yearly cost without the modification:", costWithout)
costWith = getYearlyCost2()
print("Yearly cost with the modification:", costWith)
While I know there is an error (most likely a lot of errors) in this I cant see it. Could someone please point it out to me and help me fix it?
Also I added my mpg.py in case the error is in there and not the payoff file.
def getInfo(driven,costg,costm,mpgbm,mpgam):
driven = eval(input("enter number of miles driven per year: "))
costg = eval(input("enter cost of a gallon of gas: "))
costm = eval(input("enter the cost of modification: "))
mpgbm = eval(input("eneter MPG of the car before the modification: "))
mpgam = eval(input("enter MPG of the car after the modification: "))
return driven,costg,costm,mpgbm,mpgam
def getYearlyCost(driven,costg):
getYearlyCost = (driven / costg*12)
def getYealyCost2(driven,costm):
getYearlyCost2 = (driven / costm*12)
return getYearlyCost,getYearlyCost2
def gallons(x,y,z,x2,y2,z2):
x = (driven/mpgbm) # x= how many gallons are used in a year
y = costg
z = (x*y) # z = how much money is spent on gas in year
print("money spent on gas in year ",z)
x2 = (driven/mpgam) # x2 = how much money is spent with mod.
z2 = (x2*y)
y2 = (costm + z2)
1,1 Top
Here's your immediate problem:
costWith = getYearlyCost2()
The function you're trying to call is named getYealyCost2() (no "r").
There are other problems that you'll find as soon as you fix that, such as no return statement in getYearlyCost() and trying to return the function getYearlyCost() in getYearlyCost2() and calling getYearlyCost2() without any arguments.
On top of that, import * is frowned upon, and then there's the use of eval()... but that'll do for starters.