Why doesn't my code enter a loop? - python

def is_number(s):
try:
float(s)
return True
except ValueError:
return False
flag = True
while flag != False:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
flag = True
break
else:
print "Error, only numbers are allowed"
I do not see the problem.
Why doesn't it enter a loop?
Doesn't print anything, just gets stuck.

flag = False is not required here:
else:
print "Error, only numbers are allowed"
flag = False <--- remove this
Simply use:
while True:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
break
else:
print "Error, only numbers are allowed"
demo:
Enter your first number: foo
Error, only numbers are allowed
Enter your first number: bar
Error, only numbers are allowed
Enter your first number: 123

try this:
while True:
numInput = raw_input("Enter your first number: ")
try:
numInput = float(numInput)
break
except:
print "Error, only numbers are allowed"

Related

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

How to make a specific string work in a try-except block?

I don't want to make the user be able to enter anything other than numbers as the input for the "number" variable, except for the string "done".
Is it possible to somehow make an exception to the rules of the try-except block, and make the user be able to write "done" to break the while loop, while still keeping the current functionality? Or should I just try something different to make that work?
while number != "done":
try:
number = float(input("Enter a number: ")) #The user should be able to write "done" here as well
except ValueError:
print("not a number!")
continue
Separate the two parts : ask the user and verify if it is done, then parse it in a try/except
number = None
while True:
number = input("Enter a number: ")
if number == "done":
break
try:
number = float(number)
except ValueError:
print("not a number!")
continue
print("Nice number", number)
Instead of trying to make exceptions to the rules, you can instead do something like,
while True:
try:
number=input("Enter a number: ")
number=float(number)
except:
if number=="done":
break
else:
print("Not a number")
Check if the error message contains 'done':
while True:
try:
number = float(input("Enter a number: "))
except ValueError as e:
if "'done'" in str(e):
break
print("not a number!")
continue
also in this case continue is not necessary here (for this example at least) so it can be removed
Maybe convert the number to float afterwards. You can check if number is not equal to done,then convert the number to float
number = 0
while number != "done":
try:
number = input("Enter a number: ") #The user should be able to write "done" here as well
if number=="done":
continue
else:
number = float(number )
except ValueError:
print("not a number!")
continue
There are various ways to approach this situation.
First one that came across my mind is by doing:
while True:
user_input = input("Enter a number: ")
if user_input == "done":
break
else:
try:
number = float(user_input)
except ValueError:
print("not a number!")
continue
while True:
try:
user_input = input("Enter a number: ")
if user_input == "done":
break
number = float(user_input)
except ValueError:
print("not a number!")
continue
You can cast the input to float after checking if the input is 'done'

Better way to ask user input in integer form in Python?

So I'm kind of very beginner to programming and just learning yet the basics. Now I would like to have my python program to ask the user to give a number and keep asking with a loop if string or something else is given instead.
So this is the best I came out with:
value = False
while value == False:
a = input("Give a number: ")
b = 0
c = b
try:
int(a)
except ValueError:
print("No way")
b += 1
if c == b:
value = True
So is there easier and better way to do this?
You can use this:
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
or this:
while True:
a = input("Give a number: ")
if a.isdigit():
break
print("No way")
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
continue
This will continue to prompt the user for an integer till they give one.
value = True
while value == True:
a = input("Give a number: ")
try:
int(a)
except ValueError:
print("No way")
continue
print("Yay a Number:", a)
value = False
Is this what you need?

How can my code only accept integers in Python?

My code distinguishes whether the input is valid or not. It's not supposed to accept zero or words. If the user plugs zero in, it works and says "anything but zero", "try again" BUT when it asks again, it accepts anything. What do I do to make it continue to ask until there is a valid input??
So far I got:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Please help! Thank you all!
You need to use a loop:
while True:
A = raw_input('Enter A:')
try:
A = float(A)
except ValueError:
print "enter a float!"
else:
if A == 0:
print "Enter not 0"
else:
break
The simplest approach is use a while loop and to move all the logic inside the try breaking if the cast is successful and not equal to 0:
while True:
try:
A = float(raw_input('Enter A: '))
if A != 0:
break
print "anything but zero"
except ValueError:
print "HEY! that is not a float!"
If you actually only want integers you should be casting to int not float.
Use a while loop:
valid = false
while not valid:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
valid = true
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Hope this helps :)
while 1==1:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
#valid input
break
except ValueError:
print "HEY! that is not a float!"

python: raw_input function back to top again

I have a raw_function looks like:
number = raw_input('number (empty to finish): ')
if len(number) == 0:
print
print
print 'finished'
print
print
return def()
else:
pass
while True:
try:
column2 = int(raw_input('Enter column: '))
break
except ValueError:
print 'You did not supply an integer. Please try again. '
When i finish answering my second raw_input, I would like to return to first raw_input.
How can I do this?
Thanks in advance.
while True:
number = raw_input('number (empty to finish): ')
if not number:
print "\n\nfinished\n\n\n"
return def()
while True:
try:
column2 = int(raw_input('Enter column: '))
break
except ValueError:
print 'You did not supply an integer. Please try again. '

Categories