Stopping a while statement - python

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`

Related

Guess the number game Python (while loop)

I am trying to create a game that will ask the user to make a guess and if the guess is lower than the randomly generated integer, then it'll print ('Too low! Try again.), if the guess higher than the guess then it will print ('Too high! Try again) and if guess is equal to the random integer then it will ask the user if she wants to play again. This is where I am having trouble with - how can I have the code loop it back to recreate the random integer and start the loop if 'y' is entered?
import random
def main():
again='y'
count=0
while again=='y':
print('I have a number between 1 to 1000.')
print('Can you guess my number?')
print('Please type your first guess')
number=random.randint(1, 1000)
print(number)
guess=int(input(''))
while guess !='':
if guess>number:
print('Too high, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess<number:
print('Too low, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
else:
print('You entered an invalid value')
main()
You can do this by just adding one line with your code, use break in the inner while loop, in this portion below, it will break the inner loop if user guessed the number accurately with getting new input of again, then if again = 'y' it will start the outer loop again and random will generate again, otherwise the game will end.
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break # added this `break`, it will break the inner loop
Since you are in two loops you have to break the deepest one. Here are two ways for your situation.
Eather update "guess" to: '':
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
guess=''
Or add a break after the again input:
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break

How do I exit a while loop?

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.

Why does this print the error message twice?

New to stackoverflow, and new to python (python-3). Currently learning on edx.org and ran into the following error.
I created a function that checks a user-input str against the answer str and returns True or False.
When testing the function, I created a while loop to stop at the 3rd unsuccessful attempt. However, whenever there is an unsuccessful attempt, the function prints the error message twice when it should only print it once.
I fixed the error by storing the returning Bool value of the function into a variable rather than calling the function directly in the if condition within the while loop. However, I would like to understand the logic behind the error message printing twice. Here is the original code that prints the error message twice :
def letter_guess(letter, guess):
if len(guess) == 1 and guess.isalpha() and guess < letter:
print(guess,"is lower than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess > letter:
print(guess,"is higher than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess == letter:
print("Correct answer!")
return True
else:
print("Please only enter one alphabet for the letter. Try again.\n")
return False
answer2 = "m"
guess2 = input("Please enter a single alphabet : ")
i = 0
while i < 3:
if letter_guess(answer2, guess2):
break
elif letter_guess(answer2, guess2) == False and i == 2:
print("You have reached 3 guesses. Game over.")
break
else:
i += 1
guess2 = input("Please guess again : ")
You want to call input() inside the while loop:
# ...
answer2 = "m"
i = 0
while i < 3:
guess2 = input("Please enter a single alphabet : ")
# ...
Otherwise the user doesn't have a chance to change their answer, guess2 never changes and they get the same error message multiple times.
You call the function twice, in first if and in elif, with the same wrong guess. You fixed it right calling only once and storing the return value.
I try to explain it better: the function is always called by the first if, to evaluate its condition; if return value is false, is called again to evaluate the elif condition, with same arguments as before.

Collatz Function: Strange try/except Bugs

So I'm getting into coding and I was doing an exercise from the Automate the Boring Stuff book. I figured out how to write the original function, but then I wanted to try to add a little more to it and see if I could fit it all in one function.
So in Python 3.6.2, this code works fine if I enter strings, positive integers, nothing, or entering "quit". However, if I enter 1 at any point between the others then try "quitting", it doesn't quit until I enter "quit" as many times as I previously entered 1. (like I have to cancel them out).
If I enter 0 or any int < 0, I get a different problem where if I then try to "quit" it prints 0, then "Enter a POSITIVE integer!".
Can't post pics since I just joined, but heres a link: https://imgur.com/a/n4nI7
I couldn't find anything about this specific issue on similar posts and I'm not too worried about this working the way it is, but I'm really curious about what exactly the computer is doing.
Can someone explain this to me?
def collatz():
number = input('Enter a positive integer: ')
try:
while number != 1:
number = int(number) #If value is not int in next lines, execpt.
if number <= 0:
print('I said to enter a POSITIVE integer!')
collatz()
if number == 1:
print('How about another number?')
collatz()
elif number % 2 == 0: #Checks if even number
number = number // 2
print(number)
else: #For odd numbers
number = number * 3 + 1
print(number)
print('Cool, huh? Try another, or type "quit" to exit.')
collatz()
except:
if str(number) == 'quit':
quit
else:
print('Enter an INTEGER!')
collatz()
collatz()

My while loop never reaches the conditional stament and keeps looping

The assignment was to make a guessing game where the parameter is the answer. At the end if the person gets it right, it prints a congratulatory statement and returns the number of tries it took, if they type in quit, it displays the answer and tries == -1. other than that, it keeps looping until they get the answer correct.
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1
When i run it, no matter what i put in it just keeps asking me for my guess.
Since you called your variable num so I'm guessing it's a integer, you were checking equality between an integer and a string so it's never True. Try changing the num to str(num) when comparing, so:
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1
Is the code properly indented?
The body of the function you are defining is determined by the level of indentation.
In the example you pastes, as the line right after the def has less indentation, the body of the function is 'empty'.
Indenting code is important in python
Additionally, for assigning one value to a variable you have to use a single '=', so the:
tries == -1
should be
tries = -1
if you want to assign the -1 value to that variable.

Categories

Resources