I am working on a simple function to let the user select the language.
But for some reason, I can't see my mistake and the while loop never breaks.
def chooseLanguage():
"""Simple function to let the user choose what language he wants to play in"""
if game["language"] == "en_EN":
import res.languages.en_EN as lang
elif game["language"] == "de_DE":
import res.languages.de_DE as lang
else:
while game["language"] is None:
print ("Hello and welcome! Please select a language.")
print ("1. German / Deutsch")
print ("2. English")
langC = input ("Your choice: ")
if inputValidator(1, langC) == 1:
game["language"] = "de_DE"
break
elif inputValidator(1, langC) == 2:
game["language"] = "en_EN"
break
if game["language"] is None:
chooseLanguage()
else:
pass
Evidently the infinite loop was caused by inputValidator returning a value that was neither equal to 1 or 2. Thus the exit conditions of the loop were never met. And so it continues.
Related
I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.
when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.
elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.
def print_menu(self,car):
print ("1.Search by platenumber")
print ("2.Search by price ")
print ("3.Delete 3")
print ("4.Exit 4")
loop=True
while loop:
print_menu()
ans==input("Please choose from the list")
if ans==1:
print("These are the cars within this platenumber")
return platenumber_
while ans:
if ans==2:
elif ans==2:
print("These are the prices of the cars")
return price_
elif ans==3:
print("Delete the cars ")
return delete_
elif ans==4:
return Exit_
loop=False
else:
raw_input("please choose a correct option")
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.
loop=True
while loop:
print_menu()
ans = int(input("Please choose from the list"))
if ans==1:
print("These are the cars within this platenumber")
# return some valid information about plate numbers
elif ans==2:
print("These are the prices of the cars")
# return some valid information about pricing
elif ans==3:
print("Delete the cars ")
# Perform car deletion action and return
elif ans==4:
# I am assuming this is the exit option? in which case
# return without doing anything
else:
# In this case they have not chosen a valid option. Send
# A message to the user, and do nothing. The while loop will run again.
print("please choose a correct option")
Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.
Hi Guys for the below code i want to execute only if the first condition satisfy so please help me
print('welcome')
username = input()
if(username == "kevin"):
print("Welcome"+username)
else:
print("bye")
password = input()
if(password == "asdfg"):
print("Acess Granted")
else:
print("You Are not Kevin")
If I got this right, you want to exit/terminate the script at the "else" block of the 1st if statement.
There are two approaches - 1st is that you use sys.exit():
import sys
#if statement here
...
else:
print("bye")
sys.exit()
2nd is that you put your 2nd if under the 1st if's else block:
...
else:
password = input()
if password=="abcdef":
#do something here
else:
print("you're not Kevin")
Also, I see that you're using brackets after the if statements (if (condition):). That is not necessary for Python 3.x as far as I'm concerned.
See: https://repl.it/CEl7/0
I am new to python and learning quickly. Thank you all for the help.
I am attempting to create a text menu that will always run in the background of a storytelling text rpg. I have searched and cannot find an explanation of how to create an "always on" menu or how one would work.
I would like the player to be able to hit "m" at any time in the game and have the menu prompt show up.
So far, I have created a "userinput" function as well as a "menu" function that will be deployed each time the game prompts the user/player for input.
def menu():
print('Press "1" for map >>> "2" for stats >>> "3" for exit')
choice = input()
if choice == '1':
print('map needs to be made and shown')
elif choice == '2':
print('stats need to be made and assinged to choice 2 in def menu')
elif choice == '3':
print('You are exiting the menu. Press "M" at any time to return to the menu')
return
else:
print('I did not recognize your command')
menu()
def userinput():
print('Press 1 to attack an enemy >>> 2 to search a room >>> 3 to exit game')
print('Press "M" for menu at any time')
inputvalue = input()
if inputvalue == 'm':
menu()
elif inputvalue == '1':
print('attack function here')
elif inputvalue == '2':
print('search function here')
elif inputvalue == '3':
exit
else:
userinput()
This does not appear to be an ideal solution because the user cannot choose to view a map or exit the game at any time they want.
Is there a way to have a menu always running in the background?
I thought of using a while loop that would never close and all of the game would be held within that while loop but that doesn't seem economical by any means.
Any thoughts or help would be appreciated.
I took a stab at it. This is perhaps not the best structure for doing what you're looking for but I don't want my reply to get too complicated.
The "standard" approach for anything with a UI is to separate the model, the view and the control. Check out MVC architecture online. While it adds complexity at the start it makes life much simpler in the long run for anything with a non trivial UI.
Other points of note are:
you're not stripping whitespace from your input (potentially problematic "3 " won't do what you want)
you're input is case sensitive (you ask for "M" but check for "m") .. maybe use choice = choice.strip.lower()??
there's a difference between the way raw_input and input work between Python 2 and Python 3 which means your code doesn't work in python 2. What's the difference between raw_input() and input() in python3.x? I've changed my example to use raw_input. You may want to use this work around http://code.activestate.com/recipes/577836-raw_input-for-all-versions-of-python/ near the top of your code for portability.
Some code
# flag we set when we're done
finished = False
def finish():
# ask the user for confirmation?
global finished
finished = True
return
def handle_menu_input(choice):
handled = True
if choice == '1':
print('map needs to be made and shown')
elif choice == '2':
print('stats need to be made and assinged to choice 2 in def menu')
else:
handled = False
return handled
def menu():
finished_menu = False
while not finished_menu:
print('Press "1" for map >>> "2" for stats >>> "3" for exit')
choice = raw_input() # NOTE: changes behaviour in Python 3!
if handle_menu_input(choice):
# done
pass
elif choice == '3':
print('You are exiting the menu. Press "M" at any time to return to the menu')
finished_menu = True
else:
print('I did not recognize your command')
menu()
return
def userinput():
print('Press 1 to attack an enemy >>> 2 to search a room >>> 3 to exit game')
print('Press "M" for menu at any time')
choice = raw_input() # NOTE: changes behaviour in Python 3!
if choice == 'm':
menu()
elif choice == '1':
print('attack function here')
elif choice == '2':
print('search function here')
elif choice == '3':
finish()
# elif handle_menu_input(choice):
# # delegate menu functions?? ..
# # do this if you want to see maps anytime without going through the menu?
# # otherwise comment this elif block out.
# # (Problem is 1, 2 etc are overloaded)
# pass
else:
print('I did not recognize your command')
return
def main():
# main loop
while not finished:
userinput()
return
if __name__ == "__main__":
main()
I am trying to create menu where user can choose which part of the program he/she wants to run. When I am importing function computer automatically runs it rather to wait for user input. What shall I do to run function only when called? My code:
import hangman
menu = raw_input("""Welcome to Menu, please choose from the following options:
1. Hangman game
2.
3.
4. Exit
""")
if menu == 1:
hangman()
elif menu == 2:
"Something"
elif menu == 3:
"Something"
elif menu == 4:
print "Goodbye"
else:
print "Sorry, invalid input"
The code for hangman.py looks like that:
import random
words = ["monitor", "mouse", "cpu", "keyboard", "printer",]
attempts = [] # Stores user input
randomWord = random.choice(words) # Computer randomly chooses the word
noChar = len(randomWord) # Reads number of characters in the word
print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."
def game():
guess = raw_input ("Please choose letter")
attempts.append(guess) # Adds user input to the list
print (attempts)
if guess in randomWord:
print "You have guessed the letter"
else:
print "Please try again"
while True:
game()
chance = raw_input ("Have a guess")
if chance == randomWord:
print "Congratulations, you have won!"
break
Without seeing hangman.py, I would assume that it directly contains the code for running the hangman game, not wrapped in a function. If that's the case, you created a module, no function (yet).
Wrap that code in
def run_hangman():
# Your existing code, indented by 4 spaces
# ...
import it like this:
from hangman import run_hangman
and finally call the function like this:
run_hangman()
So here is the start menu:
import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
hangman.main()
elif option == '2':
hangman.run_hangman('SKIP')
elif option == '3':
handman.run_hangman('Default User')
Inside your hangman code you want to have it modulated. You should have somthing like this:
def main():
stuff = raw_input('Starting new game. Please enter stuff to do things')
run_hangman(stuff)
def run_hangman(options):
if options == 'SKIP':
important_values = 5
vales_set_by_user = 'Player 1'
else:
values_set_by_user = options
rest_of_code()
So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)