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))
Related
I'm trying to find find the longest string entered then print it as the output value. The program stops running when an 'a' has been entered then returns the longest string entered not just the numbers of characters in the string. Can the length function do this?
def longest_str(words):
words = len(words)
return words
true = 1
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
if words.startswith('a'): #comparing if starts with a or A
print(f"The longest string was: {longest_str(words)}") # printing output
break #stop once reached a
else:
continue # continue to loop through, no a was found.
I understand what you are trying to do but you have several mistakes
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
This will read only one word at the time.
So, your if will be executed only if you enter a word starting with 'a'.
This will solve your problem
def longest():
maxLength = 0
longestWord = ''
while(True):
word = str(input("Enter a string: "))
word = word.lower()
if word == 'a':
print(f"The longest string was: {longestWord}")
break
if len(word) > maxLength:
maxLength = len(word)
longestWord = word
Take a look at the differences
We check if the word entered is 'a', then print the longest string and stop.
If not, we check if the new word is longer than what we previously had (initialy nothing).If the new word is longer, we retain it to be able to print it.
Just call this in the main function.
If you want the string itself you could just do it like this:
longest_string = ''
while True:
word = input("Enter a string: ").lower()
if word == 'a': break
if len(word) > len(longest_string):
longest_string = word
print("The longest string was: " + longest_string)
Keep in mind, this will make ALL words lowercase, if you dont want that you have to remove the .lower()
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.
I have tried to make this work with a phrase, but I am having issues with getting it to the ie to go at the end of the words. For example HankTIE ouYIE would be the output of the input Thank You.
Here is what I have:
string=input("Please input a word: ")
def silly_encrypter(string):
strr = string.split()
for strr in string:
first_letter_at_the_end = strr[1:] + strr[0]
ie_at_the_end = first_letter_at_the_end + "IE"
print (ie_at_the_end)
silly_encrypter(string)
You can do this:
string=input("Please input a word: ")
def silly_encrypter(string):
splitspace = string.split() # first split the string into spaces.
for s in splitspace: # then looping over each element,
strlist = list(s) # turn the element into a list
strlist.append(strlist[0]) # first number to the last
del strlist[0] # delete the first number
strlist[0] = strlist[0].capitalize() # Capitalize the first letter
strlist.append('IE') # add IE
print(''.join(strlist), end=" ") # join the list
silly_encrypter(string)
Upon reading the accepted answer, I had to provide a cleaner solution:
def silly_encryptor(phrase, suffix="IE"):
new_phrase = []
for word in phrase.split():
new_phrase.append(word[1:]+word[:1]+suffix)
return " ".join(new_phrase)
phrase = input("Please enter your phrase: ")
print (silly_encryptor(phrase))
I have a while loop, which will keep asking a user to input words until they type stop. The input is stored in a variable called sentence.
My question is how do I store multiple inputs into one variable.
My current code is
stop = "stop"
sentence = []
while sentence != stop:
sentence = input("Enter a word: ")
sentence = sentence
print(sentence)
I don't understand how I would keep storing variables from one input and print out all the variable stored separated by commas/spaces etc
All you need to do is append() your new variables to the array:
>>> a = []
>>> for x in range(5):
... a.append("Hello!")
...
>>> a
['Hello!', 'Hello!', 'Hello!', 'Hello!', 'Hello!']
At the end, if you need everything in a single variable you can use join():
>>> ",".join(a)
'Hello!,Hello!,Hello!,Hello!,Hello!'
stop = "stop"
# okay --- 'sentence' is a list. Good start.
sentence = []
while sentence != stop:
# ...but now you've replaced the list 'sentence' with the word that was just input
# NOTE that in Python versions < 3, you should use raw_input below.
sentence = input("Enter a word: ")
# ...and this does nothing.
sentence = sentence
print(sentence)
Works better if you do something like this:
stop = "stop"
sentence = []
# create a new variable that just contains the most recent word.
word = ''
while word != stop:
word = input("Enter a word: ")
# stick the new word onto the end of the list
sentence.append(word)
print(sentence)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
...or to re-design a bit to omit the 'stop', something like:
stop = "stop"
sentence = []
while True:
word = input("Enter a word: ")
if word == stop:
# exit the loop
break
sentence.append(word)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
Its pretty simple
stop = "stop"
sentence = []
all = ""
while sentence != stop:
sentence = input("Enter a word: ")
all += sentence + ","
print(all)
One of your problems is that you are constantly writing over your sentence variable.
What you want to do is make use of the list append method. Documentation on lists:
https://docs.python.org/3/tutorial/datastructures.html
Example:
a = []
a.append(1)
a.append(2)
a.append(3)
print(a)
[1, 2, 3]
Next, you are looking to end your code if the user enters "stop". So what you should do is check in your loop if "stop" was written, and make use of Python's break, to break out of the loop.
What this means is that you should change your loop to loop indefinitely until you get that stop, using while True.
Your code can now simply look like this:
sentence = []
while True:
entry = input("Enter a word: ")
if entry == "stop":
break
sentence.append(entry)
print(sentence)
You probably want something like this:
sentence = []
while True:
word = input("Enter a word: ")
if word == "stop":
break
sentence.append(word)
print " ".join(sentence) + "."
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