This is kind of an extension to my last question, but I was wondering if it is possible to make the script go back to a specific line, if an event happens.
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
else:
print "not working"
On the last line, if 'else' happens, can you make it so it restarts from line 2 again?
Any help will be very greatly appreciated, thanks a lot!
You could put your code in an endless loop that only exits if the right word is typed in:
print "Type in 'Hello'"
while True:
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
break
else:
print "not working"
You can let the program lie in a loop till the correct input is given
while True:
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
break
there is 2 ways to do it , one with while loop , and one with recursion
the two answer before mine solved your problem with while loop , so i'd solve yours with recursion
def Inp():
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
else:
print "not working"
Inp()
Inp()
at the end just call the function Inp and it will continue asking for entering the value you want
Related
I'm new to coding and started with a python course now.
I was trying to work on a word bingo game but can't seem to make it work.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
list = bingo.split()
print
print "Okay, let's go! "
random.shuffle(list)
for choice in random.shuffle(list):
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
#for words in range(len(list)):
#user = raw_input()
#if user == "":
#print(random.sample(list, 1))
#raw_input("")
#else:
#print "That's the end of the game ^.^"
#break
If i use choice in random.shuffle(list) I get a NonType error
before I used a for loop with random.sample (seen in the ## parts at the end)
That worked except in each iteration the words were still repeated.
I tried to search for similar questions but they all either had numbers or more automatic loops.
I want it so the user enters words, then each time they press enter, a new word appears from the list without repetition.
I can't seem to figure out how to get that into a loop - any help?
I tried to use random.choice and random.sample but the words still kept repeating in a for loop.
Tried shuffle and had a nonType error
Two comments:
Don't use list for variable name, it is a keyword in Python for type list
random.shuffle(l) does operation in-place (i.e. after you called it, l will be shuffled). So, you just supply l into the loop. Hope this helps.
import random
from random import randint
print "Let's play Bingo!"
print
# prompt for input
bingo = input("First enter your bingo words: ")
# split up the sentence into a list of words
l = bingo.split()
print
print "Okay, let's go! "
random.shuffle(l)
for choice in l:
user = raw_input()
if user == "":
print(choice)
raw_input("")
else:
print "That's the end of the game ^.^"
break
P.S.
Why did you decide to use Python 2? If you are new to Python it can be better to work with Python 3. It is your decision to make. FYI, https://www.python.org/doc/sunset-python-2/#:~:text=We%20have%20decided%20that%20January,as%20soon%20as%20you%20can.
I am using break statement inside while loop to exit from while loop. But it gives wrong output. I don't know why this occurs. Here is the code I have used:
def func():
print "You have entered yes"
t='yes' or 'Y' or 'y' or 'Yes' or 'YES'
while True:
r=raw_input("Enter any number:")
if t=='r':
func()
else:
break
print "Program End"
Update:
When I put Yes it should give :
You have entered yes , but control goes to break statement. Why?
You should not use t = 'y' or 'Y' ... in your code because when you use or it checks the validity. Try this code and I am pretty sure it will work.
def func():
print "You have entered yes"
t=('yes', 'Y', 'y', 'Yes', 'YES')
while True:
r=raw_input("Enter any number:")
if r in t:
func()
else:
break
print "Program End"
Change
if t=='r':
to
if t==r:
Is that what you want?
First, you're checking if t is equal to the string literal 'r' and not the variable r, so in theory what you want is if t==r
However, this won't work. What you're looking for is a list, like the following:
def func():
print "You have entered yes"
t= ['yes','Y','y','Yes','YES']
while True:
r=raw_input("Enter any number:")
if r in t:
func()
else:
break
print "Program End"
When executing
t=='r'
you are comparing variable to a string r (this exact one character only), not to r variable.
There is a small code below containing of while-loop.
question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"
while True:
if question == "good":
print "Ok. Your mood is good."
state = False
question_2 = raw_input("How are you 2? > ")
elif question == "normal":
print "Ok. Your mood is normal."
elif question == "bad":
print "It's bad. Do an interesting activity, return and say again what your mood is."
else:
print "Nothing"
If I type in "normal", the program prints Ok. Your mood is normal. an infinite number of times.
But if I type in "good", the program prints Ok. Your mood is normal. and prints the contents of question_2.
Why is the question in question_2 = raw_input("How are you 2? > ") not repeated an infinite number of times?
Is it reasonable to conclude that raw_input() stops any infinite while loop?
No. It's not stopping the loop; it's actively blocking for input. Once input is received, it will not be blocked anymore (and this is why you get infinite text from other selections); there is no blocking I/O in those branches.
The reason you're not getting a lot of text output from option 1 is due to the way it's being evaluated. Inside of the loop, question never changes, so it's always going to evaluate to "good" and will continually ask you the second question1.
1: This is if it is indeed while True; if it's while state, it will stop iteration due to state being False on a subsequent run.
Once you've answered "good, the value returned by the second raw_input will be stored in variable question_2 rather than question. So variable question never changes again, but will remain "good". So you'll keep hitting the second raw_input, no matter what you answer to it. It doesn't stop your loop, but rather pauses it until you answer. And I think you should also take a good look at the comment of Alfasin...
You can stop an infinite loop by having an else or elif that uses a break for output. Hope that helps! :D
Example:
while True:
if things:
#stuff
elif other_things:
#other stuff
#maybe now you want to end the loop
else:
break
raw_input() does not break a loop. it just waits for input. and as your question is not overwritten by the second raw_input(), your if block will always end up in the good case.
a different approach:
answer = None
while answer != '':
answer = raw_input("How are you? (enter to quit)> ")
if answer == "good":
print( "Ok. Your mood is good.")
elif answer == "normal":
print( "Ok. Your mood is normal.")
# break ?
elif answer == "bad":
print( "It's bad. Do an interesting activity, return and say again what your mood is.")
# break ?
else:
print( "Nothing")
# break ?
here is my code.
highnum=100
lownum=0
guessnum=highnum/2
print "Please think of a number between 0 and 100!"
while True:
print "Is your secret number is "+str(guessnum)+"?"
print "Enter 'h' to indicate the guess is too high.",
print "Enter 'l' to indicate the guess is too low. ",
print "Enter 'c' to indicate I guessed correctly."
result=raw_input()
if result=="h":
highnum=guessnum
guessnum=int(highnum+lownum)/2
if result=="l":
lownum=guessnum
guessnum=int(highnum+lownum)/2
if result=="c":
break
else:
print "Sorry, I did not understand your input."
print "Game over. Your secret number was: "+str(guessnum)+" ."
Everytime I type the input, it prints out "Sorry, I did not understand your input." The condition "else" doesn't work.
I don't know why. Could anyone help me? Thank you very much!
Because as written, each of your if statements are independent, the else only corresponds to your last if result == 'c', so if they don't type 'c', they hit your else case.
Instead, you can use if/elif/else to try each of your cases.
if result=="h":
highnum=guessnum
guessnum=int(highnum+lownum)/2
elif result=="l":
lownum=guessnum
guessnum=int(highnum+lownum)/2
elif result=="c":
break
else:
print "Sorry, I did not understand your input."
I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin.
Here is my script:
import sys
print "********************************************************************"
print "** 1) This is menu choice #1 **"
print "** **"
print "** **"
print "** **"
print "** **"
print "** **"
print "********************************************************************"
print
print "Choice ?"
choice = sys.stdin.readline()
print "You entered: " + choice
if choice == 1:
choice1 = sys.stdin.readline()
print "You entered:" + choice1
else:
quit()
print "Exiting"
When I run the script, I get to the Choice? prompt. I enter 1 and I get the "You entered:" message and then the script exits without displaying the "Exiting" message.
Seems like it should be so easy. Thanks in advance for any help.
You're comparing a string to an integer. Try converting the string into an integer:
if int(choice.strip()) == 1:
Use raw_input() instead of sys.stdin.readline()
Change choice == 1 to choice == '1'
The problem is that readline returns a string, but your if statement expects an int. To convert the string to an int, you could use int(choice.strip()) (be prepared for it to raise an exception if what you enter isn't a valid number).
In [8]: choice
Out[8]: '1\n'
In [9]: int(choice.strip())
Out[9]: 1
Not sure, but I think the user is entering a string, not a number. The number 1 and the string 1 are two completely different things.
Try choice == "1"
The readline function retains the newline at the end of the input. Your first if should be:
if choice == "1\n":
assuming you want the newline.
It's exiting by calling quit() since it takes the else branch. That's because '1' (a string) does not equal 1, an integer.