looping not exiting and not printing the results at the end [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping to create a code to output if a next number entered is Up, Down or Same as the first one. I wanted it to exit when '0' is entered. I also wanted it to print the 'Up', 'Down', or 'Same' result at the end when exited with '0' instead of each time a number is entered.(if user enters: 4, 6, 1, 1, then 0 to exit, the final output will be Up, Down, Same printed.) Please tell me what I am missing, here is what i have so far:
firstNumber = input('Please enter your first number:')
nextNumber=input('Enter the next number(0 to finish)')
while nextNumber !=0:
if firstNumber<nextNumber:
print ('Up')
elif firstNumber>nextNumber:
print ('Down')
elif firstNumber==nextNumber:
print ('Same')
firstNumber = nextNumber
nextNumber=input('Enter the next number(0 to finish)')

You are comparing string, not numbers.
You should cast your input to integers with int().
here:
try:
firstNumber = int(input('Please enter your first number:'))
nextNumber = int(input('Enter the next number(0 to finish)'))
except ValueError:
# Handle cast error here
pass
while nextNumber !=0:
...
Note
As blubberdiblub explained:
< > compare pointer code of strings, that means "8" < "10" returns False while 8 < 10 returns True

input
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So use
int(input(...))

Related

Input and if/else statements not processing correct input [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I'm putting together a small program for a friend that requires an input from the user, and depending on the input it does a certain function
Heres my code:
value = input ("Enter Number")
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")
However, even entering 1 or 2, it always prints "hmmm".
I've tried everything including making a new function and passing the input into it and still it doesn't take. Any advice?
That's because you are taking input as a string not an integer.
Because of it your value is string and when it is compared with integer 1 or 2 it's coming false and the else condition gets satisfied.
Correct code:
value = int(input ("Enter Number"))
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")

Compare string and integer in same if statement [duplicate]

This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
How can I read inputs as numbers?
(10 answers)
Closed 6 months ago.
I have a program that takes input from the user. I want to display an invalid option message if the input is a string or it is not a number between 1 to 4. I want to check all these 3 conditions in a single if statement.
ask_option = input("Your option: ")
if int(ask_option) != int and (int(ask_option) < 1 or int(ask_option) > 4):
print("Not a valid option")
I feel the int(ask_option) != int is incorrect. But is it possible to fulfill all these 3 in a single if statement?
My code fulfills the criteria to choose between 1-4 but doesn't work to check string input. Please help
input() will always return a string unless you explicity convert it. So using ask_option = int(input("Your option: ")) will already satisfy checking if ask_option is an integer as an exception will be raised otherwise.
As for evaluating the integer, you can accomplish this in a single line such as:
if not 1 <= ask_option <= 4:
print("Not a valid option")
If you try to convert string input into an int, the program will throw ValueError.
ask_option = input("Your option: ")
try:
val = int(ask_option)
if val <= 1 or val => 4:
print("Not a valid option!")
except ValueError:
print("Not a valid option!")
ask_option = input("Your option: ")
if len(ask_option) != 1 or ask_option < '1' or ask_option > '4':
print("Not a valid option")
else:
print( "valid option")
Edit:
OP: "I want to display an invalid option message if the input is a string or it is not a number between 1 to 4."
Therefore we need to accept values ranging from 1 - 4
We know that input() accepts everything as a string
so in the if statement
first condition: len(ask_option) != 1
We invalidate any string whose length is not equal to 1 ( since we need to accept values ranging from 1-4 which are of a length 1 )
And now we are left to deal with the input value whose length is just 1 which could be anything and will be checked with the next 2 conditions.
second and third condition: ask_option < '1' or ask_option > '4'
We do string comparison ( which is done using their ASCII values )
more on string comparison: String comparison technique used by Python
I would not recommend using this approach since it's hard to tell what it does on the first look, so it's better if you use try except instead as suggested in other answers.
See this solution as just a different approach to solve OP's problem ( but not recommended to implement. )

Validating int numbers in a certain range. Python-3.x [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:
def validateOpt(v):
try:
x = int(v)
if int(v)<=0:
x=validateOpt(input("Please enter a valid number: "))
elif int(v)>5:
x=validateOpt(input("Please enter a valid number: "))
return x
except:
x=validateOpt(input("Please enter a valid number: "))
return x
Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.
You can do this with a while loop, something like this should be a good start:
def getValidInt(prompt, mini, maxi):
# Go forever if necessary, return will stop
while True:
# Output the prompt without newline.
print(prompt, end="")
# Get line input, try convert to int, make None if invalid.
try:
intVal = int(input())
except ValueError:
intVal = None
# If valid and within range, return it.
if intVal is not None and intVal >= mini and intVal <= maxi:
return intVal
Then call it with something like:
numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)
use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.
def get_input(minimum, maximum):
while True:
try:
x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
if minimum <= x <= maximum:
return x
except ValueError as ve:
print("Thats not a valid input")
value = get_input(1, 5)
Use for loop in the range between 1 and 5
Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:
def f():
x = input("Enter an integer between 1 and 5:")
try:
x = int(x)
if x<=0 or x>5:
f()
except:
f()
f()

If condition is getting skipped even if the condition is true [duplicate]

This question already has answers here:
Python input does not compare properly [closed]
(2 answers)
Closed 3 years ago.
I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if a<0:
print "Please enter a number greater than or equal to 0"
else:
if(a==1 or a==0 ):
print "1"
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.
Comparing string with number returns False as result
'-2'< 0 ---> False --> if condition will be skipped
Convert the string to integer since factorial are only applied to integer
int('-2') < 0 ---> True --> if condition will be executed
x = raw_input().split(" ") returns strings data type in a list
so you can't use int for the entire list x,
only one string at the time
When invoking the if condition you are considering only one element in the list,
then convert from string to int before comparing to 0 --> int(a) < 0
The second point is related to indentation print (",".join(c))
should be included inside the else loop
Also
if(a==1 or a==0 ):
print "1"
is not needed as it has been take care in the for loop below
The code is as follow
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if int(a) < 0:
print "Please enter a number greater than or equal to 0"
else:
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
You might want to convert the input into int before doing int operations. Change this
x=raw_input().split(" ")
to
x=map(int, raw_input().split(" "))
x="-2 3 6 -3".split(" ")
c=[]
for a in x:
b=1
if int(a)<0:
print ("Please enter a number greater than or equal to 0" )
continue
else:
if(a==1 or a==0 ):
print ("1" )
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print (",".join(c))
o/p:
Please enter a number greater than or equal to 0
Please enter a number greater than or equal to 0
6,720
Two changes, int(a) in if condition and if you wish not to calculate the factorial for negative numbers then add continue

Python while loop ( doesnt comes out from while loop ) [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I want this python code comes out from loop when I enter 0 as input number of "num" variable But it continues printing these three lines constantly
Thanks
num = 10 #10 is dummy number for starting loop
while(num!=0):
print("1)Test func1")
print("2)Test func2")
print("0)Exit")
num = input("Enter a number:")
print("Comes out from while loop!")
There reason behind is that the input takes input as a string and you have to either convert it to int:
num = int(input("Enter a number:"))
or change the while loop:
while(num!='0'):
print takes input as string , in order to come out of loop
use
num = int(input("Enter a number:"))
it will consider num variable as an integer but not an string and will come out of the loop.
You have got a correct answer before this but you can change your code too:
while True:
print("1)Test func1")
print("2)Test func2")
print("0)Exit")
num = input("Enter a number:")
if num == '0':
break
print("Comes out from while loop!")
at the begining while always get True, you don't need to set value, 'break' means 'stop current loop and exit'

Categories

Resources