Python program does not execute beyond first user input [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written a Python program that I expect to accept a "y" input from a user, and if the user inputs "y", do some simple calculations and print the results.
However it is not executing beyond
the user input even if that input is "y". Please help me locate the errors in the program.
The code is:
#This function is to get the user to input the data needed to use in the rest of the program
#It should return the 3 variables name, hrs_wrkd, and payrate
def get_info(name,hrs_wrkd,payrate):
print('is this working?');
name = input('What is the last name of the employee?');
hrs_wrkd = float(input('How many hours did',name,' work last week?'));
payrate = float(input('How much does',name,' get paid?'));
return name,hrs_wrkd,payrate
#This function should be to calculate the employee's regular pay hours
#It accepts arguments from get_info
def calculate_reg_pay(hrs_wrkd,payrate):
reg_hrs = hrs_wrkd
reg_pay = reg_hrs * payrate
OT_hrs = 0
OT_pay = 0
return reg_hrs,reg_pay,OT_hrs,OT_pay
#This function should calculate the Overtime pay for the employee
#It accepts arguments from the get_info function as well
def calculate_OT_pay(hrs_wrkd,payrate):
reg_hrs = hrs_wkrd - 40
reg_pay = reg_hrs * payrate
OT_hrs = hrs_wrkd - reg_hrs
OT_pay = OT_hrs * (payrate * 1.5)
return reg_hrs,reg_pay,OT_hrs,OT_pay
#This function decides which calculation to use, either OT or regular pay
#It also accepts srguments from get_info
def calc_employee(hrs_wrkd,payrate):
if hrs_wrkd <= 40:
calculate_reg_pay(hrs_wrkd,payrate)
else:
calculate_OT_pay(hrswrkd,payrate)
#This function should print the single employee information after it was calculated
#It gets its arguments from the calc_employee function
def print_employee(reg_pay,OT_pay,name):
print(name,'earned $',format(reg_pay,'.2f'),' worth of regular pay and ',format(OT_pay,'.2f'),' in overtime this week.')
#This function is supposed to calculate the running total of the hours and pay for overtime and regular pay for the company
# It accepts its arguments from the calc_employee function also
def running_total(reg_hrs,reg_pay,OT_hrs,OT_pay,total_reg_hrs,total_reg_pay,total_OT_hrs,total_OT_pay):
total_reg_hrs = total_reg_hrs + reg_hrs
total_reg_pay = total_reg_pay + reg_pay
total_OT_hrs = total_OT_hrs + OT_hrs
total_OT_pay = total_OT_pay + OT_pay
#This function is supposed to print out the running total for the company, but I realized that it isnt in the proper position when called
def print_totals(total_reg_hrs,total_reg_pay,total_OT_hrs,total_OT_pay):
print('The total regular hours worked was',total_reg_hours)
print('The total regular pay was $',format(total_reg_pay,'.2f'))
print('The total overtime hours worked was',total_OT_hours)
print('The total overtime pay was $',format(total_OT_pay,'.2f'))
# So here I am defining the main loop that will activate everytime the user selects Yes
#It calls most of the other functions
def main_loop():
get_info
calc_employee
print_employee
running_total
#Here I am defining the main program where I put the loop control
def main():
loop_control = input("Would you like to enter an employee's name, payrate and hours? y to do so")
if loop_control == "y":
main_loop
else:
print_totals(total_reg_hrs,total_reg_pay,total_OT_hrs,total_OT_pay)
#Here we call the main function
main()

You need to call your functions. This does nothing but reference the function object:
main_loop
Add () to call a function:
main_loop()
Same in your main_loop() function:
def main_loop():
get_info()
calc_employee()
print_employee()
running_total()
Not that that'll work, because your functions take parameters; you need to pass those in in a function call to work. get_info() takes parameters it then ignores; remove those parameters in the function signature:
def get_info():
print('is this working?');
name = input('What is the last name of the employee?');
hrs_wrkd = float(input('How many hours did',name,' work last week?'));
payrate = float(input('How much does',name,' get paid?'));
return name,hrs_wrkd,payrate
Next you want to assign return values; get_info() returns a few things, but you never assign any of them:
name, hours_worked, payrate = get_info()
Now you can pass these to other function calls:
calc_employee(hours_worked, payrate)
etc.
You'll have quit a few more to fix, that is outside the scope of this answer though. Don't forget to use return on function calls too! calc_employee doesn't return anything, for example, it simply ignores what the functions it delegates to return, for example.

Related

Coffee Machine - invalid syntax and End of Statement expected in new function

So I'm trying to create a coffee machine program (you choose a drink, the machine checks the ingredients, the resources and the money you insert, then it dispenses the drink.) and it went okay until I got to the part where the program processes the coins and, if sufficient, adds them to the amount of money in the machine.
I'm not really good with return statements and global vs local scopes, so I assume they are the issue. I tried googling, but nothing came up that actually solves the specific problem I have.
This is the code for the function in question:
def process_coins(order, money):
print("Please insert coins.")
quarters = float(input("Quarters: ")) * quarters_value
dimes = float(input("Dimes: ")) * dimes_value
nickles = float(input("Nickles: ")) * nickles_value
pennies = float(input("Pennies: ")) * pennies_value
total = quarters + dimes + nickles + pennies
if total < MENU[order]["cost"]:
total = 0
return print("Sorry, that's not enough money. Money refunded.")
else:
return money += total
PyCharm tells me "End of Statement expected" and "invalid Syntax" for the last line.
When I remove "return" it runs but doesn't actually add the total to the money in the machine. I also tried putting brackets around money += total, which turns both problems into "unexpected expression syntax".
I honestly don't understand why this doesn't work. I just want pycharm to add "total" (local scope) to "money"(global scope) and to return it so I can use it in the rest of the code.
I also don't understand why this function wasn't able to work with the variable "money" before I added it as an argument in the brackets, but it was able to work with the variables "dimes_value" etc. just fine, even though those are mentioned just one line before "money" at the start of the code and aren't part of the arguments in the bracket of the function.
What am I missing?
The problem is that return can only return expressions, but an augmented assignment is a statement. This is why you get a syntax error.
For Python >= 3.8, you can use an assignment expression to overcome this:
return (money := money + total)
* Note the necessary parenthesis.
This will both assign to money and return the value assigned to it.
But this will create a new problem: money will now be considered a local variable (because you assign to it inside the function) and you'll get a different error.
To overcome this, you will need to declare
global money
At the start of the function.
But really the best solution here is not to use global variables at all, simply return money + total, and assign the returned value in the global scope, where you call the function.
if total < MENU[order]["cost"]:
total = 0
return print("Sorry, that's not enough money. Money refunded.")
else:
money += total
return money

Unsupported operand type(s) in Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to python and am having trouble with functions/defining something properly.
Now I am getting the TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
I have to output it a certain way and meet specific directions given to me, but I just can't seem to figure this out. Any help would be greatly appreciated. I will include an image of the rules I have to follow, I figured out how to make it work when not following the rules but can't make it work when I try to stick to them.
Direction to follow for coding this
# A function that prompts the user for a name and returns it to the
# calling statement.
def getName():
name = input("Please enter your name: ")
return name
# A function that prompts the user for a score and returns it to the
# calling statement.
def score_input():
int(input("Enter your score: "))
# A function that receives two numbers and returns the average of those
# two values to the calling statement.
def find_avg():
(score_a + score_b) / 2
# A function that receives a string and a number (the name and the
# average score) and prints it out on the screen in the appropriate format.
def output():
print("Hi, {}. Your average score is {}".format(name, avg))
#############################################################################
# prompt for name
name = getName()
# prompt for two scores
score_a = score_input()
score_b = score_input()
# calculate the average
avg = find_avg()
# display the final output
output()
score_input doesn't have a return statement, so it returns None.
Two of your functions neglect to return the computed values, so they return None by default. Just change them to:
def score_input():
return int(input("Enter your score: "))
# ^^^^^^ added return
def find_avg():
return (score_a + score_b) / 2
# ^^^^^^ added return
and you won't get Nones when you call them.
Side-note: It's typically considered bad form to rely on non-constant globals. I'd suggest changing output to be more reusable by having it receive the items to output as arguments, e.g.:
def output(name, avg):
print("Hi, {}. Your average score is {}".format(name, avg))
then calling it with:
output(name, avg)
Same goes for find_avg. Packaging the script functionality up into a main method helps avoid accidentally relying on globals, which would get final code like this (comments omitted for brevity):
def getName():
return input("Please enter your name: ")
def score_input():
return int(input("Enter your score: "))
def find_avg(a, b):
return (a + b) / 2
def output(name, avg):
print("Hi, {}. Your average score is {}".format(name, avg))
#############################################################################
# Wrapping script functionality in main ensures all variables are local,
# not global, which ensures you don't accidentally depend on global state
def main():
name = getName()
score_a = score_input()
score_b = score_input()
avg = find_avg(score_a, score_b)
output(name, avg)
if __name__ == '__main__':
main() # Called only when invoked as a script, not when imported as a module
You don't return the input from the function score_input. So the return type is None.
In order to make your code work you would need to add return {expression} in the function.
This is how I would change the code:
# A function that prompts the user for a name and returns it to the
# calling statement.
def getName():
name = input("Please enter your name: ")
return name
# A function that prompts the user for a score and returns it to the
# calling statement.
def score_input():
return int(input("Enter your score: "))
# A function that receives two numbers and returns the average of those
# two values to the calling statement.
def find_avg():
return (score_a + score_b) / 2
# A function that receives a string and a number (the name and the
# average score) and prints it out on the screen in the appropriate format.
def output():
print("Hi, {}. Your average score is {}".format(name, avg))
#############################################################################
# prompt for name
name = getName()
# prompt for two scores
score_a = score_input()
score_b = score_input()
# calculate the average
avg = find_avg()
# display the final output
output()

How to use def *insert name here* (): functions?

I'm new to python and had a question about to to use more functions in a code besides def main():
My code below works, but I am trying to add new def's to their respective areas.
So like a new def called (def calcPay():), to where the hours enter are calculated (regPay, overtimePay, and total) as 3 separate items.
&
Also add a new def called (def displayOutput():), the function would receive all three of the values from (overtimePay, regPay, and totalPay) and print the message below.
If someone could explain to me how to use new functions besides main, that would be greatly appreciated.
Thanks, here is my code:
def main():
try:
hoursWorked = float(input("How many hours did you work? "))
if hoursWorked > 40:
overtimePay = (hoursWorked - 40) * 15
regPay = 40 *10
totalPay =( overtimePay + regPay)
else:
regPay = hoursWorked * 10
overtimePay = 0
totalPay = (regPay + overtimePay)
print("You earned",'${:,.2f}'.format(regPay),"in regular pay",'${:,.2f}'.format(overtimePay),
"in overtime for a total of",'${:,.2f}'.format(totalPay))
except:
print("Sorry, that wasn't a valid number. Ending program")
main()
You can declare your functions outside of the main function declaration and then use them in the main function (or inside of other functions in the main function).
So you could do something like:
def calcPay(hours):
# Does logic
return [400, 30, 430]
def displayOutput(regPay, overtimePay, totalPay):
# Prints formatted string
def main():
hoursWorked = float(input("How many hours did you work? "))
pay = calcPay(hoursWorked)
displayOutput(pay[0], pay[1], pay[2])
main()
Have a look at these similar questions:
What does it mean to call a function?
How to correctly define a function?
Basic explanation of Python functions?
There's nothing special about the function named main. You can name functions whatever you want.
When you "call" a function you're just jumping from one block of code to another. When the function returns it goes back to the line that called it.
def something():
print('something')
def other():
print('else')
def a_value():
return 100
something()
other()
x = a_value()
print(x)
# ~~~~~ output
something
else
100
In your example a good use of a function would be to calculate the employee's pay.
def total_pay(hours_worked, hourly_rate, overtime_after=40):
base_pay = min(overtime_after, hours_worked) * hourly_rate
overtime_pay = max(0, hours_worked - overtime_after) * (hourly_rate * 1.5)
return base_pay + overtime_pay
This function allows us to define the three things that determine a worker's pay. The base_pay will be, at most, the number of hours before overtime is applied. The overtime_pay will be from 0 to "some other limit" that's not defined here. Overtime is given time and a half (1.5).

Returning multiple valuables and then calling those valuables separately

I'm having issue with allowing a function to call on variables set by another function. I believe I know how to do this with single variables, but my code requires it be done with multiple variables, a challenge I've struggled with for hours. I've read much about ways others seem to have done this but I can't find success in implementing them.
#gathers the user's requests
def ask():
userw = int(input('How wide? '))
userh = int(input('How tall? '))
userc = input('What string to use? ')
userc_len = int(len(userc))
return (userw, userh, userc, userc_len)
#draws the rows of the box. First the top with the topbot function, then the body with body(), then the bottom with topbot again
def draw(w, h, c, c_len):
def topbot(w_, c_):
for x in range(w_):
print (c_, end ='')
print ('\n')
def body(w_, h_, c_, c_len_):
for x in range(h_-2):
print (c_, end = '')
for x in range(w_-2):
print(' ' * c_len_, end = '')
print (c_)
topbot(w, c)
body(w, h, c, c_len)
topbot(w, c)
#begins draw
draw(userw, userh, userc, userc_len)
The problem begins when the draw function tries to begin with the arguments of userw, userh, userc, userc_len, but can't find them:
NameError: name 'userw' is not defined
is returned when I try to run it.
Is it correct to define topbot and body within the draw function and manage the arguments how I did?
How do I return the four variables from ask in a manner such that draw can then use them as arguments?
ask() is a function which will return 4 values. So,
returnValues = ask()
draw = draw(*returnValues)
or simply, draw = draw(*ask())
Also, end = ' ' is not correct. Instead of that you can just use print(c_,'').
Include Validations wherever necessary. Like what if I type "hi" for "How wide?". In this case the program should tell me that this is wrong.
I was able to get draw() to accept the inputs from your ask() function (in Python IDLE) just by changing the last line of your code to this:
draw(*ask())
The * will unpack the variables from the ask() call and pass that along to draw(). The output looks kind of funny, and I'm not sure whether that's what you're looking for or not, but at least it got the variables in there correctly.

Passing Arguments in Python

I am trying to figure out how to pass arguments in Python and why my code is not working. Why is it saying that the arguments are not defined? I need the arguments in from each function to be able to speak to one another. I could only solve this problem by putting the variables in the defined main function, which is not how I wanted to design the program.
#make computer program that takes amount of doughnuts that customer
#wants to order.
#second, multiply the number of doughnuts the customer wants to order
#by the price and the sales tax.
#next, print the price of the doughnut with the sales tax
DOUGHNUT=1.75
SALES_TAX=0.08625
def getNumDoughnuts(numDoughnuts):
numDoughnuts= raw_input("How many donuts would you like to order?")
return numDoughnuts
def calculateDoughnutPrice(numDoughnuts, doughnutPrice):
doughnutPrice=DOUGHNUT*float(numDoughnuts)
return doughnutPrice
def calculateSalesTax(doughnutPrice, priceWithTax):
taxAmount= (doughnutPrice*(SALES_TAX))
priceWithTax= taxAmount+doughnutPrice
return priceWithTax
def displayPrice(priceWithTax):
print(priceWithTax)
def main():
getNumDoughnuts(numDougnuts)
calculateDoughnutPrice(numDoughnuts, doughnutPrice)
calculateSalesTax(doughnutPrice, priceWithTax)
displayPrice(priceWithTax)
main()
In main, numDougnuts is indeed not defined when you call getNumDoughnuts. OTOH, the latter function ignores its argument and returns a value, which main in turn ignores. And so forth -- you need to distinguish arguments from return values!
So putting things in proper order your program would become:
DOUGHNUT = 1.75
SALES_TAX = 0.08625
def getNumDoughnuts():
numDoughnuts = raw_input("How many donuts would you like to order?")
return numDoughnuts
def calculateDoughnutPrice(numDoughnuts):
doughnutPrice = DOUGHNUT * float(numDoughnuts)
return doughnutPrice
def calculateSalesTax(doughnutPrice):
taxAmount = doughnutPrice*(SALES_TAX)
priceWithTax = taxAmount + doughnutPrice
return priceWithTax
def displayPrice(priceWithTax):
print(priceWithTax)
def main():
numDoughnuts = getNumDoughnuts()
doughnutPrice = calculateDoughnutPrice(numDoughnuts)
priceWithTax = calculateSalesTax(doughnutPrice)
displayPrice(priceWithTax)
main()
See the difference between arguments and return values? Arguments are what gets into a function (and their values must be defined at the time you call that function). A return value is what gets out of the function -- and usually needs to be bound to a variable, or otherwise used, by the function's caller.
Also, of course, you need to call main, or else nothing happens!-)

Categories

Resources