Python - my while loop is stopping itself - python

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.

Related

Python Beginner, Easy Question: Help me to understand what this line of code does and why it impacts elif?

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/

Keeping track of position in searched text when the same word appears more than once

def test():
users_note = """There is a substantial need for child mental health support –
evidence shows that at any given year,
1 in 10 young people will have a diagnosable mental health problem.
Out of these incredibly high numbers,
70% of these young people do not receive adequate mental health support at all,
and of the 30% that do,
only half of them improve.
Though we have evidence-based intervention techniques that work,
we are still relying on outdated technologies and delivery mechanisms.
"""
note_list = users_note.split()
while True:
for users_try in range(5):
word_list = input('Enter words you gonna say next: ').split()
for word in word_list:
if word not in note_list:
print('Sorry, try again')
else:
print(note_list[note_list.index(word) + 1])
else:
break
This function is essentially a teleprompter. When the user inputs a word or multiple words in any order, the function prints the word right after each of the user's input words. However, there's an edge case when an input word occurs multiple times within the pre-made text; the function always prints the word the first occurrence. How can this function be modified in order to keep track of the user's input word position within the pre-made text? For example:
For the first occurrence of "a" in the pre-made text:
Enter words you gonna say next: a
substantial
If the user has already passed that point in the text, inputting "a" a second time:
Enter words you gonna say next: a
diagnosable
For the first occurrence of "these" in the pre-made text:
Enter words you gonna say next: these
incredibly
If the user has already passed that point in the text, inputting "these" a second time:
Enter words you gonna say next: these
young
In other words, the program should continue moving forward in the text once a word has already been searched for. How do I accomplish that?
As long as you don't intend for the user to ever be able to go backwards in the text, an easy solution is to modify note_list as you go:
if word not in note_list:
print('Sorry, try again')
else:
note_list = note_list[note_list.index(word) + 1:]
print(note_list[0])
This makes it impossible to ever "repeat" a particular word, whether the word is unique or not.

The break statement - Stuck in a loop [duplicate]

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

How to fix this Anagram Scrambler code?

print "YOU HAVE CHOSEN TO REARRANGE YOUR THE WORD THAT YOU ARE ABOUT TO ENTER..."
word = raw_input ("FIRSTLY YOU MUST ENTER A WORD TO BE REARRANGED, ENTER IT HERE:")
character_save = word[1]
def anagram(word):
if len(word)>1:
print str.replace('a','b')
word = str.replace(word[1],word[3])
word= str.replace(word[3], character_save,1)
print word
anagram(word)
I tried to fix this on numerous occasions, the problem with the first time was that it would just replicate characters instead of replacing the positions, the second time I tried to store the position that I was going to replace in a variable but now it mentions that I have only one argument given (when it should be 2).
Would it be easier to do this with a list instead of a string?
The replace message that you are using is called on the string that you want to replace and not on the str type itself.
In your case that is the word parameter that you are providing.
So if you replace the instances of str.replace with word.replace your code will run. However, it doesn't create an anagram yet. The algorithm is still lacking.

Finding specific words in a file

I have to write a program in python where the user is given a menu with four different "word games". There is a file called dictionary.txt and one of the games requires the user to input a) the number of letters in a word and b) a letter to exclude from the words being searched in the dictionary (dictionary.txt has the whole dictionary). Then the program prints the words that follow the user's requirements. My question is how on earth do I open the file and search for words with a certain length in that file. I only have a basic code which only asks the user for inputs. I'm am very new at this please help :(
this is what I have up to the first option. The others are fine and I know how to break the loop but this specific one is really giving me trouble. I have tried everything and I just keep getting errors. Honestly, I only took this class because someone said it would be fun. It is, but recently I've really been falling behind and I have no idea what to do now. This is an intro level course so please be nice I've never done this before until now :(
print
print "Choose Which Game You Want to Play"
print "a) Find words with only one vowel and excluding a specific letter."
print "b) Find words containing all but one of a set of letters."
print "c) Find words containing a specific character string."
print "d) Find words containing state abbreviations."
print "e) Find US state capitals that start with months."
print "q) Quit."
print
choice = raw_input("Enter a choice: ")
choice = choice.lower()
print choice
while choice != "q":
if choice == "a":
#wordlen = word length user is looking for.s
wordlen = raw_input("Please enter the word length you are looking for: ")
wordlen = int(wordlen)
print wordlen
#letterex = letter user wishes to exclude.
letterex = raw_input("Please enter the letter you'd like to exclude: ")
letterex = letterex.lower()
print letterex
Here's what you'd want to do, algorithmically:
Open up your file
Read it line by line, and on each line (assuming each line has one and only one word), check if that word is a) of appropriate length and b) does not contain the excluded character
What sort of control flow would this suggest you use? Think about it.
I'm not sure if you're confused about how to approach this from a problem-solving standpoint or a Python standpoint, but if you're not sure how to do this specifically in Python, here are some helpful links:
The Input and Output section of the official Python tutorial
The len() function, which can be used to get the length of a string, list, set, etc.
To open the file, use open(). You should also read the Python tutorial sec. 7, file input/output.
Open a file and get each line
Assuming your dictionary.txt has each word on a separate line:
opened_file = open('dictionary.txt')
for line in opened_file:
print(line) # Put your code here to run it for each word in the dictionary
Word length:
You can check the length of a string using its str.len() method. See the Python documentation on string methods.
"Bacon, eggs and spam".len() # returns '20' for 20 characters long
Check if a letter is in a word:
Use str.find(), again from the Python sring methods.
Further comments after seeing your code sample:
If you want to print a multi-line prompt, use the heredoc syntax (triple quotes) instead of repeated print() statements.
What happens if, when asked "how many letters long", your user enters bacon sandwich instead of a number? (Your assignment may not specify that you should gracefully handle incorrect user input, but it never hurts to think about it.)
My question is how on earth do I open the file
Use the with statement
with open('dictionary.txt','r') as f:
for line in f:
print line
and search for words with a certain length in that file.
First, decide what is the length of the word you want to search.
Then, read each line of the file that has the words.
Check each word for its length.
If it matches the length you are looking for, add it to a list.

Categories