Below is a piece of code from Python which has been bothering me for a while.
var=0
while (var <1 or var>100):
var=raw_input('Enter the block number ')
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
The problem is that the while loop iterates continuously without breaking. Can anyone help me how to break the loop.
Is there any way to implement a do..while in Python?
The problem is that raw_input returns a string. You're comparing a string with an integer which you can do in python 2.x (In python 3, this sort of comparison raises a TypeError), but the result is apparently always False. To make this work you probably want something like var=int(raw_input('Enter the block number'))
From the documentation:
objects of different types always compare unequal, and are ordered consistently but arbitrarily.
You're needlessly checking var twice, and you're trying to compare int and str (because raw_input returns a string), which doesn't work right. Try this:
var=0
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
You should convert your string to int.
var=0
while (var <1 or var>100):
# I changed here
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
else:
print 'ERROR!!! Enter again.'
You're running into an issue that strings (as returned by raw_input) are always greater than integers:
>>> "25" > 100
True
You need to convert your input to an integer first:
var = int(raw_input("Enter the block number "))
Of course, you'll want to be resilient in the face of bad input, so you'll probably want to wrap the whole thing in a try block.
hello you need to enter "break" and also var should be an integer, see below
while True:
var=int(raw_input('Enter the block number '))
if (var >=1 and var<=100):
print '\nBlock Number : ',var
break
else:
print 'ERROR!!! Enter again.'
continue
hope this helps
Related
So Im supposed to write a program that does the following
• Read an eight-digit integer entered by the user. If less or more then eight digits are entered prompt the user again for input
Ive tried the following methods yet they dont work, what do I do. Either it accepts asdfghjk as an eight digit number or it crashes the entire loop
number= input("Enter an eight digit number")
while True:
if len(number)==8 and number.isnumeric():
continue;
else:
number=input("Invalid Entry, Type again:")
number = int(input("Enter an eight digit number:"))
while True:
if number < 10000000 or number > 99999999:
number = input("Invalid Entry, Type again:")
else:
continue
I think you got the "continue" command wrong.
Continue jumps to the next iteration, e.g. starts again at the while loop. You should exchange it to "break", which breaks out of the loop continuing with the code after the while loop.
Edit: and also you can delete the semicolon after continue. There is no need for semicolons in python.
What do you wanna do if its 8 digit number? If u want to quit the loop, replace continue; by break
Use a single input() and place it inside the loop.
Then in this case I prefer the option to break when it's OK - rather than continue when it's not.
while True:
number = input("Enter an eight digit number")
if len(number)==8 and number.isnumeric():
break
print(f"{number=}")
Situation:
I'm creating a "Casting of Lots" game for school. I have a function to validate the user's input for how much they want to "wager" this round. I want to catch all errors, while print out different error messages based on the error and ask for input again.
Problem:
I caught every error, however, I can't seem to figure out how to loops my first try-except statement so that if an integer is entered twice, it will continue to catch the error.
Here's my code (the talents argument is going to be used later in the function):
def validate_wager(talents):
"""
Validates user input for wager, checks for strings, negatives, and excessively high numbers
"""
# formats wager request
print('{wager:-<34}'.format(wager="How much do you wish to wager? "), end=" ")
try:
# gets user input for wager, captures Type and Value
# errors, asks again
wager = int(input())
except:
wager = int(input('Wager must be a whole number: '))
# if wager is 0 or negative, prints error, asks again
while wager <= 0:
# captures Value and Type Errors within loop
try:
wager = int(input('Wager cannot be zero or negative: '))
except:
wager = int(input('Wager must be a non-negative, whole number: '))
# if wager is greater than remaining talents, prints error, asks again
while wager > int(talents):
# captures Value and Type Errors within loop
try:
wager = int(input('Wager cannot be more than remaining talents: '))
except:
wager = int(input('Wager must be a whole number and less than remaining talents: '))
return wager
This is the output for the first iteration after a string is entered once:
Welcome to the Lots Game
Talents you have to play with: 100
1 - Field Bet
2 - Pass Bet
3 - Quit
Choice --------------------------- 1
How much do you wish to wager? --- H
Wager must be a whole number:
The solution:
If a string is entered again, the try-except statement will not catch it. I'd like it to repeat "Wager must be a whole number" until an integer is entered.
I've already tried nesting the try-except statement inside a while loop that updates a variable with "True" or "False" if the is or is not an error, but that didn't work. I've tried a number of other things as well, but I just can't seem to figure it out. Any help would be greatly appreciated.
As all condition are based on wager, use only one while True loop, and break it only when all conditions are meet
while True:
try:
wager = int(input('Wager must be a number, strictly positive and less than remaining talents: '))
if 0 < wager < int(talents):
break
except ValueError:
print("Invalid number")
When you have multiples values to get frmo the user, use the while True construction once per value
New to Python (2.7). I'm trying to collect a user input that can either be an int or string (I'm assuming this is possible, though I'm not 100% sure). When I get to the statement that I've posted below, any number I enter prints the 'Invalid input' message and prompts me for a user input again, even if it's within the range I want it to be. Entering 'q' still works properly and returns if entered.
I've tried changing that first if statement to read (0 <= collectEyesBlade <= 9) ... with no luck either.
while True:
collectEyesBlade = raw_input(
"\nEnter desired blade number: ")
if collectEyesBlade in [range(0,9)]:
break
elif collectEyesBlade.lower() == 'q':
return
else:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
Since raw_input returns a str, start with the comparison that uses another string. Then, try to convert it to an int. Finally, if that succeeds, try the integer comparision.
while True:
collectEyesBlade = raw_input("\nEnter desired blade number: ")
if collectEyesBlade.lower() == 'q':
return
try:
collectEyesBlade = int(collectEyesBlade)
except ValueError:
print "\nInvalid input. Enter value between 0 and 9, or 'q' to quit"
continue
if collectEyesBlade in range(0,9):
break
if collectEyesBlade in [str(x) for x in range(0,9)] - this should work since collectEyesBlade is a string so we need to compare it to a string
You've hit at two of the little quirks of Python. One: a range is itself an iterable, but it's possible to put an iterable inside of another iterable.
In other words, your statement
if collectEyesBlade in [range(0,9)]:
is checking to see whether collectEyesBlade is an item in the list, which has only one item: a range iterable. Since you're not entering a range iterable, it's failing.
You can instead say
if collectEyesBlade in list(range(0,9)):
which will turn the range iterable into an actual list, or just
if collectEyesBlade in range(0,9):
Either should do what you intend.
However, as another answerer has mentioned, that's only half the problem. If your input were actually possibly integer type, the above would be sufficient, but you're asking for a string input. Just because the input is a "1" doesn't mean it's not a string one.
There are a couple of options here. You could do a try-except converting the string input into an integer, and if it fails because the string can't be converted into an integer, move on; or you could convert the range/list of numbers to compare to into strings.
I want to check if a user entered a number as percent format (18.06) instead of decimal format (0.1806), and always convert to decimal format.
Currently, I check to see if the value > 1, and if so, divide by 100. This works in my use case, but I can imagine some edge cases where it doesn't work. Is there a better solution?
UPDATE: let's assume it's a float, and therefore all strange characters, i.e. %s, have been removed.
Since you likely take the user input as a string(?) you could check the last digit to see if it is a "%"
if user_input[-1] == "%":
user_val = float(user_input[:-1]) / 100.0
else:
user_val = float(user_input)
assuming that you want to keep the original str value as well, otherwise use the same var.
It would be preferable imho to be explicit with the users as to the format that you want the input to be, as (pointed out by #pushkin) vals can be 0.5% as a valid input.
to be clear about the format of the input, then perhaps
while True: # if Py2.7 use raw_input instead of input
user_res = input("For 5% please enter 5. For 44.7%, please enter 44.7")
try: # handle invalid input that is not a number
user_val = float(user_res)
if (user_val >100) or (user_val < 0): # check upper and lower bound
print("Invalid entry- outside bonds")
else:
confirm = input("{}% to be recorded as your entry- confirm (Y/n) ".format(user_val))
if confirm.upper == "Y":
break
else:
print("Please try again")
except:
print("Invalid entry- nAn")
Someone downed me for this answer even though it's the only one and not marked as duplicate, so if you find it useful please upvote- thanks.
I'm trying to teach myself python right now, and I'm using exercises from "Learn Python The Hard Way" to do so.
Right now, I'm working on an exercise involving while loops, where I take a working while loop from a script, convert it to a function, and then call the function in another script. The only purpose of the final program is to add items to a list and then print the list as it goes.
My issue is that once I call the function, the embedded loop decides to continue infinitely.
I've analyzed my code (see below) a number of times, and can't find anything overtly wrong.
def append_numbers(counter):
i = 0
numbers = []
while i < counter:
print "At the top i is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
count = raw_input("Enter number of cycles: ")
print count
raw_input()
append_numbers(count)
I believe you want this.
count = int(raw_input("Enter number of cycles: "))
Without converting the input to integer, you end up with a string in the count variable, i.e. if you enter 1 when the program asks for input, what goes into count is '1'.
A comparison between string and integer turns out to be False. So the condition in while i < counter: is always False because i is an integer while counter is a string in your program.
In your program, you could have debugged this yourself if you had used print repr(count) instead to check what the value in count variable is. For your program, it would show '1' when you enter 1. With the fix I have suggested, it would show just 1.
convert the input string to integer... count=int(count)
Above has been cleared why the while looped for ever. It loops for a lot(=ASCII code which is really big)
But to fix the while you can simply:
while i<int(counter):
print "At the top i is %d" % i
numbers.append(i)
raw_input returns a string, but i is an integer. Try using input instead of raw_input.