Hoping someone can help me with this.
I think I need to use the try and except function in order to do what I need but im not creating an error for an exception to occur.
When a user enters a1 it looks at the a1 dictionary and finds an x so it does not satisfy the while loop as true. so it moves to else. I need to reask the question again and start over from the top of the while loop. Is it possible to trigger an exception just because something is false?
here is what I am working with
board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}
def o_move():
print 'im over at o now'
def x_move():
ans = raw_input('Player x please Enter a location: ') #ask user for location
f = board[ans] #current value of dictionary location selected
while f is '_' or f is ' ':
board[ans] == 'x' #writes the user location selected to the dictionary
o_move() #everything was good, move on
break #break the loop
else:
print 'space not available Try again'
ans = raw_input('Player x please Enter a location: ') #ask again
x_move()
A simpler way to do this is to have the function x_move() call itself if a valid move's not chosen the first time. That way, you don't have to write two raw_input() statements.
Here's one way your code might be simplified:
board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}
def o_move():
print 'im over at o now'
def x_move():
ans = raw_input('Player x please Enter a location: ')
open_positions = ['_', ' ']
if board[ans] in open_positions:
board[ans] = 'x'
o_move()
else:
print 'space not available Try again'
x_move()
x_move()
Instead of having
ans = raw_input('...')
Again, you should just put:
else:
Print 'space not available, try again'
x_move()
And that should send it to the start of the while loop again
Related
My list:
listOfMovies=[the Slow and Confused 9, Somebody, Gorilla vs. King, The Blundering 3: Boss Made Me Do It]
I am trying to take an input and if there is a match to the list, the function will print out the object.
If there is no match, the function will print out and ask if I would like to search again or return to the mainmenu.
No results found
1. Search again
2. Return to Main Menu
Currently I am able to print the matches however, I also print out the no results as well.
If there are no matches with the input, I want No results to be printed.
I would like to print out the matches and skip printing the no results found.
My code is:
def DisplayMovie( movie, i ):
print ( "Movie Name: " + str(movie[i].getName()) + ",", "Category:" , movie[i].getCategory())
return
def SearchBasedOnName(searchString, listOfMovies):
for i in range ( len(listOfMovies) ):
if (searchString.lower() in listOfMovies[i].getName().lower()):
DisplayMovie( listOfMovies, i)
print("\nNo results found")
print("1. Search again")
print("2. Return to Main Menu")
option3input = input("")
if option3input == "1":
searchString = input("\nPlease enter your search input: \n")
elif option3input == "2":
printMenu()
searchString = input("\nPlease enter your search input:")
SearchBasedOnName(searchString, listOfMovies)
The output I get:
Please enter your search input: king
Movie Name: Gorilla vs. King
No results found
1. Search again
2. Return to Main Menu
The 'in' keyword will be your saviour. Given a list of strings and some comparison criterion then, for example:-
mylist = ['abc', 'def']
if 'xyz' in mylist:
print('Found')
else:
print('Not found')
You should be able to adapt this to your use-case
Put return under the DisplayMovie in the if scope so that you get out of the function right after it did something expected.
def SearchBasedOnName(searchString, listOfMovies):
for i in range ( len(listOfMovies) ):
if (searchString.lower() in listOfMovies[i].getName().lower()):
DisplayMovie( listOfMovies, i)
return
So I'm designing a sign-in AI, and I want it to work so that the admin name is Shawn. Here is my issue:
The program starts with the interface -
def interface():
username = input('Hello traveler, what is your name? ')
lowerUsername = username.lower()
print()
print()
if lowerUsername == 'megan':
print()
print('So you are the one Shawn has told me so much about? You are looking beautiful today my dear βΊοΈπ·')
elif lowerUsername == 'shawn':
OfficialSignInEdit()
So you can see at the end that if the user inputs that their name is 'shawn' at sign-in, it calls on the OfficialSignInEdit function, which is the admin sign in. It looks like this:
def OfficialSignInEdit():
print()
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again π')
else:
print()
res1 = input('Incorrect password, try again? (Yes/No)')
lowres1 = res1.lower()
if lowres1 == 'yes':
print()
print()
OfficialSignIn()
elif lowres1 == 'no':
print()
print()
interface()
So I have pinpointed the source of my issue to be right here in this particular line:
if PossInputs('perio', 'What street did you grow up on?: ') == correct:
print()
print('Greetings Master Shawn, it is a pleasure to see you again π')
this (just for your reference) is the PossInputs function:
def PossInputs(x, y):
term = x
question = input(y)
lowQuestion = question.lower()
words = lowQuestion.split()
if term in words:
print()
print (correct)
else:
print()
print (incorrect)
So what I want to happen is, when 'shawn' is entered as a name, the program will jump to the OfficialSignInEdit Function, and ask the question 'What street did you grow up on?'. Then IF the user enters the answer 'perio', the program will print 'correct', and then print the message 'Greetings Master Shawn, it is a pleasure to see you again'. I tried to say that IF PossInputs == correct (and I did define correct = 'correct', and incorrect = 'incorrect' outside all functions) then this would happen, but instead it prints 'correct', and then 'Incorrect password, try again? (Yes/No)', so how can I make a conditional statement that says that if the user answers 'perio', then it will print the welcome message?
Just for thoroughness sake, I also tried
if PossInputs('perio', 'What street did you grow up on?: ') == True
also without success...
anyways anything you can give me is extremely appreciated, if you have any questions or you would like to to clarify something about the written code, I would be more than happy to get back with you as soon as I can.
Thanks!
I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.
hey im making a simple little grocery list on Python. I know it's not the most eloquent... but I am just learning the syntax right now. I want to get into learning Django.
list = []
def makeList():
listing = True
while listing:
addTo = raw_input("Add to list: ")
if addTo == 'q':
listing = False
else:
list.append(addTo)
def checkList():
if check in list:
print "Yay there is " + check + " here"
else:
print "No you have not added that..."
addAnother = raw_input("Would you like to add it? ")
if str.lower(addAnother) == "yes":
list.append(check)
elif str.lower(addAnother) == "no":
print "Okay then here is your list."
print list
else:
print check
makeList()
check = raw_input("What item: ")
checkList()
I know its pretty complex and hard to understand O_o... but you can see that the nested if statement is not registering when you run it.
What is making it do this? I think that's the best way to ask this.
I've rewritten it a bit to make it cleaner and more Pythonic;
def get_list(prompt, halt):
lst = []
while True:
item = raw_input(prompt)
if item == halt:
return lst
else:
lst.append(item)
def check_list(lst, item):
if item in lst:
print('Yay there is {} here'.format(item))
return True
else:
print('No you have not added {}'.format(item))
return False
def get_yesno(prompt):
while True:
yesno = raw_input(prompt).lower()
if yesno in {'y', 'yes'}:
return True
elif yesno in {'n', 'no'}:
return False
def main():
mylist = get_list('Add to list:', 'q')
check = raw_input('Look for item:')
if not check_list(mylist, check):
if get_yesno('Would you like to add it?'):
mylist.append(check)
print(mylist)
if __name__=="__main__":
main()
Some style tips:
Don't use list as a variable name; it's a built-in function, and you don't want to overwrite it.
Global variables are almost always a bad idea; passing data around explicitly makes it much easier to figure out where bad data is coming from, and makes functions more reusable.
camelCase is generally denigrated; use_underscores for function names instead.
You probably intended to keep going rather than break when you append the new item (or at least print something to indicate success), but the nested if statement works just fine, appends the thing to the list as specified and then the function and program terminate.
result = raw_input("Enter results file: ")
while True:
try:
result = get_marks_from_file(result)
break
except IOError:
print 'Please supply correct file. '
Above is the raw_input function that I am using to bring a file. When I put correct file name, it works well. But when I put something else such as 'asdsada', the sentence 'please supply correct file. ' is printed and it doesn't stop. Is there any method for just one printing and return to the question?
Any advices or helps would be appreciated.
Move the raw_input inside your loop:
while True:
result = raw_input("Enter results file: ")
try:
result = get_marks_from_file(result)
break
except IOError:
print 'Please supply correct file. '