I am writing a program that prompts the user to input some information to output the pay amount. After displaying the amount, the program asks the user whether the user wants to repeat it using the while loop. After the definition of the program that calculates the pay amount, there is a while loop to repeat the questions for the inputs. The problem is that I cannot find a way to exit the loop.
Here is what I have so far:
def CalPay(hrs,rate):
print('Please enter number of hours worked for this week:', hrs)
print('What is hourly rate?', rate)
try:
hrs = float(hrs)
except:
print('You entered wrong information for hours.')
return
try:
rate=float(rate)
except:
print('You entered wrong rate information.')
return
if hrs < 0:
print('You entered wrong information for hours.')
elif rate < 0:
print('You entered wrong rate information.')
else:
if hrs > 60:
pay=((hrs-60)*2*rate)+(20*rate*1.5)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
elif hrs > 40:
pay=((hrs-40)*1.5*rate)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
else:
pay=rate*hrs
print('Your pay for this week is:', '$'+str(pay))
repeat=input('Do you want another pay calculation?(y or n)')
while repeat == 'y' or 'Y':
while True:
try:
hrs = float(input('Please enter number of hours worked for this week:'))
except:
print('You entered wrong information for hours.')
continue
else:
break
while True:
try:
rate=float(input('What is hourly rate?'))
except:
print('You entered wrong rate information.')
continue
else:
break
if hrs < 0:
print('You entered wrong information for hours.')
elif rate < 0:
print('You entered wrong rate information.')
else:
if hrs > 60:
pay=((hrs-60)*2*rate)+(20*rate*1.5)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
elif hrs > 40:
pay=((hrs-40)*1.5*rate)+(rate*40)
print('Your pay for this week is:', '$'+str(pay))
else:
pay=rate*hrs
print('Your pay for this week is:', '$'+str(pay))
repeat=input('Do you want another pay calculation?(y or n)')
print('Good Bye!')
I think your problem is, every time after calculation it is asking you question "'Do you want another pay calculation?(y or n)'" and if you answer n, still execution is going inside loop.
you are using below condition in while
while repeat == 'y' or 'Y': #this is wrong
when you write above condition it actually resolves to
while (repeat == 'y') or ('Y'):
here first condition is false but 2nd is true. So execution will go inside while.
Instead use 'in' keyword as below.
while repeat in ['y', 'Y']: #I will prefer this.
or
while repeat == 'y' or repeat=='Y':
or
while repeat == ('y' or 'Y'):
Hope this will help you.
You have nested while loops. You'll need to break out of both of them.
Related
the conditions are:
Repeatedly reads numbers until the user enters 'done'. Once 'done' is entered, break out of the loop.
If the user enters anything but a number, capture the error using a try-except construct and display the message "Bad Data"
Once 'done' is entered print out one of 2 messages:
If the total is greater or equal to 200 then:
"The total (the value in the total variable) for the numbers entered is Large"
If the total is less than 200 then:
"The total (the value in the total variable) for the numbers entered is Small"
count = 0
while count <= 200:
x = int(input('Please enter a number to add: '))
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
elif x == 'done':
print ('The total',count,'for the number entered is Small')
break
elif x == ValueError:
print('Bad Data')
continue
Im a beginner so a little help would be cool.
When you accept the input value you need to check if it is a number before you try to convert it to an int. So you have two ways of doing this: either wrap the first line in a try except block to catch the value error or just check to see if the input they supply is actually a number. Also as Tim Roberts said above you can't check for "done" if you have already converted to an integer so that's why I have moved that check to the top of each example.
Version 1 (Try Except):
count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
try:
x = int(user_input)
except ValueError:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
Version 2 (Check if number):
count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
if user_input.isnumeric():
x = int(user_input)
else:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
PS. Adding the .lower() to the user_input allows them to type 'done' or 'DONE' or any combination of uppercase and lowercase and it will still exit.
I have edited your code a little bit. It might help you to understand the logic.
total = 0
while True:
userInput = input('Please enter a number to add: ')
if userInput == "done":
break
try:
x = int(userInput)
total += x
if total >= 200:
print('The total', total, 'for the number entered is Large')
elif total <= 200:
print ('The total',total,'for the number entered is Small')
except:
print("Bad Data")
A few notes. I have changed the count name to total since the logic of your problem seems to be closer to this name.
Output
Please enter a number to add: I am inputting bad data
Bad Data
Please enter a number to add: 100
The total 100 for the number entered is Small
Please enter a number to add: 0
The total 100 for the number entered is Small
Please enter a number to add: 50
The total 150 for the number entered is Small
Please enter a number to add: 30
The total 180 for the number entered is Small
Please enter a number to add: -50
The total 130 for the number entered is Small
Please enter a number to add: done
Asked a question earlier today, but managed to figure out my answer from earlier after some goofing around. I have a new question though. I'm still really new to python, and I'm working on my first mid-term project. My code currently runs exactly to the specifications the instructor has asked for, however I would like to add a little extra by making sure that the only input the code will accept from the user is an integer. I've looked at a posts and seen how it can be done, but I don't quite understand yet. Can someone show me how I would be able to write an exception handler into my code that continues to loop properly?
#will be used later to generate a random guess
import random
#Welcome Greeting
print("----------------------------------------------------")
print("Hello, and welcome to my Fall 2021 Mid-term Project.")
print("----------------------------------------------------\n\n")
#collect data for group size, give user the option to exit
groupSize = int(input("How many people are there in your group today? Or enter 0 to exit: "))
while groupSize != 0:
eachAge = 0
#prep user to enter values
print("\nWhy don't you tell me how old each person is?\n")
for eachLoop in range (1, groupSize+1):
age = int(input("# "+str(eachLoop)+" : "))
#make sure to add the ages of the group to each other to update the eachAge variable
eachAge += age
#divide the total age by the groupSize variable and round to 3 decimals
averageAge = round(eachAge/groupSize,3)
print("\nThe average age for this group is",str(averageAge)+".\n")
#generate a random guess between 1-100
randNum=random.randint(1,100)
print("I was going to guess %0.3f"%randNum)
if randNum < averageAge:
#i'm creating variables to make the fomatting in my string simpler
guessLow = float(averageAge-randNum)
print("\nI seem to have guessed too low, short by %0.3f" % guessLow)
elif randNum > averageAge:
guessHigh = float(randNum-averageAge)
print("\nIt looks like I guessed too high, over shot it by %0.3f" % guessHigh)
#this is extremely unlikely with the random guessing, I just thought it might be fun
else:
print("\nOh man, I guessed right on the money!")
#time to categorize our averaged age groups
if averageAge <= 19:
print ("\nYou have a group of very young people.\n\n")
elif averageAge >= 20 and averageAge <= 44:
print ("\nYou have a group of young people.\n\n")
elif averageAge >= 45 and averageAge <= 59:
print ("\nYou have a group of middle aged people.\n\n")
elif averageAge >= 60 and averageAge <= 74:
print ("\nYou have a group of young elderly people.\n\n")
elif averageAge >= 75 and averageAge <= 90:
print ("\nYou have a group of elderly people.\n\n")
else:
print ("\nYou have a group of long-lived people.\n\n")
print("----------------------------------------------------")
print("Why don't we give it another shot? Let's start over.")
print("----------------------------------------------------\n\n")
#reinitialize value back to 0 so that the program can run again from the beginning
groupSize = int(input("How many people are there in your group this time? Or enter 0 to exit: "))
if groupSize <= 0:
print("\n\n\n-`-`-`-`-`-`-`-`-`-`Thanks for trying out my program!`-`-`-`-`-`-`-`-`-`-")
Here is one way to continuously prompt the user until they enter an integer (or an exception is thrown, like KeyboardInterrupt if they press ctrl C):
def read_int(msg):
while True:
val_str = input(msg)
try:
return int(val_str)
except ValueError:
print('%r is not a valid integer' % val_str)
x = read_int('Please enter an integer')
print('user entered %d' % x)
The way it works is by calling input and converting it to an int, like you are doing. But using try/except, it handles the case where int(val_str) throws an exception if the input is not a valid integer. Normally the program would end and print the stack trace in that case, but if we catch it then we can do whatever we want: in this case, loop and call input again.
The loop ends when we return. You could also break if this is not inside its own function.
Without functions or try/except
For the purposes of learning, one way of doing it without functions or try except could involve manually checking if the string is a valid integer (but thanks to #chepner for pointing out that I first missed negative numbers, and that the python int() can handle far more than ascii 0-9 with an optional negative):
val_int = None
while True:
val_str = input(msg)
# Below is a crude way to implement
# the regex '[+-]?[0-9]+'
# make a copy of the string so that we can modify it
val_str_test = val_str
is_valid_int = True
# allow negative numbers in subsequent checks
# by removing the leading unary negative/positive if it exists
if len(val_str_test) > 0 and val_str_test[0] in [ '-', '+' ]:
val_str_test = val_str_test[1:]
# check if all characters in the string
# are between 0 and 9, to ensure this is a valid integer
for c in val_str_test:
if not('0' <= c <= '9'):
is_valid_int = False
break
# empty strings are also not valid integers, but wouldn't
# be caught by the above loop
if len(val_str_test) == 0:
is_valid_int = False
# if the user's string is not a valid integer,
# then loop to the beginning where we prompt the user to
# enter a string
if not is_valid_int:
continue
# I am pretty sure that in this case, int(val_str)
# can't throw an exception, besides maybe
# running out of memory or something outside the scope
# of this question
val_int = int(val_str)
break
Set a function to reprompt the person for a number:
def get_number(question):
value = input(question)
while 1:
try:
value = int(value)
break
except:
value = input(f'(must be a number) {question}')
return value
groupSize = get_number("How many people are there in your group this time? Or enter 0 to exit: ")
#or
age = get_number("# " + str(eachLoop) + " : ")
Your entire code would look like this:
# will be used later to generate a random guess
import random
# Welcome Greeting
print("----------------------------------------------------")
print("Hello, and welcome to my Fall 2021 Mid-term Project.")
print("----------------------------------------------------\n\n")
# collect data for group size, give user the option to exit
def get_number(question):
value = input(question)
while 1:
try:
value = int(value)
break
except:
value = input(f'(must be a number) {question}')
return value
while 1:
groupSize = get_number("How many people are there in your group this time? Or enter 0 to exit: ")
if groupSize == 0:
break
eachAge = 0
# prep user to enter values
print("\nWhy don't you tell me how old each person is?\n")
for eachLoop in range(1, groupSize + 1):
age = get_number("# " + str(eachLoop) + " : ")
# make sure to add the ages of the group to each other to update the eachAge variable
eachAge += age
# divide the total age by the groupSize variable and round to 3 decimals
averageAge = round(eachAge / groupSize, 3)
print("\nThe average age for this group is", str(averageAge) + ".\n")
# generate a random guess between 1-100
randNum = random.randint(1, 100)
print("I was going to guess %0.3f" % randNum)
if randNum < averageAge:
# i'm creating variables to make the fomatting in my string simpler
guessLow = float(averageAge - randNum)
print("\nI seem to have guessed too low, short by %0.3f" % guessLow)
elif randNum > averageAge:
guessHigh = float(randNum - averageAge)
print("\nIt looks like I guessed too high, over shot it by %0.3f" % guessHigh)
# this is extremely unlikely with the random guessing, I just thought it might be fun
else:
print("\nOh man, I guessed right on the money!")
# time to categorize our averaged age groups
if averageAge <= 19:
print("\nYou have a group of very young people.\n\n")
elif averageAge >= 20 and averageAge <= 44:
print("\nYou have a group of young people.\n\n")
elif averageAge >= 45 and averageAge <= 59:
print("\nYou have a group of middle aged people.\n\n")
elif averageAge >= 60 and averageAge <= 74:
print("\nYou have a group of young elderly people.\n\n")
elif averageAge >= 75 and averageAge <= 90:
print("\nYou have a group of elderly people.\n\n")
else:
print("\nYou have a group of long-lived people.\n\n")
print("----------------------------------------------------")
print("Why don't we give it another shot? Let's start over.")
print("----------------------------------------------------\n\n")
if groupSize <= 0:
print("\n\n\n-`-`-`-`-`-`-`-`-`-`Thanks for trying out my program!`-`-`-`-`-`-`-`-`-`-")
So I read a bit about using Try and Except and came up with this:
while True:
try:
groupSize = int(input("How many people are there in your group? Or enter 0 to exit. "))
break
except ValueError:
print("\n**Please enter an integer value only.\n**")
while groupSize != 0:
eachAge = 0
The rest of the code remains unchanged from what I did earlier until the end of the loop when I basically redo the same try/except handler to re-initialize the groupSize variable back to a user input.
I've created a simple program where the user is prompted to guess a number between 1 and 20. Originally my program just prompted the user if their input was too high or low. Later on I added a function that prompted the user when their input is out of range (below 1 or above 20). The program works fine, however I was wondering if my format and syntax are "correct" or "proper".
magic_number = 12
# get input from user
user_number = int(input('What is the magic number between 1 and 20 ? '))
# attempting to create an efficient while loop
while True:
if user_number < 12 and user_number >= 1:
# error message
print('Your number is too low. Please try again.')
# ask for input again
user_number = int(input('What is the magic number between 1 and 20 ? '))
elif user_number > 12 and user_number <= 20:
# error message
print('Your number is too high. Please try again.')
# ask for input again
user_number = int(input('What is the magic number between 1 and 20? '))
elif user_number < 1 or user_number > 20:
# error message
print('Your number is out of range. Please try again.')
# ask for input again
user_number = int(input('What is the magic number between 1 and 20? '))
elif user_number == magic_number:
print('Congratulations! You have guessed the magic number.')
break
If you're interested in the official "Pythonic" way to format your code, that's what the PEP8 specification is all about: https://www.python.org/dev/peps/pep-0008/.
Looking at your code, I have a couple of suggestions to possibly make things a little cleaner and easier to maintain:
Try to avoid hard-coding the same constant value (e.g. 1, 20, 12) in multiple places. That way if you want to change them later, you only have to change it in one place.
Try to avoid repeat logic in multiple places if you can help it (or move it into a function) for the same reason as #1. If you have a bug you only have to fix it in one spot.
There's a lot of things you could do, but here's an example of what it might look like just following those two comments:
magic_number = 12
min_number = 1
max_number = 20
# attempting to create an efficient while loop
while True:
# get input from user
user_number = int(input('What is the magic number between {} and {} ? '.format(min_number, max_number)))
if user_number < magic_number and user_number >= min_number:
print('Your number is too low. Please try again.')
elif user_number > magic_number and user_number <= max_number:
print('Your number is too high. Please try again.')
elif user_number < min_number or user_number > max_number:
print('Your number is out of range. Please try again.')
elif user_number == magic_number:
print('Congratulations! You have guessed the magic number.')
break
Maybe some future things to try out might be figuring out how to handle if the user doesn't enter a number or using the random module to generate a different magic number each time instead of hard-coding it to 12.
Good luck and hope that helps.
Simply, I am entering a value, I want to determine whether the value is alpha or not. If it is not alpha, I want to check if it is a number or not. If it is a number I want to check if it is positive or negative.
I read a lot about checking a signed number like -50. There are two ways, we can use something like this:
try:
val = int(x)
except ValueError:
print("That's not an int!")
Which I think I do not need it here and I do not know where to put it in my code.
The other way is to use .lstrip("-+"), but it is not working.
amount = 0
while True:
amount = input("Enter your amount ===> ")
if amount.isalpha() or amount.isspace() or amount == "":
print("Please enter only a number without spaces")
elif amount.lstrip("-+").isdigit():
if int(amount) < 0:
print("You entered a negative number")
elif int(amount) > 6:
print("You entered a very large number")
else:
print(" Why I am always being printed ?? ")
else:
print("Do not enter alnum data")
What am I doing wrong ?
This is how you would integrate a try/except block:
amount = 0
while True:
amount = input("Hit me with your best num!")
try:
amount = int(amount)
if amount < 0:
print("That number is too tiny!")
elif amount > 6:
print("That number is yuge!")
else:
print("what a boring number, but I'll take it")
break # How you exit this loop
except ValueError:
print("Wow dude, that's like not even a number")
It does all the heavy lifting for you, as int() can process numbers with +/- automatically.
>>> amount = '-6'
>>> '-' in amount
True
>>> amount = amount.strip('-')
>>> amount.isdigit()
True
Check if the number is less than 0 or greater than 0 with < >
I have been assigned in my intro to computer science class to write a program that will print out a number that the user is asked to enter (20-99). I have been able to do that, and have created an error message if the user doesn't enter a number in this range. The issue I am having is when a number out of range is entered, the error message displays, but for some reason the program continues and still prints out a english number. I have been trying to figure out how to get the program to stop at the error message, but I have not been able to figure it out. Here is what I currently have.
a=int(input('Pick a number between 20 through 99:'))
b=a//10
c=a%10
while a<20 or a>99:
print('Error, enter number between 20 and 99:')
break
while a>20 or a<99:
if b==2:
print('The number is Twenty',end=' ')
elif b==3:
print('The number is Thirty',end=' ')
elif b==4:
print('The number is Fourty',end=' ')
elif b==5:
print('The number is Fifty',end=' ')
elif b==6:
print('The number is Sixty',end=' ')
elif b==7:
print('The number is Seventy',end=' ')
elif b==8:
print('The number is Eighty',end=' ')
else:
print('The number is Ninety',end=' ')
if c==1:
print('One')
elif c==2:
print('Two')
elif c==3:
print('Three')
elif c==4:
print('Four')
elif c==5:
print('Five')
elif c==6:
print('Six')
elif c==7:
print('Seven')
elif c==8:
print('Eight')
else:
print('Nine')
break
The second conditional you want and not or
while a>20 and a<99:
also use if because it will infinite loop if you don't
You have confused "while" with "if". You need an "if" statement here; "while" is for things you intend to repeat.
Also, note that a>20 or a<99 is always true; any number is one or the other. I believe you wanted an "and" here, which makes this merely the "else" clause of the "if" statement.
Finally, I'm not sure what you're trying to do with the "end=" in your first bank of print statements. This is a syntax error.
You have put the break statement inside of the while loop. This means that when you reach that statement, you leave the while loop. So no matter what, your function will leave the loop. A good sign that your while loop is not correct or out of place is if you call a break at the end. Here is a better way.
while True:
a=int(input('Pick a number between 20 through 99:'))
if a > 20 and a < 99:
break;
else:
print("Error, enter number between 20 and 99")
What happens is that the loop goes on indefinitely. Once the correct input is entered, it breaks from the loop. If the input is not correct, it just loops again.
Even though you didn't ask about it, I'm going to comment on the other half as well. First, your condition doesn't make sense. All numbers are either over 20 or under 99. You need to use an and so that BOTH must be true. However, the other part is that you don't even need this conditional statement. We already know that we are in this limit. That's what we made sure of in our previous while loop. Lastly, as stated before, the while itself isn't need. If you want to use a conditional that you only use one time, just use an if statement. While is mean for looping and forces you to have a break statement at the end if you will only ever use it once. Here is your completed code:
while True:
a=int(input('Pick a number between 20 through 99:'))
if a > 20 and a < 99:
break;
else:
print("Error, enter number between 20 and 99")
b=a//10
c=a%10
if b==2:
print('The number is Twenty',end=' ')
elif b==3:
print('The number is Thirty',end=' ')
elif b==4:
print('The number is Fourty',end=' ')
elif b==5:
print('The number is Fifty',end=' ')
elif b==6:
print('The number is Sixty',end=' ')
elif b==7:
print('The number is Seventy',end=' ')
elif b==8:
print('The number is Eighty',end=' ')
else:
print('The number is Ninety',end=' ')
if c==1:
print('One')
elif c==2:
print('Two')
elif c==3:
print('Three')
elif c==4:
print('Four')
elif c==5:
print('Five')
elif c==6:
print('Six')
elif c==7:
print('Seven')
elif c==8:
print('Eight')
else:
print('Nine') `enter code here`