I am having a problem with my code here. The error that I am receiving is on the bottom.
I have to enter payroll in and calculate pay with overtime or without.
enter code here
####################### Functions ########################
def Input():
try:
name=raw_input("Enter your first and last name: ")
titlename=name.title()
except:
return Input
def Hours():
try:
wHours=raw_input("Enter the hours you worked this week: ")
except:
if wHours < 1 or wHours > 60:
print "Employees' can't work less than 1 hour or more than 60 hours."
return lstEmp
def Pay():
try:
pRate=raw_input("Enter your hourly wage: ")
except:
if pRate < 6 or pRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00."
return pay
def calcHours(pr,h):
if h <= 40:
pr * h
else:
(h -40) *(pr *1.5) + pr * 40
return lstEmp
def end():
empDone=raw_input("Please type DONE when you are finished with employees' information: ")
empDone.upper() == "DONE"
#################### MAINLINE CODE
lstEmp=[]
Names=""
while True:
Names=Input()
WorkHours=Hours()
Wages=Pay()
gPay=calcHours(WorkHours, Wages)
Done=end()
if end():
break
Traceback (most recent call last):
File "J:\11-2-10.py", line 53, in
gPay=calcHours(WorkHours, Wages)
File "J:\11-2-10.py", line 29, in calcHours
pr * h
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
In Input, Hours and Pay, you assign to a variable of the same name as the functions; perhaps you mean to return these values instead?
gPay=calcHours(Hours, Pay)
You meant WorkHours, which is what you called the variable; Hours is still the function, that returned it. There are plenty of other places in the code where you've changed the variable names so they don't match any more.
Also +1 gnibbler's comment. That's really not what try does, and you should never use except without a particular Exception. The bit you might want to put in the try is a conversion to integer:
def getHours():
while True:
hours= raw_input("Enter the hours you worked this week: ")
try:
hours= int(hours)
except ValueError:
print "That's not a number, type it proper."
continue
if not 1<=hours<=60:
print "Employees must work between 1 and 60 hours."
continue
return hours
Related
I got a small project for my course, I am to write a program that simulates a person's bank account.
I'll spare the talk, the code is down below, along with the commenting....
# -*- coding: utf-8 -*-
#This program starts by taking in a user input as shown in the While loop..
#the 2 Methods in the class, 1 is for depositing money and the second is for a withdrawal..
class Account:
newBal = 0
post_bal=0
def __init__(self, balance):
self.balance = balance
def deposit(self, deposit):
self.deposit = int(deposit)
#newBal is the variable that takes the new Balance
Account.newBal = self.balance + self.deposit
print("Your Balance is now {}".format(Account.newBal))
return Account.newBal
def withdraw(self, withdraw):
self.withdraw = int(withdraw)
if self.withdraw > Account.newBal:
return "Error, we have a hard time finding that kind of money..."
else:
print("Withdrawal Accepted, have fun with that dough!")
#post_bal is the variable that stores the balance with the withdrawal taken from it
Account.post_bal = Account.newBal - self.withdraw
return("Your Balance is now {}".format(Account.post_bal))
a = Account(balance=0)
while True:
input_1 = input("What would you like to do today? [1] Deposit, [2] Withdraw ")
if int(input_1) == 1:
print(a.deposit(input("How much would you like to deposit? ")))
elif int(input_1) == 2:
print(a.withdraw(input("How much would you like to withdraw? ")))
else:
print(" I'm not too sure I understand what you're saying...")
With this I've been able to run a full loop successfully, depositing and amount and then withdrawing another, with all the outputs being returned. However, once I get either action for the second time in the loop, I get the error call...
TypeError
Traceback (most recent call last)
<ipython-input-4-6a19e620e3d6> in <module>
33 print(a.deposit(input("How much would you like to deposit? ")))
34 elif int(input_1) == 2:
---> 35 print(a.withdraw(input("How much would you like to withdraw? ")))
36 else:
37 print(" I'm not too sure I understand what you're saying...")
TypeError: 'int' object is not callable
I'm not sure what I did wrong here...
You are changing the withdraw to an int here.
def withdraw(self, withdraw):
self.withdraw = int(withdraw)
Use a different name like
def withdraw(self, withdraw):
self.withdraw_value = int(withdraw)
I am making a price is right game. I am currently working on a game mode similar to the contestant row, where they guess the price of an item.
When it asks you to submit a bid, if you enter a word (instead of a bid), the program crashes and displays the following error:
"Traceback (most recent call last):
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 36, in
contestantrow()
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 24, in contestantrow
protagnum=int(input(propername +", what is your bid?"))
ValueError: invalid literal for int() with base 10: 'alexei'"
Here's my code:
import random
print(" The Price is Sorta Right - 000776331")
welcomeplayer = True
contestantrow = True
def welcome():
while True:
global welcomeplayer
global propername
welcomeplayer = input("Please enter your name using only letters")
validname = welcomeplayer.isalpha()
propername = welcomeplayer.capitalize()
if validname == True:
print( propername, " ! Come on down! You're the next contestant on the Price is (sorta) right")
print (" Dew Drop welcomes " ,propername ," to contestants row joining EIMNOT A. HUMAN,ARTHURFICIAL EINTEL , ROBORT")
return
else:
print("Please only write letters on your name tag")
welcomeplayer = False
def contestantrow():
while True:
print("Dew Drop shows the price that you are bidding on")
protagnum=int(input(propername +", what is your bid?"))
if protagnum > 0:
componebid = random.randint(1,1000)
print("EIMNOT A. HUMAN bids: ",componebid)
comptwobid = random.randint(1,1000)
print("ARTHURFICIAL EINTEL bids: ",comptwobid)
compthreebid =random.randint(1,1000)
print("ROBORT bids: ",compthreebid)
else:
print(" Dew Drop says [Im sorry bids should start at atleast one dollar]")
contestantrow = False
welcome()
contestantrow()
protagnum=int(input(propername +", what is your bid?"))
You're converting an int / string to int. "1" will work but "a" will raise a ValueError
while True:
try:
protagnum=int(input(propername +", what is your bid?"))
break
except ValueError:
print("Invalid bid, please try again")
I'm scripting a small game to guess a number and I don't understand why I'm getting this error as both num and userNum in my numCheck() function should be strings and not functions.
import random
def num():
"""Returns a number between 1000 and 9999."""
num = str(random.randint(1000, 9999))
print("Random number is: " + num) #for testing purposes
return num
def userNum():
"""Asks user for a number between 1000 and 9999."""
while True:
try:
userNum = int(input("Choose a number between 1000 and 9999: "))
except ValueError:
print("This isn't a number, try again.")
continue
if userNum < 1000 or userNum > 9990:
print("Your number isn't between 1000 and 9999, try again.")
continue
else:
break
userNum = str(userNum)
return userNum
def numCheck(num, userNum):
"""Checks the number of cows and bulls."""
cow = 0
bull = 0
for i in range(0, 3):
if userNum[i] == num[i]:
cow += 1
else:
bull += 1
print("You have " + str(cow) + " cow(s) and you have " + str(bull) + " bull(s).")
return cow
def gameLoop():
"""Loops the game until the user find the right number."""
num()
cow = 0
if cow < 4:
userNum()
numCheck(num, userNum)
else:
print("Congratulation, You found the right number!")
gameLoop()
The error I get when I run the script is the following:
==================== RESTART: /home/pi/Desktop/cowbull.py ====================
Random number is: 8104
Choose a number between 1000 and 9999: 5555
Traceback (most recent call last):
File "/home/pi/Desktop/cowbull.py", line 47, in <module>
gameLoop()
File "/home/pi/Desktop/cowbull.py", line 43, in gameLoop
numCheck(num, userNum)
File "/home/pi/Desktop/cowbull.py", line 30, in numCheck
if userNum[i] == num[i]:
TypeError: 'function' object is not subscriptable
>>>
Note that other things may not be working or perfect at the moment, but I'm only trying to figure out the logic of this error so I can continue on.
Thanks for the help!
Here is your function gameLoop:
def gameLoop():
"""Loops the game until the user find the right number."""
num()
cow = 0
if cow < 4:
userNum()
numCheck(num, userNum)
else:
print("Congratulation, You found the right number!")
You call a function named userNum() but you don't assign its returned value to a variable. In the next line you pass userNum as an argument to the function numCheck. Since userNum was a function in the previous line, it must still be a function now (it's perfectly legitimate in Python to pass a function as an argument to another function).
In the previous line, you need to assign the returned value from userNum to a new variable. Then pass that variable to numCheck:
x = userNum()
numCheck(num, x)
You have made exactly the same mistake with the function num. Even though you want num and userNum to be strings, in fact both of them are functions. Both functions return a string, but you need to assign the returned values to new variables in order to use them later.
Abdou's comment is correct that it's confusing to use the same variable name to mean different things.
I am new to programming Python, learning mostly through "learn python the hard way." I recently wrote a script that will help me calculate the overtime earnings for my piece work employees. The script works, but it just doesn't look right to me. I would love input on how I could have saved myself some steps. I know using globals is taboo, but I could not figure out another way to get the answers outside those functions. Thank you!!
# THIS SCRIPT WILL CALCULATE THE NUMBER OF PAID HOURS, OVERTIME HOURS, PIECE RATE HOURS AND OVERTIME HOURS OWED TO AN EMPLOYEE.
number_of_straight_hours_worked = False
number_of_overtime_hours_worked = False
employee_travel_time = False
days_worked = False
employee_earnings = False
employee_hourly_rate = False
employee_overtime_rate = False
#Function to determine number of straight hours worked.
def straight_hours():
global number_of_straight_hours_worked
number_of_straight_hours_worked = float(number_of_straight_hours_worked)
while number_of_straight_hours_worked == False:
number_of_straight_hours_worked = raw_input("How many straight hours did the employee work? ")
try:
int(number_of_straight_hours_worked)
except ValueError:
print("Must use a number")
number_of_straight_hours_worked = False
else:
print ("Thank you.")
#print number_of_straight_hours_worked
# Determines number of overtime hours.
def overtime_hours():
global number_of_overtime_hours_worked
number_of_overtime_hours_worked = float(number_of_overtime_hours_worked)
while number_of_overtime_hours_worked == False:
number_of_overtime_hours_worked = raw_input("How many overtime hours did the employee work? ")
try:
int(number_of_overtime_hours_worked)
except ValueError:
print("Must use a number")
number_of_overtime_hours_worked = False
else:
print ("Thank you.")
#print number_of_overtime_hours_worked
#Calcualtes the employee's overtime rate.
def employee_ot_calculation():
global employee_hourly_rate
global employee_overtime_rate
while employee_hourly_rate == False:
employee_hourly_rate = raw_input("What is the employee's hourly rate? ")
try:
float(employee_hourly_rate)
except ValueError:
print("Must use a number.")
#print employee_hourly_rate
else:
employee_overtime_rate = float(employee_hourly_rate) * 1.5
#Stores travel time hours
def travel_time():
global employee_travel_time
while employee_travel_time == False:
employee_travel_time = raw_input("How many hours of travel? ")
try:
int(employee_travel_time)
except ValueError:
print("Must use a number.")
employee_travel_time = False
else:
print ("Thank you.")
#print employee_travel_time
#Stores number of working days. Not used in version .001
def number_of_days_worked():
global days_worked
while days_worked == False:
days_worked = raw_input("How many days did the employee work? ")
days_worked = float(days_worked)
try:
int(days_worked)
except ValueError:
print("Must use a number.")
days_worked = False
else:
print ("Thank you.")
#Stores earnings made by piece work from employee.
def employee_piece_earnings():
global employee_earnings
while employee_earnings == False:
employee_earnings = raw_input("What did the employee earn through piece rate (format: 0.00)? ")
employee_earnings = float(employee_earnings)
try:
float(employee_earnings)
except ValueError:
print("Must use a number, no dollar sign.")
employee_earnings = False
else:
print ("Thank you.")
#print employee_earnings
# Calculates what the employee will earn this pay period between hours and piece work.
def overtime_piece():
total_hours_worked = float(number_of_straight_hours_worked) + float(number_of_overtime_hours_worked)
# print total_hours_worked
actual_working_hours = float(total_hours_worked) - float(employee_travel_time)
#print actual_working_hours
piece_overtime = float(actual_working_hours) - 40
#print piece_overtime
overtime_rate = float(employee_earnings / actual_working_hours)
#print overtime_rate
earned_straight_pay = float(number_of_straight_hours_worked) * float(employee_hourly_rate)
print "This employee earned $%.2f in straight pay: %.2f hours at $%.2f per hour" % (earned_straight_pay, number_of_straight_hours_worked, employee_hourly_rate)
earned_hourly_overtime = (float(total_hours_worked) - float(actual_working_hours)) * float(employee_overtime_rate)
print "This employee earned $%.2f in hourly overtime: %.2f hours at $%.2f per hour" % (earned_hourly_overtime, number_of_overtime_hours_worked, employee_overtime_rate)
earned_piece_overtime = float(overtime_rate) * float(piece_overtime)
print "This employee earned $%.2f in piece OT: %2f for each of working hour of the %.2f hours of overtime" % (earned_piece_overtime, overtime_rate, piece_overtime)
total_employee_earnings = float(earned_straight_pay) + float(earned_hourly_overtime) + float(earned_piece_overtime) + float(employee_earnings)
print "This employee earned a total of $%.2f this pay period." % total_employee_earnings
employee_ot_calculation()
straight_hours()
overtime_hours()
travel_time()
employee_piece_earnings()
overtime_piece()
To avoid using global variables, what you want to do is use function arguments and return values.
Function arguments
Let's take your first function as an example.
You can define a variable outside of the scope of your function and pass it as an argument between the two parenthesis. You can then manipulate your variable at your convenience inside of your function. You can pass as many arguments as you want.
number_of_straight_hours_worked = 1 # Define a variable outside of function
def straight_hours(number_of_straight_hours_worked): #Pass as argument
number_of_straight_hours_worked += 1 #Do whatever you want
Returning Values
The function straight_hours takes the input on how many straight hours an employee has worked. Instead of using a global variable, what you want to do is to return the value.
number_of_straight_hours_worked = "" # Define a variable outside of function
def straight_hours(number_of_straight_hours_worked): #Pass as argument
number_of_straight_hours_worked = input("How many hours?")
return number_of_straight_hours_worked
#Then retreive the value by doing
number_of_hours = straight_hours(number_of_straight_hours_worked)
As you can see, the line number_of_hours = straight_hours() calls the functions and affects the return the return value to the number_of_hours variable.
Other notes
I would also advise shrinking and simplifying you variable names.
Also, when you declare a variable like you do at the top of your code, I would advise either declare them as NONE or not do it at all. Declaring them to False which is of type boolean to then convert it to a float makes no sense to me.
Separete your validation code from your actual calculations. This way, you can test your calculations separately.
I'm in Grade 11 Computer Science at my highschool, and I'm just starting out in Python. I'm supposed to make a function called computepay that will ask the user their name, their wage, and their hours that week and automatically calculate the total, including any overtime and not error out when an incorrect input is included. I made different functions for all the inputs, but when I plug it all into my computepay function it tells me this:
TypeError: float() argument must be a string or a number
def mainloop(): #Creating a loop so it doesn't error out.
response = input('Make another calculation?[y/n]') #inputing loop
if response == 'n': #creating input for n
return
if response == 'y':
computepay()
else:
print("\n")
print ("Incorrect input. .")
mainloop()
def getname():
name = input ("What's your name?") #input of name
def getwage():
wage = input ("Hello there! How much money do you make per hour?") #input
try:
float(wage) #Making it so it does not error out when a float
except:
print ("Bad Input")
getwage()
def gethours():
hours = input ("Thanks, how many hours have you worked this week?")
try:
float(hours) #Making it so it does not error out when a float
except:
print("Bad Input")
gethours()
def computepay():
name = getname()
wage = getwage()
hours = gethours()
if float(hours) > float(40):
newhours = float(hours) - float (40) #figuring out the amount of overtime hours the person has worked
newwage = float (wage) * float (1.5) #figuring out overtime pay
overtimepay = float (newwage) * float (newhours) #calculating overtime total
regularpay = (float(40) * float (wage)) + overtimepay #calculating regular and overtime total.
print (name,",you'll have made $",round(regularpay,2),"this week.")
else:
total = float(wage) * float(hours)
print (name,",you'll have made $",round (total,2),"this week.")
mainloop() #creating the loop.
#-------------------------------------------------------------------------------
computepay()
None of these functions are returning anything
name = getname()
wage = getwage()
hours = gethours()
So they all end up being None
Try this
def getname():
return input("What's your name?") # input of name
def getwage():
wage = input("Hello there! How much money do you make per hour?") # input
return float(wage)
def gethours():
hours = input("Thanks, how many hours have you worked this week?")
return float(hours)
What the error message is telling you is that somewhere (on the line number reported in the part of the error message that you didn't show us) you are calling float and giving it an argument (i.e. an input) that is neither a number, nor a string.
Can you track down where this is happening?
Hint: Any Python function which doesn't return anything (with the return keyword) implicitly returns None (which is neither a string nor a number).