I'm having some trouble working on a basic program I'm making whilst I try and learn Python, the problem is I am trying to compare a users input to a variable that I have set and it is not working when I try and compare them.
This is the loop in question:
if del_question == "1":
symbol = input("What symbol would you like to change?: ")
while len(symbol) != 1 or symbol not in words:
print("Sorry, that is not a valid symbol")
symbol = input("What symbol would you like to change?: ")
letter = input("What would you like to change it to?: ")
while letter in words and len(letter) != 1:
print("Sorry, that is not a valid letter")
letter = input("What letter would you like to change?: ")
dictionary[symbol] = letter
words = words.replace(symbol, letter)
print("Here is your new code: \n", words)
The game is about breaking the code by pairing letters and symbols, this is where the letters and symbols are paired but on the letter input when I try and make it so that you are unable to pair up the same letter twice it simply bypasses it. It is working on the symbol input but I'm not sure on why it's not working here.
Here is the text file importing:
code_file = open("words.txt", "r")
word_file = open("solved.txt", "r")
letter_file = open("letter.txt", "r")
and:
solved = word_file.read()
words = code_file.read()
clue = clues_file.read()
This is the contents of the words file:
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
Your bug is a simple logic error. You have an and conditional when you really want an or conditional. Change your second while statement to:
while letter in words or len(letter) != 1
Related
So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!
Part of code where problem occurs:
for letter in secret_word:
if user_guess == letter:
current_word_index = secret_word.find(letter)
print(current_word_index) #Not in full program, only to test errors.
Full code:
#Hanging man
import string
space = "\v"
dbl_space = "\n"
secret_word = str(input("Enter a secret word: "))
guess_low = list(string.ascii_lowercase)
used_letters = []
user_errors = 0
user_errors_max = 1
secret_word_index = int(len(secret_word))
secret_word_placeholder = list(range(secret_word_index))
while user_errors != user_errors_max:
user_guess = str(input("Enter a letter: "))
if len(user_guess) != 1:
print("You have to pick one letter")
if user_guess in guess_low:
guess_low.remove(user_guess)
used_letters.extend(user_guess)
print(used_letters)
for letter in secret_word:
if user_guess == letter:
current_word_index = secret_word.find(letter)
if user_errors == user_errors_max:
print("You lost the game, the secret word was: " + secret_word)
This is an example of what you are trying to achieve. use list comprehension.
string='hello'
letter='l'
[idx for idx,ch in enumerate(string) if ch==letter]
Python's string find accepts a start parameter that tells it where to start searching:
>>> "guacamole".find('a')
2
>>> "guacamole".find('a', 3)
4
Use a loop, and use the index of the last hit you found + 1 as the start parameter for the next call.
Another more verbose solution might be:
str1 = "ooottat"
def find_all_indices(text, letter):
indices_of_letter = []
for i, ch in enumerate(text):
if ch == letter:
indices_of_letter.append(i)
return indices_of_letter
print(find_all_indices(str1, 'o'))
Side note:
Indexes is the nontechnical plural of index. the right technical plural for index is indices
Yes, if you instantiate a new_variable to be the secret_word variable before the for loop, the in the line current_word_index = secret_word.find(letter) change secret_word.find(letter) to new_variable .find(letter) then below the if statement write new_variable = new_variable [1:] which will remove the letter just found.
so your code would look something like:
new_variable = secret_word
for i in secret_word
if user_guess == letter:
current_word_index = new_variable.find(letter)
#I would do print(current_word_index) this will show the index
#Or current_word_index = current_word_index + ',' + new_variable.find(letter)
new_variable= new_variable[1:] #this will take away your letter.
I'm trying to write a program that stops if the same word is given twice. This code almost does the job, but it stops only if the duplicate words are given sequentially. Thanks for your help.
list = []
double = None
while True:
word = input("word: ")
lista.append(word)
if douple == word:
print(f"You gave {len(list)} words")
break
double = word
You need to check if the word is already in the list
seen = []
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen.append(word)
If you just want to tell duplicates, and don't need to keep the order, you can use a set instead; this will be more efficient for a large number of words:
seen = set()
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen.add(word)
Finally, in sufficiently recent Python (at least 3.6 or 3.7, depending on how you take things), you can do both by using a dictionary; this is both efficient and keeps the order in which the words were entered:
seen = {}
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen[word] = None
Change your code to what is given below:
words_list = []
while True:
word = input("Word: ")
if word not in words_list: #Checks if the word is in the list. If it exists in list, it would return False
words_list.append(word)
else:
print(f"You gave {len(words_list)} words")
break
I have changed a few things:
Don't use list as a variable name as it is a keyword in Python.
Check for duplicate words using not in before you append it to the list. If word exists in the list, the loop would break.
This should do the work. You can always comment down if you need clarification or if the code dosen't work.
what's wrong with this code : I am trying to run this code in a loop and with every loop it take two arguments but it does not works, it's runs only two time then printing constantly unnecessary things.
Code:
words= "this is my computer and my computer is super computer"
wordlist = words.split(" ")
changed_wordlist=[]
while (True):
replace = input("replace this: ")
with_this = input("with this: ")
for word in wordlist:
if word == replace:
replacedword = word.replace(replace, with_this)
print(replacedword,end=" ")
changed_wordlist.append(replacedword)
elif word!= replace:
print(word,end=" ")
changed_wordlist.append(word)
wordlist = changed_wordlist
I created an example that would change the words from the list, and then print its content after the change, both if the word was found or not. Try this:
words = "this is my computer and my computer is super computer"
wordlist = words.split(" ")
while (True):
replace = input("replace this: ")
with_this = input("with this: ")
# Iterate over the list, looking for the word
# to replace
for i in range(len(wordlist)):
# If we find the word, we replace it
if wordlist[i] == replace:
wordlist[i] = with_this
print("The list is now: " + str(wordlist))
The task that I am doing is to develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.
sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
sentencetext=sentence.isalpha or sentence.isspace()
while sentencetext==False: #if letters have not been entered
print("Only letters are allowed") #error message
sentence=input("Please enter a sentence").upper() #asks the question again
sentencetext=sentence.isalpha #checks if letters have been entered this time
word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
print(sentence)
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
elif question=="N":
print("The program will now close")
else:
print("you did not enter one of the prescribed letters")
words.write(word + " ")
position.write(positionofword + " ")
The problem for me is that I am stuck in the loop of:
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
Which therefore means that I cannot get the words into the file. I have tried to use break, but that did not work out for me because I could not get the words into the file.
I'm new to this site, but I've been stalking for quite a while. Hopefully this is right, I'm open to hearing criticism if I've worded this wrong.
Your logic in the for loop is incorrect - rather than asking once what the word the user wants to find, you ask that for each word in the sentence, and only match if they enter the word they want when that is the current word being checked. You are also printing the sentence once for each word in the sentence. Restructure it like so:
print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
if (check == word):
print("your word is in this position:", i+1)
positionofword=i+1
break
else:
print("This didn't work")
This is my caesar cipher so far- it works with spaces but it won't work with capitals. Can you please help me put in an IF statement to get it to work?
I've tried:
elif letter==letter.upper():
finalphrase=alphabet[(alphabet.index(letter)+offset)%26].upper()
but it still doesn't work...
#Caesar Cipher - Encrypts/Decrypts the user's input
#Asking the user if they want to encrypt or decrypt a word/phrase
EorD = input("Please input either 'e' (for encrypt) or 'd' (for decrypt): ")
#IF Statement to decide whether the offset gets saved as a positive or a negative integer
if EorD.lower() == 'e':
offset = int(input("Please input your chosen offset: "))
elif EorD.lower() == 'd':
offset = -int(input("Please input your chosen offset: "))
else:
print("Error")
#Asking the user for their phrase
phrase = input("Please input a word/phrase: ")
#alphabet stored in a list
alphabet= ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#A FOR loop - to loop through the individual letters in the phrase
for letter in phrase:
if letter in alphabet:
finalPhrase = alphabet[(alphabet.index(letter)+offset)%26]
else:
finalPhrase = letter
print(finalPhrase, end="")
Replace
alphabet.index(letter)
by
alphabet.index(letter.lower())
RĂ©mi was able to show you what you had wrong in your index search. I'd also like to add that the if statement in the for loop could be:
if letter.lower() in alphabet:
This will return the cipher as a lowercase, but from here I think you should be able to figure out the rest if you want to return an uppercase solution.
I did it!!!
for i in word:
if i in alphabet:
newword = alphabet[(alphabet.index(i)+offset)%26]
elif i==i.upper():
newword = alphabet[(alphabet.index(i.lower())+offset)%26].upper()
else:
newword = i
print(newword, end="")