python loops does not break even after successful while statement - python

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

Related

Boolean error, in the First code but not in Second, Why?

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.

Why this isn't working, it's giving me an this error ('bool' object is not subscriptable)

here is the code, it's a car parking system:
import time
parking_slots = []
start = []
for i in range(6):
start.append(0)
for i in range(6):
parking_slots.append(False)
while True:
print("1.view empty\n2.add\n3.remove\n4.save\n5.load\n6.exit")
choice = int(input())
if choice == 1:
print("Empty slots are: ")
for slot in range(6):
if parking_slots[slot] == 0:
print(slot, end=" - ")
print("")
if choice == 2:
index = int(input("Enter the index of the slot: "))
if start[index] == 0:
start[index] = int(time.time())
parking_slots[index] = True
else:
print("this slot is already token, please choose another one")
if choice == 3:
index = int(input("Enter the index of the slot: "))
print("Your bill is", int(time.time()) - start[index])
parking_slots[index] = False
start[index] = 0
if choice == 4:
open("cps.txt", "w").write("")
for i in start:
open("cps.txt", "a").write(str(i) + "\n")
if choice == 5:
file = open("cps.txt", "r").readlines()
start = [float(x.strip("\n")) for x in file]
for x in range(6):
if start[x] == 0:
parking_slots = False
else:
parking_slots = True
if choice == 6:
break
the error is when I enter choice 1, it tells me bool object is not subscriptable
When choice == 5 you do
for x in range(6):
if start[x] == 0:
parking_slots = False
else:
parking_slots = True
which replaces the list that was contained in parking_slots with a plain boolean, which gives you that error when you later try to index it. Probably here you meant
for x in range(6):
if start[x] == 0:
parking_slots[x] = False
else:
parking_slots[x] = True

Unable to understand why and is not working

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)

TypeError: unsupported operand type(s) for divmod(): 'NoneType' and 'Int'

I am doing past coursework for practice, but I'm not sure what to do.
The task: create a game where the user has to guess a random 4 digit number(no repeated digits).
The problem: my code kind of works - like when you input a number with no repeating digits, it's fine, but when you enter, for example, 1223 I get the error:
TypeError: unsupported operand type(s) for divmod(): 'NoneType' and 'Int'
I have looked online and cannot find an answer. Any help would be greatly appreciated.
Thank you
Code below
import random
from collections import Counter
def rng():
num = []
i = 0
while i <=3:
rng = random.randrange(1,9)
if num.count(rng) == 0:
num.append(rng)
i+=1
return num
def menu():
userGuesses = 1
num = rng()#sort out a new num every time
print(num)
x = True
while x == True:
userExit = input("Would you like to exit(yes or no)")
if userExit == "yes":
print("Exiting...")
exit()
elif userExit == "no":
x = False
over = game(num)
while over !=True:
over = game(num)
userGuesses+=1
print("Congratulations you got it right, and it only took you ", userGuesses, " guesses!")
menu()
else:
print("Invalid entry")
def userInput():
userNum = int(input("Please enter a four digit number(no repeated digits)"))
if(userNum > 1000 or userNum < 9999):
print("...")
c = Counter(str(userNum))
if any(value > 1 for value in c.values()):
print ("Your number has repeating digits, please change it.")
else:
x = False
return userNum
else:
print("Invalid entry")
def convertToArray(userNum):
userArray = []
while userNum != 0:
userNum, x = divmod(userNum, 10)
userArray.append(int(x))
userArray.reverse()
print(userArray)
return userArray
def check(userArray, num):
i = 0
bulls = 0
cows = 0
while i<=3:
if num[i] == userArray[i]:
bulls +=1
elif int(userArray[i] in num):
cows +=1
i+=1
print("Bulls:")
print(bulls)
print("Cows:")
print(cows)
if bulls == 4:
return True
else:
return False
def game(num):
userNum = userInput()
userArray = convertToArray(userNum)
if check(userArray, num) == True:
return True
else:
return False
#Main-----------------------------------------------------------------
print("""Hello and welcome to the game \"Cows and Bulls\":
*In this game you enter a 4 digit number
*We compare it to a random number
*If you get the right number in the right 'place' then you get one bull
*If you get the right number in the wrong 'place then you get one cow'
*The game is over when you get 4 bulls, or all the numbers in the right place""")
menu()
Yes - your function doesn't actually return anything because of the print statements, hence an implicit None is returned - but there's another solution you can use.
Take advantage of the fact that userInput will return None if the input isn't valid. Have a condition just before userArray = convertToArray(userNum) to check if userNum is None:
def game(num):
userNum = userInput()
if userNum is None:
# Bad input was given
return False
userArray = convertToArray(userNum)
if check(userArray, num) == True:
return True
else:
return False
def userInput():
userNum = int(input("Please enter a four digit number(no repeated digits)"))
if(userNum > 1000 or userNum < 9999):
print("...")
c = Counter(str(userNum))
if any(value > 1 for value in c.values()):
print ("Your number has repeating digits, please change it.")
else:
x = False
return userNum
else:
print("Invalid entry")
when userNum is repeated, you return nothing. you should return something and pass it to convertToArray

Can you use input to accept both an integer and a string?

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

Categories