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) + "."
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()
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))
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'm trying to set the scrambled word from the list back to the list I have created, which is from split. I tried reading some of the solutions here and I think it's because you can't change the string in the list?
I'm not really sure correct me if I'm wrong :( . the sentence[i] = temp_word is giving the error. thanks in advance :)
class WordScramble:
def __init__(self):
self.user_input = input("Please give me a sentence: ")
def scramble(self):
# print what was input
print("The user input was: ", self.user_input)
# first scramble is just one word
print(self.user_input[0] + self.user_input[2] + self.user_input[1] + self.user_input[3:])
# reverse two indices
# particularly good to use is to switch the first two
# and the last two
# this only makes sense if you have a world that is longer than 3
# now try to scramble one sentence
sentence = self.user_input.strip().split(" ")
for i, word in enumerate(sentence):
if len(word) > 3:
temp_word = list(word)
if ',' in temp_word:
temp = temp_word[1]
temp_word[1] = temp_word[-3]
temp_word[-3] = temp
else:
temp = temp_word[1]
temp_word[1] = temp_word[2]
temp_word[2] = temp
temp_word = ''.join(temp_word)
sentence[i] = temp_word
sentence = ''.join(sentence)
print(sentence)
#print(" ".join(sentence))
# do just words first, then you can move on to work on
# punctuation
word_scrambler = WordScramble()
word_scrambler.scramble()
Because inside the for loop you wrote:
sentence = ''.join(sentence)
Thus, at the second iteration, the 'sentence' variable is now a string and in python, strings don't support item assignment as they are immutable variables. I think you meant to get this out of the for loop to print the final sentence.
So I am trying to create a function that calls two functions within the function where one function called "encode" checks if the first letter of a word is a vowel and if yes it will add "way" to the end of the word and if the word starts with a consonant it will move the first letter to the third position in the word and adds gar.
my problem is creating that function that calls from the encode function to read a sentence and change each word accordingly based on the first letter.
So here are some text cases for the function:
encode() function:
The output will look like this:
Please enter your message: python is fun
The secret message is: ythonpar isway unfar
translation is correct when words are separated by more than one space character.
Please enter your message: simple is better than complex
The secret message is: implesar isway etterbar hantar omplexcar
Here is my script. They are suppose to be connected.
def get_input():
user_input = input('Please enter a message: ')
more_message = True
while more_message:
user_input = input('Please enter a message: ')
if not user_input==' ':
more_grades = False
return
def starts_with_vowel(word):
while True:
data = word
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
print ('true')
else:
print ('false')
return
def encode(word):
while True:
data = starts_with_vowel(word)
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
new_word=word+'way'
print ('The secret word is:',new_word)
else:
new_word2=word+'ar'
scrambled_word=new_word2[1:-2]+new_word2[0]+new_word2[3]+new_word2[4]
print (scrambled_word)
print ('The secret word is:',new_word2)
return
def translate(text):
secret_message= encode(text)
return (secret_message)
translate('gin is a boy')
A better approach would be to use split on the sentence (input) and loop over the words:
vowels = 'aeiou'
sentence = 'python is fun'
new_words = []
for word in sentence.split():
if word[0].lower() in vowels:
new_words.append(word+'way')
else:
new_words.append(word[1:3]+word[0]+word[3:]+'gar')
' '.join(new_words)
'ytphongar isway unfgar'
I think in the first part of the code you will need to change the more_grades section with more_message, because first off more_grades has not been initialized and more_messages is controlling your loop so i think that's what you meant to do. Don't worry I believe that's only one error I have caught I will check the rest of the code and get back to you. Don't stress it.Happy coding :-)