Jump to content

So I'm no expert in Python but I'm teaching myself, I basically need a way for my input function to work only if the spacebar is pressed, would someone be able to walk me through this?

 

Here is the Code:

_exit = "Hit spacebar to exit the game!"if guessOne == computerNum:    print ("YOU WIN!")    input (_exit)   ''' I want this input function to execute when spacebar is pushed '''    exit()

Basically input functions default to enter in order to work, I want to change this so that the user has to hit the spacebar instead for my input(_exit) function, thanks!

Link to comment
https://linustechtips.com/topic/526365-python-help/
Share on other sites

Link to post
Share on other sites

Is it just a text input game type thing?  E.g., prompt the user for an input, check that against some value?  Because there's the "input" function for that.  input("string") will prompt the user for a text-based input, using the prompt "string".  It'll wait for the user to type something out and press "enter", and can store that input in a variable.  Note: it's stored as a string, so if you need it to be an integer/float type, you'll need to manually convert it using int() or float() or whatever.

 

To check when the user presses space, you'll probably want a few if/elif/else statements to check their input against the right answer, the exit string, and whatever else you need to.

 

Your code would look something like this:

_exit = " " # just a spaceuser_answer = input("Type your guess and press 'enter'. ")# Check user's input against the different possible casesif user_answer == computerNum:    print("YOU WIN!")elif user_answer == _exit:    exit()else:    print("YOU LOSE!")

Something else to note: if you want the game to continue until the user either quits or gets the right answer, you can put everything except the first line inside a while True loop.  This will prompt the user for input, then check it against the correct answer and whatever the input is to quit the game.  If it's either of those, it'll exit the while loop, and won't ask for any more input.  But if the user gets the answer wrong, it'll prompt them for their input again.

Link to comment
https://linustechtips.com/topic/526365-python-help/#findComment-6990087
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×