I am trying to understand why Python is not getting into the loop and exiting with an error code.
On the same time OR condition works fine.
def user_choice():
choice=''
within_range = False
while choice.isdigit == False and within_range == False:
choice=input('Enter valid selection (1-9): ')
if choice.isdigit() == False:
print('You entered non-digit value, please input digit')
if choice.isdigit() == True:
if int(choice) in range(0,10):
within_range=True
else:
within_range=False
return int(choice)
There is also another flaw in the following blocks of code:
(you should change the "and" with "or" to get a proper result, otherwise regardless of what integer you put in( not inside the range), it will return that!
def player_choice():
choice=' '
within_range = False
while choice.isdigit() == False **or** within_range == False:
choice=input('Enter valid selection (0, 1, 2): ')
if choice.isdigit() == False:
print('You entered non-digit value, please input digit(0, 1, 2)')
if choice.isdigit() == True:
if int(choice) in range(0,3):
within_range=True
else:
within_range=False
return int(choice)
You have error in this line:
while choice.isdigit == False and within_range == False:
You are comparing function str.isdigit with boolean False
You should instead evaluate function choice.isdigit()
Full fixed version:
def user_choice():
choice = ''
within_range = False
while choice.isdigit() == False and within_range == False:
choice = input('Enter valid selection (1-9): ')
if choice.isdigit() == False:
print('You entered non-digit value, please input digit')
if choice.isdigit() == True:
if int(choice) in range(0, 10):
within_range = True
else:
within_range = False
return int(choice)
Related
(im noob) I'm having a problem using the keyboard module, every time I use it all the input I enter will be visible on the next input statement.
while pamatoChooser:
pamatoChooser = True
pamatoScreen = True
piliCardo()
ownedChecker()
backUseNext()
inputChooser = keyboard.read_key()
if inputChooser == ("1"):
inputPamato = ('1')
break
elif inputChooser == ("b"):
# nothing here yet
pass
elif inputChooser == ("Esc"):
bMain = False
pamatoScreen = False
break
elif inputChooser == "n":
transition1()
johnnyLoop = True
while johnnyLoop:
piliJohnny()
ownedChecker()
backUseNext()
inputChoose1 = str(input("Choose your pamato: "))
if inputChooser == ('1'):
inputPamato = ('2')
pamatoChooser = False
break
elif inputChooser == ('b'):
transition2()
break
This code is showing the error. But we type it in a different way it runs. I am not getting it.
any one please help me why the second code isn't showing the error?
You can check the error by this link:
def check_input():
choice = 'wrong'
digit = False
while choice.isdigit() == False or digit == False:
choice = input('Enter the value: ')
if choice.isdigit() == False:
print('Please enter the digit between 0 to 10')
if choice.isdigit() == True:
if int(choice) < 1 and int(choice) > 10:
digit = False
else:
choice = True
return int(choice)
def check_input():
choice = 'wrong'
within_range = False
acceptable_range = range(0,10)
while choice.isdigit() == False or within_range == False:
choice = input('Enter the value: ')
if choice.isdigit() == False:
print('Please enter the digit between 0 to 10')
if choice.isdigit() == True:
if int(choice) in acceptable_range:
within_range = True
else:
within_range = False
return int(choice)
The first code has this line:
choice = True
which, when executed, makes choice a value of type bool. That's why, the next time choice.isdigit() is executed, and because bool objects really don't have an isdigit attribute, you get the error.
The second code doesn't do that, so you don't get the error.
My while loop does not break even after successful while recall. I need to check if the number exists and if it doesnt my while loop should break and successfull print out the number apart from 1 / 3 or 6
def is_1(inp):
if inp == 1:
print("1 it is")
return False
def is_3(inp):
if inp == 3:
print("3 it is")
return False
def is_6(inp):
if inp == 6:
print("6 it is")
return False
# ------------------------
me = False
while me != True:
try:
inpp = int(input("Please enter a number : "))
if any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
me = False
else:
me = True
print(inpp)
except IndexError:
print('Inappropriate domain and username')
Each of the functions is_1(), is_3(), is_6() returns None when the respective condition is not met.
This means, if you enter any number other than 1, 3, or 6, this will lead to an array containing only Nones in the line
if any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
i.e.
if any([None,None,None]) == False:
This, in turn, will evaluates to False.
In other words, the line me = True is never reached.
In order to fix this, you need to make the three methods above return something that evaluates to True if the condition isn't met (i.e. when you are passing in anything else than 1,3, or 6).
You just add a break and rewrite you if statements. That would break your loop. (Also according to what #p3j4p5 wrote)
Here is the code:
def is_1(inp):
if inp == 1:
print("1 it is")
return False
def is_3(inp):
if inp == 3:
print("3 it is")
return False
def is_6(inp):
if inp == 6:
print("6 it is")
return False
# ------------------------
me = False
while me != True:
try:
inpp = int(input("Please enter a number : "))
if inpp not in (1, 3, 6):
me = True
print(inpp)
break
elif any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
me = False
except IndexError:
print('Inappropriate domain and username')
Now if the input is not in 1 or 3 or 6 it will break. Is this the solution?
The problem is_1, is_3, and is_6 will evaluate to none if inp != 1, and because of the code also to false if inp ==1
def is_1(inp):
if inp == 1:
print("1 it is")
return False
2-
any([item1, item2, ....]) returns true if any (or at least one) of the items is true. Otherwise It returns false
And because is_1 and is_3 and is_6 always return false or none, any([is_1(inpp),is_3(inpp),is_6(inpp)]) will always be false and me will always be false.
To fix the issue, is_1 and is_3 and is_6 needs to return a true value:
def is_1(inp):
if inp == 1:
print("1 it is")
return True
def is_3(inp):1
if inp == 3:
print("3 it is")
return True
def is_6(inp):
if inp == 6:
print("6 it is")
return True
# ------------------------
me = False
while me != True:
try:
inpp = int(input("Please enter a number : "))
if any([is_1(inpp),is_3(inpp),is_6(inpp)]) == False:
me = False
else:
me = True
print(inpp)
except IndexError:
print('Inappropriate domain and username')
I am doing an excercise, created a while loop but it is printing everything twice. I'm pretty new at programming, so excuse me if this is some kind of stupid easy mistake.
def user_choice():
choice = "wrong"
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a number (0-10): ")
if choice.isdigit() == False:
print("Please enter a digit!")
if within_range == False:
print("Please enter a number in range (0-10)")
if choice.isdigit() == True:
within_range = int(choice) in range(0,10)
return int(choice)
Having multiple if statements means that it's possible the code will hit all 3 depending on the conditions.
Changing them to an if else block means it can only use one of them.
It's checks for a condition match from the top down so if it finds the conditions match in the first if then It would skip the remaining 2 options.
Your way, it would check the first if, and if it evaluates to True it would fire the code in the if block and then check the second if statement etc etc and so on.
Try this:
`def user_choice():
choice = "wrong"
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a number (0-10): ")
if choice.isdigit() == False:
print("Please enter a digit!")
elif within_range == False:
print("Please enter a number in range (0-10)")
elif choice.isdigit() == True:
within_range = int(choice) in range(0,10)
return int(choice)`
You are evaluating the responses in the wrong order to be handled by the while statement.
Here is one way:
def user_choice():
choice_is_digit = False
within_range = False
while choice_is_digit == False or within_range == False:
choice = input("Please enter a number (0-10): ")
choice_is_digit = choice.isdigit()
if choice_is_digit == False:
print("Please enter a digit!")
continue # skip rest of loop
within_range = int(choice) in range(0,10)
if within_range == False:
print("Please enter a number in range (0-10)")
return int(choice)
I just tried to write the code below that takes only a whole number between 1 to 10 and prints some statements of the input value does not fulfill the required conditions.
gamelist = list(range(0,11))
def display_game(gamelist):
print('Here is your list of options:')
print(gamelist)
def user_choice():
choice = 'x'
acceptable_range = range(0,11)
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input('Please enter a digit from the above options:')
if not choice.isdigit():
print("Oops! That's not a digit. Please try again.")
if choice.isdigit():
if int(choice) in acceptable_range:
within_range == True
else:
within_range == False
print('The entered number is out of acceptable range!')
return int(choice)
display_game(gamelist)
user_choice()
And after running this code, even after entering the correct value it keeps on asking for the input.I am not understanding what's gone wrong exactly and where.
Arguments are generally passed to give the function access to the data is has no access to but is required to work upon the task it is assigned to do.
A good example would be if you call a function from inside other function and want to use data of local variable of your former function into latter, you would have to pass it as argument/arguments .
This is a very vague example just to give you some basic hint , basically there are many factors you would consider before deciding whether or not you need arguments in your function!!
== is for comparison, = is for assigment:
gamelist = list(range(0, 11))
def display_game(gamelist):
print("Here is your list of options:")
print(gamelist)
def user_choice():
choice = "x"
acceptable_range = range(0, 11)
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a digit from the above options:")
if not choice.isdigit():
print("Oops! That's not a digit. Please try again.")
if choice.isdigit():
if int(choice) in acceptable_range:
# within_range == True # this doesn't assign, but compares
within_range = True # this assigns
else:
# within_range == False # And the same here
within_range = False
print("The entered number is out of acceptable range!")
return int(choice)
display_game(gamelist)
user_choice()
This prevents the endless loop. Comparing to booleans is not really necessary. Keeping the same idea this version is a bit more readable:
def user_choice():
choice = "x"
acceptable_range = range(0, 11)
while not choice.isdigit() or not within_range:
choice = input("Please enter a digit from the above options:")
if not choice.isdigit():
print("Oops! That's not a digit. Please try again.")
else:
within_range = int(choice) in acceptable_range
if not within_range:
print("The entered number is out of acceptable range!")
return int(choice)
Or even a version where choice is never a string. But maybe you haven't gotten to Exceptions yet :-). (this will change the message for '-1', though.)
def user_choice():
choice = None
acceptable_range = range(0, 11)
while choice not in acceptable_range:
try:
choice = int(input("Please enter a digit from the above options:"))
except ValueError:
print("Oops! That's not a digit. Please try again.")
if choice not in acceptable_range:
print("The entered number is out of acceptable range!")
return choice