This is a part of a text adventure that I am working on. It works fine until the user inputs any button to start, and then it prints "None". I was wondering if there was a simple way that I either am overlooking or do not know yet to prevent it from outputting "None".
def main():
print "Welcome to my Text Adventure!"
raw_input("Press any button to start!")
print main()
Function does not return anything (returns None) without explicit return statement.
def main():
print "Welcome to my Text Adventure!"
return raw_input("Press any button to start!")
As you are printing the return value by main() function, so you are supposed to return something. But you are not doing so, which results in returning "nothing", which will print "None" on the console.
Try this
def main():
return raw_input("Welcome to my Text Adventure!\nPress any button to start: ")
print main()
Related
I am having a problem with curses library in Python. Consider the following code:
def main(stdscr):
print('Hello World!!')
create_screen()
curses.endwin()
if __name__ == "__main__":
curses.wrapper(main)
The problem is every text printed by "print" function is messed up even before calling "create_screen()" function which initiates the screen by "curses.initscr()"
You can use print and input normally before and after your program uses curses. Also, you do not have to put all your code into main, and you don't have to pass the main function to curses, either. main is just a function like any other. Check out this simple example:
import curses, time
def incurses(stdscr):
stdscr.addstr(0, 0, "Exiting in ")
stdscr.addstr(2, 0, "Hello World from Curses!")
for i in range(5, -1, -1):
stdscr.addstr(0, 11, str(i))
stdscr.refresh()
time.sleep(1)
curses.endwin()
def main():
print('Hello World!!')
choice = input("Start Curses Program? ")
if choice == "yes":
curses.wrapper(incurses)
print("After curses")
if __name__ == "__main__":
main()
This prints and asks for user input, then shows a curses screen, then goes back into "normal" printing mode.
I need to write a function in tkinter which will run until the user gives the correct password. In principle, it should be the same as:
check = input('type ok')
while True:
if check == 'ok'
break
else:
check = input('type ok')
print('You made it!')
...but with a few frustrating differences:
1. I'm not using the input() function, but rather getting text from a tkinter Text widget.
2. This check method is bound to a return press, which just generally makes things very inconvenient
The best I have, so far (in pseudo-code ish):
def authenticate():
root.bind('<Return>', check)
if auth == True:
return
else:
root.after(500, authenticate)
def check():
if pword == correct_pword:
auth = True
def signin():
auth = False
authenticate()
print('you're signed in!')
This way, authenticate only returns when the user presses enter and the password is correct. I thought that meant that the code in signin would only continue then, but this doesn't seem to be the case for whatever reason.
Is this the right approach? I don't understand why the code continues before the function has returned anything.
Like jasonharper said in his comment, you should not think the same way as for a command line program. Especially, you don't need a while loop since the mainloop of the GUI provides one already (the GUI waits for events like keyboard input, mouse click, ...).
So you just need to create the entry for the password and bind the Return key to a function that checks whether the password is right or not. Each time the user presses "Return", the function will be called and for instance destroy the login window if the password is right or clear the entry if it's wrong.
Corresponding code:
import tkinter as tk
def login(event):
pwd = entry.get()
if pwd == "ok":
print("You are logged in !")
root.destroy()
else:
entry.delete(0, "end")
root = tk.Tk()
entry = tk.Entry(root, show="*")
entry.pack()
entry.bind("<Key-Return>", login)
root.mainloop()
Exit without Saving
How should I program my exit function that if user exit without saving then it should pop a question
def main(self):
...
file.add_command(label="New",command=lambda: self.new())
file.add_command(label="Open",command=lambda: self.load())
file.add_command(label="Save",command=lambda: self.save())
file.add_command(label="Exit",command=self.exit)
menu.add_cascade(label="File",menu=file)
def exit(self):
result = askquestion("Exit", "Are You Sure Without Saving?", icon='warning')
if result == "yes":
exit()
else:
return False
Have a global variable called
hasBeenSaved = False
When you call the save() function, switch that global boolean hasBeenSaved to True.
If the user does anything else to change their file, set hasBeenSaved back to False .
Now, when you are going through your exit() function, if hasBeenSaved is False, prompt the user for:
"Are you sure you wanna exit without saving?"
Hope this helps!
Am currently having a bit of trouble with my code. I am making a very basic RPG, and have came across this problem:
(unbound method wrongCommand.wrong)
Am also running python 2.7.5, and windows 7.
Here's my code:
import os
class wrongCommand():
def wrong():
os.system("cls")
print "Sorry, the command that you entered is invalid."
print "Please try again."
def main():
print "Welcome to the game!"
print "What do you want to do?"
print "1.) Start game"
print "2.) More information/Credits"
print "3.) Exit the game"
mm = raw_input("> ")
if mm != "1" and mm != "2" and mm != "3":
print wrongCommand.wrong
main();
main()
So first, you'd want to change
print wrongCommand.wrong
To
print wrongCommand.wrong()
(Note: addition of open and close parens)
But then you'd get the lines printed from the wrong method as well as the return value of that method, which is currently None.
So then I'd probably change
print wrongCommand.wrong()
To simply
wrongCommand.wrong()
(Note: dropping of the print statement)
Alternatively, you could have wrong() return a string, rather than print one, and then this line
print wrongCommand.wrong()
Would be fine.
You will either have to call the wrong() method off of a class instance, e.g.
wc = wrongCommand() # Create a new instance
wc.wrong()
or simply
wrongCommand().wrong()
In either case you'll have to change your wrong() method definition to
def wrong(self):
#...
Or you'll get an error like "wrong() expects exactly 1 argument, got none".
Or you can define the wrong method as a class method or static method:
#staticmethod
def wrong():
# ...
or
#classmethod
def wrong(cls):
#...
I am trying to develop this program , that invokes the main function of another program and takes the program to be inkoved's name as user input , let us call this program 1 :
Program 1 # takes the program 2's name as user input
try:
print "Please input the file you want to test"
filename = raw_input().split(".")[0]
module = __import__(filename)
except:
program 2 is like
def main():
first()
def first():
5/0
if __name__ == "__main__":
main()
so basically I want to know how to invoke program 2's main function from program 1 .
thank you
Just do module.main() - there's nothing special about a function called main