I don't understand why when the user enters "0" the loop won't exit.
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
if integerIn == "0":
done = True
else:
integers.append(integerIn)
return integers
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
Everything above here is fine, but as soon as you got to the comparison, you forgot that you've casted the input to an int.
if integerIn == "0":
Should be
if integerIn == 0:
The reason is because integerIn is an integer and you are treating it like a string in if integerIn=="0". Replace it with integerIN==0 will do the job.
You're converting to an integer and then checking for equality with the string "0".
EDIT: screw the advice about using input or raw_input. Just saw you python 3.x tag, but decided to leave it for future readers.
You have few problems there...
First, in this line:
integers.append(integerIn)
where is integers to begin with? unless it's a global name you must define it in your function.
Second, in this line:
if integerIn == "0":
you're comparing integer to string here, and here's a thing: in python (using python 2.7 here) a string will be bigger than any number if you're doing a comparison, so integerIn == "0" will evaluate to False, always.
Fix it with this:
if integerIn == 0:
Finally, I should tell you this... your code the way it looks like will throws NameError instead of executing what you've done in your except statement.
Try it with the following test cases and try to explain the behavior yourself :)
Please enter an integer < 0 to finish >: test
Please enter an integer < 0 to finish >: "test"
To avoid such problem next time, use raw_input instead of input. So this line:
integerIn = input("Please enter an integer < 0 to finish >: ")
should be like this:
integerIn = raw_input("Please enter an integer < 0 to finish >: ")
NOTICE: I'm not sure but I think raw_input doesn't exist in python 3.x, instead input there will do exactly the same. please correct if I'm wrong.
However, If you're using python 3 then I think you should have no problem.
Here's input vs raw_input() in python 2.x:
input will evaluate the user input then return it.
raw_input will return the user input as string.
so:
# python 2.x
foo = input("input something") # input 3 + 5
print foo # prints 8
bar = raw_input("input something") # input 3 + 5
print bar # prints "3 + 5"
Try this
if integerIn == 0:
should work now.
Related
I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function
So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break
I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have a function that evaluates input, and I need to keep asking for their input and evaluating it until they enter a blank line. How can I set that up?
while input != '':
evaluate input
I thought of using something like that, but it didn't exactly work. Any help?
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input with input.
This is a small program that will keep asking an input until required input is given.
we should keep the required number as a string, otherwise it may not work. input is taken as string by default
required_number = '18'
while True:
number = input("Enter the number\n")
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
or you can use eval(input()) method
required_number = 18
while True:
number = eval(input("Enter the number\n"))
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
you probably want to use a separate value that tracks if the input is valid:
good_input = None
while not good_input:
user_input = raw_input("enter the right letter : ")
if user_input in list_of_good_values:
good_input = user_input
Easier way:
required_number = 18
user_number = input("Insert a number: ")
while f"{required_number} != user_number:
print("Oops! Something is wrong")
user_number = input("Try again: ")
print("That's right!")
#continue the code
I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
if foo != guessfoo:
print('haha, fail.')
Why doesn't this work? And how should I be doing it? I am a beginner at this, please help!
With python version 3 :
input() returns a 'str' (string) object. A string compares to an integer returns False :
1 == '1'
False
You must cast your input like that :
guessfoo = int(input('Guess my number: '))
Don't forget to try...except if the result of the input cannot be casted into an int.
Full example code :
try:
foo = 1
guessfoo = int(input('Guess my number: '))
if foo == guessfoo:
print('Well done, You guessed it!')
else:
print('haha, fail.')
except ValueError:
# cannot cast your input
pass
EDIT:
With python version 2 :
Thanks for this comment :
In previous versions, input would eval the string, so if the user typed in 1, input returned an int.
Ouput or your original code:
$ python2 test.py
Guess my number: 1
Well done, You guessed it!
Currently you have no condition to stop the loop. You're just printing stuff. Put a break after you guessed the number, or set loop to a different value than 1.
Because integers (foo) aren't strings (result of input()).
If you think that Python behaves like PHP or Perl then you are wrong
1 is something completely different than '1'.
You have to either convert the string using int(..) to an int or check against 'foo'
as a string.
It looks like the first problem will be an infinite loop, since the condition you're checking each iteration will always be true with the above code. When you loop, you need to make sure you change something that will bring loop closer to that condition. As a start, your code should look like this:
loop = 1
while loop == 1:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
loop = 0
if foo != guessfoo:
print('Oh no, try again')
This will cause the loop to finish executing if the number is actually guessed.
The next problem is that input returns a String, so the check to see if the entered number is equal to the expected number will always fail. In python, use the int() function to convert a string to a number, so that line looks like:
guessfoo = int(input('Guess my number: '))
At this point, you should have a decently-working loop. However, there are a few things you could do to make your code simpler. Here are some suggestions, starting with the simplest tweaks and moving to cleaner code.
The first step could be to use if...else to make sure only one condition is executed, and you only have to check the value of foo once. If the condition is true, the first branch is executed; if it fails, execution proceeds to the else block.
loop = 1
while loop == 1:
foo = 1
guessfoo = int(input('Guess my number: '))
if foo == guessfoo:
print('Well done, You guessed it!')
loop = 0
else:
print('Oh no, try again')
This works, but we can also move the check for a correct result in the condition of the loop. This way, the program only loops until the number is displayed:
foo = 1
guessfoo = 0
while foo != guessfoo:
guessfoo = int( input( 'Guess my number: ' )
if guessfoo != foo:
print( 'Oh no, try again' )
print( 'Well done, You guessed it!' )
Now the success message will only be displayed when foo == guessfoo. This loop is a bit clearer and simpler.
As a beginner, you've chosen a great place to ask for help! Welcome to StackOverflow!
Also, should you be using two different if's?
shouldn't it be something more like
if foo == guessfoo:
print('Well done, you guessed it!')
else:
print('haha, fail.')
import random
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
foo = random.randint(1,10)
while True:
guess = int(inp('Guess my number: '))
if guess < foo:
print('Too low!')
elif guess > foo:
print('Too high!')
else:
print('You got it!')
break