I'm trying to get input from a user using the Walrus operator :=, but if the user will only type in the Enter key as input, than the python script will terminate. How can I catch this error and make sure that the user hasn't only pressed the Enter key?
There is this answer but it does not work using the walrus operator.
This code without the walrus operator will successfully check that not only the Enter key was pressed:
while True:
answer = input("Please enter something: ")
if answer == "":
print("Invalid! Enter key was pressed.")
continue
else:
print("Enter wasn't pressed!")
# do something
If the user only presses Enter, than the whole script will terminate.
while answer := input("Please enter something: "):
# if user pressed only `Enter` script will terminate. following will never run
if answer == "":
print("enter was pressed")
else:
print("Enter wasn't pressed!")
# do something
What's happening in the code?
Part 1:
This happens because this statement answer := input("Please enter something: ") takes the input value and assigns to the variable answer. If you press Enter then the value for answer is empty string.
Part 2:
while loop evaluates the value. As the value is an empty string and empty string evaulates to false, the loop exits
We can't do this using walrus operator because the control never goes inside the loop and moreover you want to check the value of the entered string
You put the assignment expression in the wrong spot. Your original loop is infinite, but your second loop uses answer as the break condition.
while True:
if not (answer := input("Type something: ")):
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
As well, since we're using continue, the else clause is not needed.
In action:
Type something: hello!
You typed: hello!
Type something:
You didn't type anything before pressing Enter!
Type something: hi!
You typed: hi!
However, there's no real advantage to using the walrus operator here, so I would avoid it.
while True:
answer = input("Type something: ")
if not answer:
print("You didn't type anything before pressing Enter!")
continue
print("You typed:", answer)
You can write the following code:
while (answer := input("Please enter something: ")) != 0:
# if user pressed only `Enter` script will terminate. following will never run
if answer == "":
print("enter was pressed")
else:
print("Enter wasn't pressed!")
# do something
This means that != 0 will always be satisfied.
I have two files in my text-based game. The variable that is being assigned will be keep_note.
If you enter "Take" the boolean value True is assigned to the have_note-001
but in the next file when if have_note_001 == True I get an error saying
have_note-001 is undefined
If keep_note is == "Take":
have_note_001 = True
Then in the next file I want that True value to travel over to the next file.
If have_note_001 == True: print("This Value Is True")
keep_paper = input("Do you want to Leave the piece of paper or Take it? > ")
if keep_paper == "Take":
have_note_01 = True
if have_note_01 == True:
print("You have chosen to keep the piece of paper")
print("You leave the house with the note(" + note_001 + ")")
This is my next file
from intros.intro_001 import have_note_001
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
In the file, the import is working.
I am importing the have_note_001. It is just not transferring the value True over. It doesnt seem to remember when you give it that value you in the first file, to the second
How can I have the value assigned to a variable carry over to another file when imported?
I'm not sure what you are asking for is in your best interest. The values stored in variables are already carried over by default when you import the file they are from. However, this type of sporadic architecture is not really considered good practice. Let me give you some feedback on your program. First lets give it some input validation:
# start off setting keep_paper to nothing
keep_paper = ''
# As long as the player does not enter 'take' or 'leave' we are going to
# keep asking them to enter a proper response.
while keep_paper not in ['take', 'leave']:
# here we are going to "try" and ask the player for his choice
try:
# here we are getting input from the user with input(...)
# then converting it into a string with str(...)
# then converting it to lowercase with .lower()
# all together str(input(...)).lower()
keep_paper = str(input("Do you want to Leave the piece of paper or Take it? > ")).lower()
# if the player entered an invalid response such as "53" we will go back
# to the beginning and ask for another response.
except ValueError:
print("Sorry, I didn't understand that.")
# ask the user to provide valid input
continue
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
Now let's address the main topic of your question. Having the value assigned to a variable carry over on imports. As I've already mentioned, this is generally not something that you want, which is why most Python programs have code including:
if __name__ == "__main__":
# do xyz....
This ensures that xyz is only run if the file is being ran, and will not run if the file is imported.
For good measure, I recommend you checkout: https://github.com/phillipjohnson/text-adventure-tut/tree/master/adventuretutorial, reading over the code in this project will give you a better idea at how you might want to tackle your own project. (The basics of functions, classes and inheritance)
Ok so in this I have an issue where if the answer is "N" then it will still continue to the else statement. How do I fix this? (this is all in a function, edit: with other if statements that work fine)
if command == "Exit":
exit = 1
while exit == 1:
print("Quit? Y/N:", end="")
ex = input()
if ex == "Y":
quit()
elif ex == "N":
break
else:
print("Err")
The Code Seems To work Fine.
I assumed what you Want to do is : on Entering Exit ask user Y or N if user enters Y you quit the program if user enters N you want to break out of while loop. It works fine for both the cases can you add something else to the question to illustrate the problem.
I would also recommend you to try using return statnment while trying to break from multiple loop or if you are creating function for this purpose.
Make sure You are not entering small alphabets . You can use .upper() function to make sure you always use uppercase.
I have been trying to convert some code into a try statement but I can't seem to get anything working.
Here is my code in pseudo code:
start
run function
check for user input ('Would you like to test another variable? (y/n) ')
if: yes ('y') restart from top
elif: no ('n') exit program (loop is at end of program)
else: return an error saying that the input is invalid.
And here is my code (which works) in python 3.4
run = True
while run == True:
spuriousCorrelate(directory)
cont = True
while cont == True:
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
cont = False
elif choice == 'n':
run = False
cont = False
else:
print('This is not a valid answer please try again.')
run = True
cont = True
Now what is the proper way for me to convert this into a try statement or to neaten my code somewhat?
This isn't a copy of the mentioned referenced post as I am trying to manage two nested statements rather than only get the correct answer.
If you want to make your code neater, you should consider having
while run:
instead of
while run == True:
and also remove the last two lines, because setting run and cont to True again isn't necessary (their value didn't change).
Furthermore, I think that a try - except block would be useful in the case of an integer input, for example:
num = input("Please enter an integer: ")
try:
num = int(num)
except ValueError:
print("Error,", num, "is not a number.")
In your case though I think it's better to stick with if - elif - else blocks.
Ok so as a general case I will try to avoid try...except blocks
Don't do this. Use the right tool for the job.
Use raise to signal that your code can't (or shouldn't) deal with the scenario.
Use try-except to process that signal.
Now what is the proper way for me to convert this into a try statement?
Don't convert.
You don't have anything that raises in your code, so there is no point of try-except.
What is the proper way to neaten my code somewhat?
Get rid of your flag variables (run, cont). You have break, use it!
This is prefered way of imlementing do-while, as Python docs says; unfortunately, I cannot find it to link it right now.
If someone finds it, feel free to edit my answer to include it.
def main()
while True: # while user wants to test variables
spuriousCorrelate(directory) # or whatever your program is doing
while True: # while not received valid answer
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
break # let's test next variable
elif choice == 'n':
return # no more testing, exit whole program
else:
print('This is not a valid answer please try again.')
I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user hitting <Return> only. So far I have:
User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
Run my program
if User == # Not sure what to put here
Break
else
running == 1
I have tried: (as instructed in the exercise)
if User == <Carriage return>
and also
if User == <Return>
but this only results in invalid syntax.
Please could you advise me on how to do this in the simplest way possible.
Thanks
I ran into this page while (no pun) looking for something else. Here is what I use:
while True:
i = input("Enter text (or Enter to quit): ")
if not i:
break
print("Your input:", i)
print("While loop has exited")
The exact thing you want ;)
https://stackoverflow.com/a/22391379/3394391
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.
If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.
Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link
I think the following links would also help you to understand in much better way.
python cross platform listening for keypresses
How do I get a single keypress at a time
Useful routines from the MS VC++ runtime
I hope this helps you to get your job done.
Use a print statement to see what raw_input returns when you hit enter. Then change your test to compare to that.
This works for python 3.5 using parallel threading. You could easily adapt this to be sensitive to only a specific keystroke.
import time
import threading
# set global variable flag
flag = 1
def normal():
global flag
while flag==1:
print('normal stuff')
time.sleep(2)
if flag==False:
print('The while loop is now closing')
def get_input():
global flag
keystrk=input('Press a key \n')
# thread doesn't continue until key is pressed
print('You pressed: ', keystrk)
flag=False
print('flag is now:', flag)
n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()
You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)
if repr(User) == repr(''):
break
a very simple solution would be, and I see you have said that you
would like to see the simplest solution possible.
A prompt for the user to continue after halting a loop Etc.
raw_input("Press<enter> to continue")
user_input=input("ENTER SOME POSITIVE INTEGER : ")
if((not user_input) or (int(user_input)<=0)):
print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
import sys #import
sys.exit(0) #exit program
'''
#(not user_input) checks if user has pressed enter key without entering
# number.
#(int(user_input)<=0) checks if user has entered any number less than or
#equal to zero.
'''
Here is the best and simplest answer. Use try and except calls.
x = randint(1,9)
guess = -1
print "Guess the number below 10:"
while guess != x:
try:
guess = int(raw_input("Guess: "))
if guess < x:
print "Guess higher."
elif guess > x:
print "Guess lower."
else:
print "Correct."
except:
print "You did not put any number."
You are nearly there. the easiest way to get this done would be to search for an empty variable, which is what you get when pressing enter at an input request. My code below is 3.5
running = 1
while running == 1:
user = input(str('Enter <Carriage return> only to exit: '))
if user == '':
running = 0
else:
print('You had one job...')
I recommend to use u\000D. It is the CR in unicode.
Here's a solution (resembling the original) that works:
User = raw_input('Enter <Carriage return> only to exit: ')
while True:
#Run my program
print 'In the loop, User=%r' % (User, )
# Check if the user asked to terminate the loop.
if User == '':
break
# Give the user another chance to exit.
User = raw_input('Enter <Carriage return> only to exit: ')
Note that the code in the original question has several issues:
The if/else is outside the while loop, so the loop will run forever.
The else is missing a colon.
In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
It doesn't need the running variable, since the if clause performs a break.
If you want your user to press enter, then the raw_input() will return "", so compare the User with "":
User = raw_input('Press enter to exit...')
running = 1
while running == 1:
Run your program
if User == "":
break
else
running == 1
The following works from me:
i = '0'
while len(i) != 0:
i = list(map(int, input(),split()))