This question already has answers here:
How do I check if raw input is integer in python 2.7?
(5 answers)
Closed 6 years ago.
# Validating for only numbers in python one after another(in sequence)
a = raw_input()
#if a is a number then it should take next raw_input i.e., 'b' else it should ask for 'a' again
b = raw_input()
#if b is a number then it should take next raw_input i.e., 'c' else it should ask for 'b' again
c = raw_input()
#if c is a number then it should take next raw_input i.e., 'd' else it should ask for 'c' again
## This should be done upto 'e'
use a.isdigit() to validate string a is digit or not
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
Make use of if..else construct for the conditional checks and refer this post for the integer check.
Edit 1
I have not executed it,but you could try the following and see if it works-
def ask(text):
temp = raw_input(text)
try:
retVal = int(temp)
return retVal
except ValueError:
return False
a = False
b = False
c = False
while not a:
a = ask("Enter A:")
if a == False:
continue
while not b:
b = ask("ENter B:")
if b == False:
continue
while not c:
c = ask("Enter C:")
Related
I wonder why this code will give a result of 3 for count.
s = 'awb'
count = 0
for i in range (0, len(s)):
if s[i] == 'a' or 'b':
count += 1
print ("number of a and b: ", count)
I understand that in order to count the number of a and b, the if statement should look like:
if s[i] == 'a' or s[i] == 'b':
However, I am just curious why the if statement in my original code will result in all the characters in the string being counted?
The expression:
if s[i] == 'a' or 'b'
says if the current index of the string s == 'a' execute the code below this line. The second condition is True ('b' always evaluates to True in the context of truthiness in python). The second condition in the statement will make this if statement True. Therefore, count will always be incremented for each iteration the loop. Within the context of boolean evaluation a literal always evaluates to True. Consider the snippet below:
not not 'b'
If you execute this line of code by itself you'll see that the expression evaulates to True. 'b' was "casted" into a boolean value (True or False). This implicitly happens behind the scenes within the if statement in question.
There is no reason for it to through an error. Writting x == 5 or 4 would be evaluated as (x == 5) or 4 So the left hand of the or will be true when x is 5 but the right hand will always be true since truthyness will say any int thats not 0 is True. Now you may think well whats the point but there are valid use cases.
lets imagine we have a game that always gives a prize on the first go regardless if you were right or not then for each turn after that you only win if your correct.
prize_gauranteed = True
while True:
guess = int(input("Guess: "))
if guess == 5 or prize_gauranteed:
print("You win a prize")
prize_gauranteed = False
else:
print("No prize this time")
OUTPUT
Guess: 10
You win a prize
Guess: 10
No prize this time
Guess: 4
No prize this time
Guess: 5
You win a prize
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
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am new to python.
The following code should read an integer into the voting rating:
`rating = input('Enter an integer rating between 1 and 10')`
My doubt: The problem with the above code is it allows any values without error. How can I insert error message?
You can try to parse the string to an integer, and if you cannot, print accordingly, but if you can and the integer is between 1 and 10, decide accordingly
def check_int(s):
is_int = False
try:
int(s)
is_int = True
except:
pass
return is_int
rating = input('Enter an integer rating between 1 and 10>>')
#If string can be converted to integer
if check_int(rating):
#Convert it to an integer and compare ranges
r = int(rating)
if 1<=r<=10:
print('Integer is', r)
else:
print('Integer is not between 1 and 10')
#Else print error
else:
print('Not an integer')
The output will be
Enter an integer rating between 1 and 10>>11
Integer is not between 1 and 10
Enter an integer rating between 1 and 10>>6
Integer is 6
Enter an integer rating between 1 and 10>>hello
Not an integer
You use a function like this:
While the imput isn't correct, we ask a new input. We also check the input is an number with cast. If it's not a number, that will raise an exception that we catch in the try ... catch.
def getInputVal():
# Boolean equal to false while the input isn't correct
correct_answer = False
while (not correct_answer):
# Read the input (string)
val = input('Enter an integer rating between 1 and 10: ')
try: # Try to cast the string as an integer
val_int = int(val)
if (val_int >= 1 and val_int <= 10): # If the value is in the right interval
correct_answer = True # We go out of the loop
print("Well done, your value is: ", val_int) # We display the value
except: # If the cast raise an error
print("A number is expected") # An "error" message is shwon
I have a function named orderInt passed three integers and returns true if the three int are in ascending order, otherwise false. Here's my code so far:
def orderInt(a, b, c):
print "Enter 3 integers: "
a = input()
b = input()
c = input()
How do I compare the variables?
First of all, your indentation is wrong.
def orderInt():
print "Enter 3 integers: "
a = input()
b = input()
c = input()
if a<b<c:
return True
else:
return False
print orderInt()
Second, your function is taking three arguments and also taking inputs. The arguments passed will be overwritten by your inputs.
def orderInt():
print "Enter 3 integers: "
if a<b<c:
return True
else:
return False
a = input()
b = input()
c = input()
print orderInt(a,b,c)
Hope this helps.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm very new to Python, so forgive my newbish question. I have the following code:
[a while loop starts]
print 'Input the first data as 10 characters from a-f'
input1 = raw_input()
if not re.match("^[a-f]*$", input1):
print "The only valid inputs are 10-character strings containing letters a-f"
break
else:
[the rest of the script]
If I wanted to, instead of breaking the loop and quitting the program, send the user back to the original prompt until they input valid data, what would I write instead of break?
To go on with the next loop iteration, you can use the continue statement.
I'd usually factor out the input to a dedicated function:
def get_input(prompt):
while True:
s = raw_input(prompt)
if len(s) == 10 and set(s).issubset("abcdef"):
return s
print("The only valid inputs are 10-character "
"strings containing letters a-f.")
print "Input initial data. Must be 10 characters, each being a-f."
input = raw_input()
while len(input) != 10 or not set(input).issubset('abcdef'):
print("Must enter 10 characters, each being a-f."
input = raw_input()
Slight alternative:
input = ''
while len(input) != 10 or not set(input).issubset('abcdef'):
print("Input initial data. Must enter 10 characters, each being a-f."
input = raw_input()
Or, if you wanted to break it out in to a function (this function is overkill for this use, but an entire function for a special case is suboptimal imo):
def prompt_for_input(prompt, validate_input=None, reprompt_on_fail=False, max_reprompts=0):
passed = False
reprompt_count = 0
while not (passed):
print prompt
input = raw_input()
if reprompt_on_fail:
if max_reprompts == 0 or max_reprompts <= reprompt_count:
passed = validate_input(input)
else:
passed = True
else:
passed = True
reprompt_count += 1
return input
This method lets you define your validator. You would call it thusly:
def validator(input):
return len(input) == 10 and set(input).subset('abcdef')
input_data = prompt_for_input('Please input initial data. Must enter 10 characters, each being a-f.', validator, True)