Compare string and integer in same if statement [duplicate] - python

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. )

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")

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

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(...))

Python User input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm writing a game that prompts the user to input the number of rows. The problem I'm having is how do I get the program to keep prompting the user until they enters a whole number. If the user enters a letter or a float such as 2.5, the int value will not work, and thus I cannot break out of the loop. The program crashes. The int is essential so that I can check the number. The input must be even, it must be greater then or equal to 4 and less then equal to 16. Thanks!
def row_getter()->int:
while True:
rows=int(input('Please specify the number of rows:'))
if (rows%2 == 0 and rows>=4 and rows<=16):
return rows
break
You're on the right path, but you want to use a try/except block to try and convert the input to an integer. If it fails (or if the input is not in the given bounds), you want to continue and keep asking for input.
def row_getter()->int:
while True:
try:
rows=int(input('Please specify the number of rows:'))
except ValueError:
continue
else: # this runs when the input is successfully converted
if (rows % 2 == 0 and >= 4 and rows <= 16):
return rows
# if the condition is not met, the function does not return and
# so it continues the loop
I guess the pythonic way to do it would be:
while True:
try:
rows = int(input('Please specify the number of rows:'))
except ValueError:
print("Oops! Not an int...")
continue
# now if you got here, rows is a proper int and can be used
This idiom is called Easier to Ask Forgiveness than Permission (EAFP).
Could also make isint helper function for reuse to avoid the try/except in main parts of code:
def isint(s):
try:
int(s)
return True
except ValueError:
return False
def row_getter()->int:
while True:
s = input('Please specify the number of rows:')
if isint(s):
rows = int(s)
if (rows % 2 == 0 and rows >= 4 and rows <= 16):
return rows

If the user input is a string how do you tell the user to input a number [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
user_input = float(input("Please enter a multiplier!")
if user_input == int:
print " Please enter a number"
else:
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
The program will run effectively, as for any number entered by the user the result will be effective, yet I wish to know a function that allows the user to ask for a number when they enter a letter.
Use a try/except inside a while loop:
while True:
try:
user_input = float(raw_input("Please enter a multiplier!"))
except ValueError:
print "Invalid input, please enter a number"
continue # if we get here input is invalid so ask again
else: # else user entered correct input
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
break
Something that's a float is not an int. They're separate types. You can have a float that represents an integral value, like 1.0, but it's still a float.
(Also, user_input == int isn't checking whether user_input is an int, it's checking whether user_input is actually the type int; you wanted isinstance(user_input, int). But since that still won't work, let's skim over this part…)
So, can you check that a float has an integral value? Well, you can do this:
if int(user_input) == user_input
Why? Because 1.0 and 1 are equal, even though they're not the same type, while 1.1 and 1 are not equal. So, truncating a float to an int changes the value into something not-equal if it's not an integral value.
But there's a problem with this. float is inherently a lossy type. For example, 10000000000000000.1 is equal to 10000000000000000 (on any platform with IEEE-854 double as the float type, which is almost all platforms), because a float can't handle enough precision to distinguish between the two. So, assuming you want to disallow the first one, you have to do it before you convert to float.
How can you do that? The easiest way to check whether something is possible in Python is to try it. You can get the user input as a string by calling raw_input instead of input, and you can try to convert it to an int with the int function. so:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
If you need to ultimately convert the input to a float, you can always do that after converting it to an int:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
else:
user_input = float(user_input)
You could use the assert-statment in python:
assert type(user_input) == int, 'Not a number'
This should raise an AssertionError if type is not int. The function controlling your interface could than handle the AssertionError e.g. by restarting the dialog-function

Python: Display and count divisors of two integers

Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :

Categories

Resources