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.
Related
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 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)
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
I have a small script I have been working on for practice with Python. I am having trouble getting my input to accept a number for an if statement and also accept string as lower case.
I want to tell my script for any input if the user types '99' then close the program. So far it works where I have int(input()), but it won't work where I have input(). What am I doing wrong or is it not something I can do?
Right now my if statement looks like:
if choice1 == 99:
break
Should I just make 99 into a string by quoting it?
Maybe something like this:
if choice1 == "99":
break
Here is the script:
global flip
flip = True
global prun
prun = False
def note_finder(word):
prun = True
while prun == True:
print ('\n','\n','Type one of the following keywords: ','\n','\n', keywords,)
choice2 = input('--> ').lower()
if choice2 == 'exit':
print ('Exiting Function')
prun = False
start_over(input)
elif choice2 == 99: # this is where the scrip doesnt work
break # for some reason it skips this elif
elif choice2 in notes:
print (notes[choice2],'\n')
else:
print ('\n',"Not a Keyword",'\n')
def start_over(word):
flip = True
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
So input() always returns a string. You can see the docs here:
https://docs.python.org/3/library/functions.html#input
What you could do is something like this:
choice2 = input('--> ')
if choice2.isnumeric() and (int(choice2) == 99):
break
this avoids you to type check and catch errors that aren't important.
see below for how isnumeric works with different numeric types:
In [12]: a='1'
In [13]: a.isnumeric()
Out[13]: True
In [14]: a='1.0'
In [15]: a.isnumeric()
Out[15]: False
In [16]: a='a'
In [17]: a.isnumeric()
Out[17]: False