I was working with a mastermind assignment but one of my define function isn't working as expected.
How do I make the "quit" jump back to "have a guess..." instead of continue to the colourlst?
def valid_usercolour():
while True:
#print('Welcome to the Mastermind')
usercolour = input('Please have your guess [r,o,y,g]: ').lower()
if 'quit' in usercolour:
while True:
dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
if dc_quit.lower() == "y":
print()
print('Alright, thank You for playing, Goodbye', user_name, '!' )
quit()
break
elif dc_quit.lower() == "n":
print("Alright, let's continue to our game")
break
else:
print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
continue
colourslist = ['r','o','y','g']
if any(character not in colourslist for character in usercolour):
print("Error! Only Characters ,", colourslist, "are allowed")
continue
if len(usercolour) != 4:
print("Error! Only 4 characters are allowed!")
continue
break
return usercolour
Just add else: and indent what's below it right before colourslist. Python codes do not "jump back":
def valid_usercolour():
while True:
#print('Welcome to the Mastermind')
usercolour = input('Please have your guess [r,o,y,g]: ').lower()
if 'quit' in usercolour:
while True:
dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
if dc_quit[0].lower()[0] == "y":
print()
print('Alright, thank You for playing, Goodbye', user_name, '!' )
quit()
break
elif dc_quit[0].lower()[0] == "n":
print("Alright, let's continue to our game")
break
else:
print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
continue
else:
colourslist = ['r','o','y','g']
if any(character not in colourslist for character in usercolour):
print("Error! Only Characters ,", colourslist, "are allowed")
continue
if len(usercolour) != 4:
print("Error! Only 4 characters are allowed!")
continue
break
return usercolour
BONUS: I added [0] at the values of dc_quit to force taking one character only. A full 'yes' or 'no' works too ;-)
Related
I complete all the steps that I am given by my code and finally it asks 'again (Y or N)'. (I have written an except argument that will prevent someone from ending the code by typing a wrong answer) When they input the wrong answer it starts the user back to the top of the code. I would like it to output what step the user was already on.
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
again = str(input("Again? (Y or N) "))
again = again.upper()
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
EDIT:
So I have made some progress but I have one last problem
CODE:
while True:
try:
choice = int(input("ONLY CHOOSE 1 AS THERE IS NO OTHER CHOICE: "))
assert choice == 1
if choice == (1):
userInp = input("TYPE: ")
words = userInp.split()
start_count = 0
for word in words:
word = word.lower()
if word.startswith("u"):
start_count += 1
print(f"You wrote {len(words)} words.")
print(f"You wrote {start_count} words that start with u.")
while True:
again = input("again? (Y or N)")
if again not in "yYnN":
continue
break
if again == "Y":
continue
elif again == "N":
break
except AssertionError:
print("Please type a given option.")
except ValueError:
print("Please type a given option.")
The problem is that the variable 'again' is not defined when outside of the while loop (outside the while loop that is in the while loop). How do I fix this?
You could create another loop (inside this main loop) where you are asking for input, and have a try block there, so that it loops just the section where the user is giving input until they give correct input.
My program takes an input from the user about what they want to add. This works fine, but the problem arises when it comes down to the nested while loop that promps the user if they wish to add more items (y/n). I want y to start the loop from the beginning, n to exit the loop and continue the program, and any other input to give an error whilst restarting the y/n prompt.
I can't seem to figure out how to get out of the nested while loop nor can I figure out how to throw an error if the input is neither y or n. How would I go about fixing this?
elif user_input == "a":
while True:
try:
add_item = input("What item would you like to add? ").lower()
if not re.match("^[a-z, A-Z]*$", add_item):
print("ERROR: Only letters A-Z are allowed!")
continue
elif len(add_item) < 1 or len(add_item) > 20:
print("Item name is too long, only a maximum of 20 characters are allowed!")
continue
else:
item_amount = int(input("How many of these would you like to add? "))
shopping_list[add_item] = item_amount
print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
while True:
try:
add_more = input("Would you like to add more items? (y/n): ").lower()
if add_more == "y":
break
elif add_more == "n":
break
except TypeError:
print("ERROR: Expected y or n in return! Try again!.\n")
break
except ValueError:
print("\nERROR: Amount must be an integer! Try adding an item again!\n")
use boolean variable(keep_adding for below code) to decide while loop's terminal condition. It will be set to False iff add_more == "n"
use raise TypeError to raise error if user input is neither "y" nor "n".
You should remove break from except TypeError in order to keep asking "Would you like to add more items? (y/n): " if input is invalid.
elif user_input == "a":
keep_adding = True
while keep_adding:
try:
add_item = input("What item would you like to add? ").lower()
if not re.match("^[a-z, A-Z]*$", add_item):
print("ERROR: Only letters A-Z are allowed!")
continue
elif len(add_item) < 1 or len(add_item) > 20:
print("Item name is too long, only a maximum of 20 characters are allowed!")
continue
else:
item_amount = int(input("How many of these would you like to add? "))
shopping_list[add_item] = item_amount
print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
while True:
try:
add_more = input("Would you like to add more items? (y/n): ").lower()
if add_more == "y":
break
elif add_more == "n":
keep_adding = False
break
else:
raise TypeError
except TypeError:
print("ERROR: Expected y or n in return! Try again!.\n")
except ValueError:
print("\nERROR: Amount must be an integer! Try adding an item again!\n")
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".
In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.
import random
import sys
loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
print('Thank you!! Visit again.')
sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')
lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)
while loop == 'yes':
user_input1 = int(input('Please enter the first number: '))
user_input2 = int(input('Please enter the second number: '))
user_input3 = int(input('Please enter the third number: '))
print('Your numbers are: ', user_input1, user_input2, user_input3)
def check():
if lotto_numbers != [user_input1, user_input2, user_input3]:
return False
else:
return True
def fbcheck():
if lotto_numbers == [user_input1, user_input2, fireball_number]:
return True
elif lotto_numbers == [fireball_number, user_input2, user_input3]:
return True
elif lotto_numbers == [user_input1, fireball_number, user_input3]:
return True
else:
return False
retry += 1
result = check()
if (result == True):
print("Congratulations!! You won!!")
else:
print("Oops!! You lost.")
if (fireball == 'yes'):
fb_result = fbcheck()
if (fb_result == True):
print("Congratulations, you won a fireball!!")
else:
print("Sorry, you lost the fireball.")
print('No of retries remaining: ', (3 - retry))
if (retry == 3):
sys.exit()
loop = input('Do you want to try again? yes/no: ')
continue
else:
pass
print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
You don't need anything at all. Code inside the if block will execute and the script will run code after the if block.
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.
I.e.:
if some_condition:
# Do stuff
# Stop indent and do some more stuff
I think I gotcha your willing.
You want to execute something after the if condition is executed? So, create a subtask, and call it!
def finish_program():
print("something")
a = "foo"
print("finish program")
loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
print('Thank you!! visit again.')
finish_program()
I'm, trying to avoid this while loop what is wrong
while True:
start = input("Ok, are you ready now?\n")
if (start != "yes" and start != "no"):
print ("Please enter Yes or No")
else:
break
elif start =="no":
continue
Your indentation is totally wrong. Your code is not valid.
By the way, there's the correct indented code:
while True:
start = input("Ok, are you ready now?")
if start == "yes":
break
elif start == "no":
continue
else:
print ("Please enter yes or no.\n")
Note that it works in Python3
I can't edit the question to fix your indentation
but i would guess that you mean why it is not working.
you cannot have elif after else for the same if
the correct flow is
if
elif
else
so it should be
while True:
start = input("Ok, are you ready now?\n")
if (start != "yes" and start != "no"):
print ("Please enter Yes or No")
elif start =="no":
continue
else:
break
Here is a dumbed down version of my program that I am using as an example.
I know that using GOTO is bad practice, because it leads to sloppy and confusing code, however it would be perfect for solving this problem that I have (problem detailed at bottom of post).
def prompt():
while True:
user_input = raw_input:
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': ##Restart
???????????
else:
return user_input
load_word_list() ##Load words into list
for word in wordList: ##Loop that needs to restart
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer != word:
print "You got it wrong"
#Print results
At the Prompt, I want to reload the wordList list and restart the outer for loop.
With GOTO I could just put in place of ????... GOTO load_word_list().
But since this is Python (and Python is about good code), What is the Pythonic way to solve this problem?
You could return a tuple from prompt():
elif user_input == 'r': #Restart
return True, None
else:
return False, user_input
and
restart, answer = prompt()
if restart:
break
if answer != word:
print "You got it wrong"
Another take on jsbuenos solution. This actually does re-run the outer for loop.
def prompt():
while True:
user_input = raw_input()
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': #Restart
raise RestartException
else:
return user_input
class RestartException(Exception):
pass
while True:
load_word_list() ##Load words into list
try:
for word in wordList: ##Loop that needs to restart
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer != word:
print "You got it wrong"
except RestartException:
# catch the exception and return to while loop
pass
else:
# exit while loop
break
class RestartException(Exception):
pass
def prompt():
while True:
user_input = raw_input:
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': #Restart
raise RestartException
else:
return user_input
load_word_list() ##Load words into list
for word in wordList: ##Loop that needs to restart
try:
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer != word:
print "You got it wrong"
except RestartException:
pass
I don't undertand very much what you want to do, but you can remove the special case in prompt and handle the 'r' special case in the for loop directly
def prompt():
while True:
user_input = raw_input("enter words")
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': #Restart
return False
else:
return user_input
answer = True
while answer == True:
load_word_list() ##Load words into list
for word in wordList: ##Loop that needs to restart
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer == False:
answer = True # reset for the while loop
break # break to while loop
elif answer != word:
print "You got it wrong"
print results