This question already has answers here:
Python Programming Unintentional Infinite Loop
(2 answers)
Closed 5 years ago.
Objectives
Familiarize the student with:
- using the break statement in loops;
- reflecting real-life situations in computer code.
Scenario
The break statement is used to exit/terminate a loop.
Using the while loop, design a program that continuously asks the user to enter a secret word (e.g.,"You're stuck in an infinite loop! Enter a secret word to leave the loop:") unless the user enters "chupacabra" as the secret exit word, in which case the message "You've successfully left the loop" should be printed to the screen, and the loop should terminate.
Don't print any of the words entered by the user. Use the concept of conditional execution and the break statement.
'''
Lab 2.2.22.1 - While loops with 'break' keyword use.
'''
secret_word = str(input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop."))
while secret_word != "chupacabra":
print("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.")
if secret_word == "chupacabra":
print("You've successfully left the loop.")
'''
just keeps printing out both lines continuosly - in a loop.
'''
Problem
When I run this program, it prints the first 2 lines and waits for an input. If the input matches the var, it doesn't display the "left the loop" string, it just does nothing. If I enter anything other than the correct secret word, it just keeps on printing in a never ending loop those first two lines again.
I'm stuck on how to use the while loop. I only want to do 2 things, print A if the input does not equal the var, and print B if the input does match the var. But everything I've read about the while loops is giving the while something to do, then the if or elif or else get something else to do each.
I'm struggling with this because I don't know how to write this loop so that while doesn't have to do anything, does this make sense?
I'm doing a python course atm, so please bear with me. This is not part of any exams or graded work, but I would rather understand what I'm doing wrong first please.
You need to read for secret_word in loop, and use break to exit when it matches wanted :
secret_word = ""
while True:
secret_word = input("You're stuck in an infinite loop!\nEnter a secret word to leave the loop.")
if secret_word == "chupacabra":
print("You've successfully left the loop.")
break
Related
I just did a YouTube tutorial to make a hangman game in Python. In the below code block, what does the first line (starting with if and ending with used_letters) of code mean in plain english? I don't understand it/what the code is doing.
# If it's on the alphabet and not in the used letters, add it
if user_letter in alphabet - used_letters:
used_letters.add(user_letter)
if user_letter in word_letters:
word_letters.remove(user_letter)
print('')
else: lives = lives - 1
print(user_letter, 'Letter is not in the word.')
elif user_letter in used_letters:
print("You have already used that character. Try again.")
else:
print("That's not a valid character. Try again.")
if lives == 0:
print(lives_visual[lives])
print("You have died. The word is: ", word)
else:
print("You guessed the word! It's:", word)
What I notice about this line of code, is that if the - used_letters is not there, then the elif statement will not execute when I run the program. I also don't understand how this line of code is impacting the elif statement.
If you want to see the full hangman program (only 57 lines) follow this link. This is exactly what I coded up in Python.
Thank you so much for your time and helping me to understand this! I truly appreciate it.
From the code:
alphabet = set(string.ascii_uppercase)
used_letters = set() # what the user has guessed
you can see that alphabet and used_letters are Python set() objects. Python set stores a list of unique values and supports operations like subtraction which results in a new set with items from the first set with eliminated items which are stored in the second set.
So alphabet - used_letters is a set with all letters not yet used.
Or said with words used by Barmar in the comment: alphabet and used_letters are sets of letters. The minus - operator is the set subtraction: it returns all the elements of the first set that are not in the second set. So alphabet - used_letters is a set with all the not yet used letters.
The if queries this resulting set checking if the user_letter is an item in the set named alphabet, but not an item in the set called used_letters. If this is the case ( True ) than the if block will be executed. If this is not not the case ( False ) the if block body code will be ignored ( skipped from execution ).
The elif will be executed only if the user_letter failed to give True in the if part. The elif part of code tests then as condition for executing the elif code block if user_letter is an item in the set used_letters. If it is, then the elif code block will be executed. If it is not, then the elif code block will be skipped and the else block will be executed instead.
I suggest you make a drawing visualizing the set elements of alphabet and used_letters to better understand what is said above and directly see yourself what is going on.
It basically checks if letter the user typed is already on the used letters.
The way it does this, is by first subtracting all of the used letters from the alphabet, if the used letter is in the result of this substraction, then it should be added to the "used_letters" set.
This is an operation between two sets, if you want to learn more about sets and how they work, you can read here
https://realpython.com/python-sets/
I am writing a code that takes a user inputted word or phrase, and then returns a string of the 50 words before and after the given word. I want it to be able to scroll through the instances where that word or phrase is found by pressing the space bar to continue, or any other button to quit. The problem that I'm running into is that if I use the keyboard.wait() method I can only allow for one type of user input, but if I use any of the other keyboard methods that I have tried it doesn't stop my while loop and accept input. Here is the code I'm currently working with, any ideas would be helpful.
while True:
keyboard.wait(" "):
x = (x+1)%len(where_found)
context = contents[where_found[x]-50:where_found[x]+50]
context = " ".join(context)
print(context+"\n")
where_found is a list containing all the index positions of the word that was searched for, or the first word if it was a phrase.
content is a list created with the read().split() method of file reading.
x is assigned a value of 1 before this section of code and allows the code to cycle through the instances where it was found.
Edit:
I have tried both readchar.readkey() and msvcrt.getch() with no success. When they are reached my shell responds as if it is waiting for an input, but never actually accepts one. I am using windows and python 3.8.5.
I tried to use keyboard.readkey from https://github.com/boppreh/keyboard but it kept returning two lines on each keypress.
Following a comment in this answer, here is a solution with https://github.com/magmax/python-readchar
It's API is a lot simpler and (on windows) it does not seem to have problems with blocking.
(contents.txt has the text from this question)
import readchar
with open('contents.txt', 'r') as fo:
contents = fo.read().split()
word = input('Please write a word to be searched: ')
print('\n### Press space for next match, any other key to exit\n')
print('matches found:')
x = -1
delta = 5
while True:
try:
x = contents.index(word, x+1)
context = ' '.join(contents[max(x-delta, 0):x+delta+1])
print(context)
if readchar.readkey() != ' ':
print('\n\nShutting down...')
break
except:
print('\n\nthere are no more matches')
break
Testing in terminal.
It waits for a keypress, I pressed only spaces.
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
of the 50 words before and after the given word. I
doesn't stop my while loop and accept input. Here is the
before this section of code and allows the code to cycle
there are no more matches
Testing with other keys
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
of the 50 words before and after the given word. I
You pressed '\r'
Shutting down...
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
You pressed 'd'
Shutting down...
This is a homework question and it asks "Pick a word. Ask the user to enter a letter. Check how many times the letter is present in your word and output the number on the screen." So far I have written it as is and it seems to be working fine:
word = str("python")
letters = len(word)
attempt = str(raw_input ("Enter a letter: "))
while attempt in word:
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
attempt = str(raw_input ("Enter another letter: "))
while attempt not in word:
attempt = str(raw_input ("This letter is not present, enter another letter: "))
count = "python".count(attempt)
if attempt in word:
print "This letter is present ",count, "time(s)."
but occasionally if I am inputting letters the program will stop and no longer take any more inputs. What am I doing wrong? I apologize if the code is very sloppy and poorly written as I am new to programming. Thanks.
I'm not sure if this is what you're getting at, but your while loops will execute one after the other. They don't both apply all the time. So the first while means "keep doing this as long as the user enters a letter that is in the word", and that loop will keep executing as long as the user enters letters in the word. As soon as the user enters one letter that isn't in the word, the loop will end and things will move on to the second loop. Execution will never go back to the first loop. Likewise, once in the second loop, if you then enter a letter that is in the word, the loop will end. Since that's the end of the program, the program will end.
So if you enter a letter that isn't in the word, then enter a letter that is in the word, the program will end. Like if you first enter "x" and then enter "y", it will then stop.
I think what you really want is more like:
while True:
attempt = raw_input("Enter a letter:")
if attempt in word:
print "That was in the word", word.count(attempt), "times"
else:
print "That was not in the word"
Of course, this program will loop infinitely until you close it by pressing Ctrl-Break or the like.
There are some other issues with your code. You don't need to wrap "python" in str, since that already is a string. You also don't need to wrap raw_input in a string, since raw_input already returns a string. You define a variable called letters but never use it.
Also, you define word = "python" at the beginning, but then sometimes later you use the word variable, while other times you retype the string "python" in your code. It doesn't matter for this program, but in general it's a good idea to assing the variable once and use that everywhere; otherwise you'll have to change it in many places if you decide to use a different word, which increases the likelihood that you'll forget to change it in one place, and thereby cause a bug.
Finally, note that in and count operate on substrings, not just single letters. So entering "yth" as as your input will still work and give a count of 1. There's not necessarily anything wrong with this, but you should be aware that although you're asking for letters the person can type in anything, and substrings of any length will still be found in the "word".
The program is sequential with two loops. Once those loops have been passed the program ends.
Loop 1: run while the input is found in the word.
As soon as this condition fails, we fall through to loop 2:
Loop 2: run while the input is not found in the word.
As soon as this condition fails, we fall through to the end of the program.
So, if you enter a "bad" input once, then a "good" input once, the program will end.
What you want to do is wrap both loops into one, and use an if-else to decide which each particular input is.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I determine if user input is a valid hexadecimal number?
Python - Program not displaying as intended
#Hex Check
def Check(HexInput):
while True:
if HexInput in Valid:
print('That is a valid hex number.')
else:
print('That is an invalid hex number.')
return HexInput
HexInput=input('Enter a hex number: ')
Valid='1234567890ABCDEFG'
Program needs to contain Check(). It should ask the user to input a hex number and tell them whether it's a valid hex number or not.
First of all,
while False:
will never execute. You can use "while True:" or "while checked == False:" but not "while False:"
Your Check() function must also take in parameters so that it looks like
def Check(UserInput, Valid):
You also need an additional "if" statement because even if the user inputs an invalid hex value, the program will still print "That is a valid hex value."
Next,
return Check
does not make sense as you do not have any variable named "Check"
Finally, you must actually call your function like so:
Check(UserInput, Valid)
It is not clear what you want to do in your program but for start , while False: mean that the code in the while loop will always be ignored (not executed)
The body of the while False: will never execute.
while False:
print("You will never enter this loop.")
.
.
.
This will execute, but you have to make sure you test for a condition,
so you can break out of the loop. That is you do not want to loop endlessly.
while True:
print("You will enter this loop.")
print("Make sure you test for a condition that will let you "break".)
break
Edit: You asked me to check your program. There are still some problems.
Use raw_input instead of input. The Python Tutorial at http://docs.python.org suggested raw_input.
The way you've written your program, if you have a multi-digit number, you'd need to check each digit, and that's what Python's for is for.
I've written something crude. In my version you'd test for 0 or non-zero. If
zero, you don't have a hex number. I'm sure there is a more elegant way to do this.
I strongly suggest fiddling with code in the Python command line. That's what it's for.
def Check(HexInput):
valid_hex_digit = 0 #Assume invalid
for digit in HexInput:
if digit in Valid:
valid_hex_digit = valid_hex_digit + 1
else:
error_str = "Invalid hex digit " + str(digit) + " found."
print(error_str)
valid_hex_digit = 0
break
return valid_hex_digit
I am working through some Looping exercises, While statements in particular. Here are the instructions:
2.2) Modify the program so that it asks users whether they want to guess again each time. Use two variables, number for the number and answer for the answer to the question whether they want to continue guessing. The program stops if the user guesses the correct number or answers "no". (In other words, the program continues as long as a user has not answered "no" and has not guessed the correct number.)
Here is my code:
#!usr/bin/env python
#
#While statement
number = 24
while number != 24:
answer = raw_input("Guess my lucky number! Do you want to keep guessing?")
if number == 24:
print "You got it! That is great!"
elif answer == "no":
print "Thank you for playing."
else:
print "That is not the right answer! Try again."
When I run the module in IDLE, the end quote of That is great!" - becomes red and says invalid syntax. In terminal if I run $ python while.py nothing loads. I've tried writing this as Python 3 functions with print("") but it still does not run.
Thanks to anyone who can help with this.
The while-cycle is never entered because the condition number != 24 never holds.
This is why there is no output.
Your loop never executes because you state that number = 24, and then right after, your while loop will only start if number != 24.
In addition, raw_input will yield a string, not an int so either ask for "24" or cast the raw_input to an int.
It also seems that you don't actually give the user a chance to guess the number at all; you only ask the user if s/he wants to keep playing.
You might want to do something like this:
number = 24
answer = ""
while answer != str(number):
answer = raw_input("Guess my lucky number, or type 'no' to quit.")
if answer == "no":
print "Okay, see you later"
break
elif answer != str(number):
print "wrong number"
if answer == str(number):
print "you got it right"
Here's the syntax issues:
answer = ""
while answer != "24":
answer = raw_input("Guess my lucky number! Do you want to keep guessing?")
if answer == "24":
# You can fill in the rest ...
Well, I don't want to straight out solve it for you, but take a look at your conditional in the while loop. Think about what happens, line-by-line, when you run it, particularly in the "number" variable.
The other answers are touching on the problem but there are more...
Yes you really should be checking the answer variable in your loop instead of the number variable, but also keep in mind that raw_input is going to give you a string. So you will not get an int 24, you will get a string "24". The idea here is to take the answer variable from raw_input and check that variable against both your number and the value "no"
number = "24"