Code works in Python shell but not with command prompt - python

I'm new to python and this is my first real program.
Heres the code:
def home():
print ('game....play-1..options-2..rules-3..exit-4..')
answer = input()
print(repr(answer))
if answer == '1':
play()
elif answer == '2':
options()
elif answer == '3':
rules()
elif answer == '4':
end()
def rules():
print ('rules...main menu-1...exit-2..')
answerRules = input ()
print(repr(answerRules))
if answerRules == '1':
home()
elif answerRules == '2':
end()
home()
The main problem i get here is that it works fine in the python shell but not with command prompt. In command prompt home() works however once you enter an answer, e.g. 3. the program just ends.

answer is type of int
so check with if answer == 1:
It will resolve

You should check to see if input() is returning the carriage return or some other character when you run it from the command prompt.

Related

Using Python for default parameters

I am currently learning python and stuck on a coding exercise. I am trying to achieve the result as shown on the image1. I am stuck on the overall code. I also not sure how to incorporate the "quit", so that the program terminates.
Image1
def tester(result):
while tester:
if len(result)< 10:
return print(givenstring)
else:
return print(result)
def main():
givenstring = "too short"
result=input("Write something (quit ends): ")
if __name__ == "__main__":
main()
For your problem, you need to have a variable that is your Boolean (true/false) value and have your while loop reference that. currently your while loop is referencing your function. inside your main function when you get your user input you can have a check that if the input is "quit" or "end" and set you variable that is controlling your loop to false to get out of it.
you also are not calling your tester function from your main function.
You missed into main() function to call your function, like tester(result). But such basics should not be asked here.
def tester(result):
if len(result)< 10 and result != 'quit':
givenstring = "too short"
return print(givenstring)
else:
return print(result)
def main():
result=None
while True:
if result == 'quit':
print("Program ended")
break
else:
result=input("Write something (quit ends): ")
if result.lower() == 'quit':
result = result.lower()
tester(result.lower())
if __name__ == "__main__":
main()

How would i get this newcommands.index work?

What I'm trying to do is get the position of the users input so if they recall a command it will return the value but it doesn't work for some reason idk why I've tried everything I know please help.
#new file
#new untitled file
args = []
newcommands = []
import time,random,os,sys
commands = ["help","version","python"]
while True:
command = input(">")
if command not in commands:
print("That command does not exist")
if command == "help":
print(commands)
if command == "version":
print("Version = 0.0.1")
if command == "python":
print("Type exit to exit the python interperter")
os.system("python")
if command == "DM ME A COMMAND":
pass
if command == "New":
if len(newcommands) != 5:
name = input("Enter a name: ")
text= input("Enter text for the function: ")
q = newcommands.append(name)
args.append(text)
if q == newcommands.index(0):
print(args.index(0))
if q == newcommands.index(1):
print(args.index(1))
if q == newcommands.index(2):
print(args.index(2))
if q == newcommands.index(3):
print(args.index(3))
if q == newcommands.index(4):
print(args.index(4))
if q == newcommands.index(5):
print(args.index(5))
i dont know what are you trying to do but seems your logic is more than i could understand
because you try to enter New command which is not on the list it means it will never execute the if condition for the "New"
and if that's not all you also try to get command line args which will never given by the user.
so basically please give the description of you question

Python - Input Menu Function

I'm quite new to Python and I am trying to make a little adventure game, just to develop my skills. So, for my game, I want there to be a few options, and the player will pick one and it will return a different result. However, the options will not always be the same, so I decided to make a function, so the options and results could differ. Here is the code for my function:
def action(act1, act2, act3, act4):
loop = True
while loop:
print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
act1
return
elif player_action == '2':
act2
return
elif player_action == '3':
act3
return
elif player_action == '4':
act4
return
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
The parameters are functions for what I want to print out.
My problem is, when I call this function and run the code, Python executes each function in every if and elif statement. For example, when I call this:
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
action(home_act1(), home_act2(), home_act3(), home_act4())
I run the program and it does this:
Welcome to the wilderness!
Welcome to the town!
Welcome to the store!
You left the adventure.
Process finished with exit code 0
It seems to just be running all four of my parameters, it worked before I made it a function but something isn't working right.
Thanks to any help!
In this line:
action(home_act1(), home_act2(), home_act3(), home_act4())
you are actually calling each function and passing the result (None in each case, since that is the default.
Try passing just the functions (home_act instead of home_act()), then in the loop body actually call act().
The reason you have all 4 outputs and then the code exiting is because you call all four home_act functions immediately by doing action(home_act1(), home_act2(), home_act3(), home_act4()), which executes one after another and exits the program due to the exit() in home_act4().
Another thing that is problematic is that you return after each action within the while-loop, which means the code would have stopped once the user has done one single action.
Fixing these problems results in the following code:
def action():
loop = True
while loop:
#print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
home_act1() # call the respective action function here
elif player_action == '2':
home_act2()
elif player_action == '3':
home_act3()
elif player_action == '4':
home_act4()
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
action()
Good luck with further coding :)
def home_act1():
print("Welcome to the wilderness!")
def home_act2():
print("Welcome to the town!")
def home_act3():
print("Welcome to the store!")
def home_act4():
print("You left the adventure.")
exit()
def action():
loop = True
while loop:
# print(menu)
player_action = input("Where would you like to go? ")
if player_action == '1':
return home_act1() #or you can remove the return and carry on in the function
elif player_action == '2':
return home_act2()
elif player_action == '3':
return home_act3()
elif player_action == '4':
return home_act4()
else:
print("Please type \'1\', \'2\', \'3\', or \'4\'")
action()
You can return a function call:
def functionToCall():
print('Ok function called')
def function():
return functionToCall()
function()

Create a text menu in Python3x that is always available

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

How to continuously prompt for user input?

I'm writing a function that prompts for input and then returns different results based on the input and then asks for input again. I've got it returning the correct values, but I'm not sure how to make it prompt for input again.
Here's the actual code of the function:
def interact():
command = raw_input('Command:')
command = command.split(' ')
if command[0] == 'i':
bike_name = command[1] + ' ' + command[2]
return get_product_id(products, bike_name)
if command [0] == 'n':
return get_product_name(products, command[1])
if command[0] == 'c':
return compute_cost(products, part, command[1])
if command[0] == 'p':
return get_parts(products, command[1])
In each line with return in it, it is simply calling up a previously defined function. The products and part are dictionaries, defined previously.
I can only use the builtin functions.
I would do it with a while loop. Like This:
while True:
com = raw_input('Command:').split()
if len(com) == 0:
break
elif com[0] == 'i':
bike_name = command[1] + ' ' + command[2]
return get_product_id(products, bike_name)
You've done most of the work, you just need this:
while True:
print interact()
There is no need to take so much pain and write your own command line interpreter.
Look at this: http://docs.python.org/2/library/cmd.html
One way is to put it in a while loop, and then also check for an exit input to break out.
Call the method inside an (end-less) loop:
while True:
some_method()

Categories

Resources