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
Related
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.
I'm trying to understand what's wrong with the following code.
This version, using boolean values, works fine with or without the break:
print("Enter your names for the contest exactly the way you want it spelled.")
list_done = False
while list_done == False:
name = input("Enter your first name: ")
others_there = input("Are there other participants? Type Y or N: ").lower()
if others_there == "y":
list_done == False
print("Call the next participant!")
elif others_there == "n":
list_done = True
print("We're done. We'll contact you soon.")
break
However, when I try using integer values for list_done, the break is required to exit the loop, or else it runs indefinitely. Why is that?
print("Enter your names for the contest exactly the way you want it spelled.")
list_done = 0
while list_done == 0:
name = input("Enter your first name: ")
others_there = input("Are there other participants? Type Y or N: ").lower()
if others_there == "y":
list_done == 0
print("Call the next participant!")
elif others_there == "n":
list_done == 1
print("We're done. We'll contact you soon.")
#break
You confused assignment and comparison. Instruction list_done = False assigns the False value to list_done. When you use list_done == False you just calculate if list_done is equal to False.
So the mistake is about lines with list_done == False, list_done == True, list_done == 0. If you fix == with =, everything will work as you desire.
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 have written a main script that has a menu with 5 different options, the fifth option is if the user wants to quit the program. If the user types 5 in the main menu the program is supposed to quit, but it doesn't... It just keeps on looping through the menu. Can anyone help me resolve this issue??
menuItems = np.array(["Load new data", "Check for data errors", "Generate plots", "Display list of grades","Quit"])
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
break
You have nested loops, and break only breaks out of the inner loop.
To remedy this delete the nested loop and the break from the else block:
while True:
choice = displayMenu(menuItems)
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
In your code, when you call break, it breaks from the inner while loop and goes to the outer while loop which causes the whole thing to go on again. If for some cases you want both of the while loops to break then you can use some sort of a flag.
Example,
flag = False
while True:
while True:
if (1 == var):
flag = True
break
if flag:
break
//Your code
flag = False
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
flag = True
break
elif (choice == 2):
checkErrors(grades)
flag = True
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
flag = True
break
else:
print("Invalid input, please try again")
flag = True
break
if True == flag:
break
It is a simple maze game I did for school. I have tried different solutions but still cant figure out how. I don't necessarily need a full solution; any tips would help.
x = 1
y = 1
valid_selection = True
while True:
if x == 1 and y == 1:
if valid_selection == True:
print("You can travel: (N)orth.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 1 and y == 2:
if valid_selection == True:
print("You can travel: (N)orth or (E)ast or (S)outh.")
valid_selection = True
choice = input("Direction: ")
if choice.lower() == "n":
y += 1
elif choice.lower() == "e":
x += 1
elif choice.lower() == "s":
y -= 1
else:
print("Not a valid direction!")
valid_selection = False
elif x == 3 and y == 1:
print("Victory!")
break
You could have your function recieving x and y as parameters, removing the While True and replacing it with its creation, like def MyFunc(x,y), putting the valid_selection variable inside it and removing x and y attributions. And then you call it in the end of the code passing 1 and 1 as your desired parameters, like MyFunc(1,1)
There are many ways to create a function.
First, you need to abstract what your program do. The name of the function have to express this.
Second, you need to know what are the inputs. In your case the input must be x and y, or the proper names to these input.
The answer which your function will return is a important thing to know. The user will see a print or the user of the function will use a number, string or other object to feed other function.
I hope this not confusing.