How would I reloop this program back to ask the user for more input again? I am confused because if I use the while True: loop, it just prints out a whole bunch of the user's inputs.
userinput = str(input("enter a sentence: \n"))
def reverseinputs(x):
string = []
result = x.split(' ')
string += reversed(result)
print (' '.join(string))
reverseinputs(userinput)
def reverseinputs(x):
...
is a definition, and as such, doesn't execute anything (well, usually) and can safely be left out of the loop.
You seem to want to repeatedly ask the user for input and then process it with reverseinputs(). That task is achieved by the first line:
userinput = str(input("enter a sentence: \n"))
and the last line:
reverseinputs(userinput)
Placing those in a while(True) loop should yield the desired result:
def reverseinputs(x):
string = []
result = x.split(' ')
string += reversed(result)
print (' '.join(string))
while(True):
userinput = str(input("enter a sentence: \n"))
reverseinputs(userinput)
Your issue seems to come from misunderstanding userinput as a function, which would (with the right syntax) be executed each time it is referred to, giving a new input each time, rather than as a variable, which simply gives whatever value it was last assigned (in this case, the first user input).
Sidenote: As #diligar pointed out in the comments, it's always a good idea to give some way for the user to get out of an infinite loop. Something like this should work:
while(True):
userinput = str(input("enter a sentence: \n"))
if userinput == "": break
...
How about simply:
while True:
userinput = input("enter a sentence: \n")
if not userinput:
break
print(' '.join(reversed(userinput.split())))
Though more elegant ways exist, a quick and simple solution is to add this at the end of the function:
x = str(input("enter a sentence: \n"))
reverseinputs(x)
Essentially, you're creating a recursive function here. I think a more elegant solution is using the while loop like you mentioned like this:
def reverseinputs(x):
string = []
result = x.split(' ')
string += reversed(result)
print (' '.join(string))
while True:
userinput = str(input("enter a sentence: \n"))
reverseinputs(userinput)
Related
I am writing a program that takes a statement or phrase from a user and converts it to an acronym.
It should look like:
Enter statement here:
> Thank god it's Friday
Acronym : TGIF
The best way I have found to accomplish this is through a list and using .split() to separate each word into its own string and am able to isolate the first letter of the first item, however when I try to modify the program for the following items by changing to print statement to:
print("Acronym :", x[0:][0])
it just ends up printing the entirety of the letters in the first item.
Here's what I have gotten so far, however it only prints the first letter of the first item...
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
print("Acronym :", x[0][0])
Using re.sub with a callback we can try:
inp = "Peas porridge hot"
output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
print(output) # PPH
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
result = ''
for i in x:
word = list(i)
result+=word[0]
print(result)
The code needs to iterate through the .split result. For example, using a list comprehension:
inp = "Thank god its friday"
inp = inp.split()
first_lets = [word[0] for word in inp]
I'm using python3 on mac.
I'm currently doing a project. However, I was trying to use "while = True" to continuously use the program until a condition is met. Please, tell me what am I missing in my code. Thanks!
import json
import difflib
from difflib import get_close_matches
data = json.load(open("project1/data.json"))
word = input("Enter a word or enter 'END' to quit: ")
def keyword(word):
word = word.lower()
while type(word) == str:
if word in data:
return data[word]
elif word == 'END'.lower():
break
elif len(get_close_matches(word, data.keys())) > 0:
correction = input("Did you mean %s insted? Enter Yes of No: " % get_close_matches(word, data.keys())[0])
if correction == "Yes".lower():
return data[get_close_matches(word, data.keys())[0]]
elif correction == "No".lower():
return "This word doesn't exist. Plese enter again. "
else:
return "Please enter 'Yes' or 'No: "
else:
return "This word doesn't exist. Please enter again."
print("Thanks!")
output = (keyword(word))
if type(output) == list:
for item in output:
print(item)
else:
print(output)
I think this might be the setup you are looking for.
def keyword(word):
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys())):
correction = input(f"Did you mean {get_close_matches(word, data.keys())[0]} instead? y/n: ")
if correction == 'y':
return data[get_close_matches(word, data.keys())[0]]
elif correction == 'n':
return "This word doesn't exist. Please enter again."
else:
return "Please type 'y' or 'n': "
else:
return "This word doesn't exist. Please enter again."
while True:
word = input("Enter a word: ").lower()
if word == 'end':
print("Thanks!")
break
else:
print(keyword(word))
Looking at the source code and your question, it seems like what you want to achieve is basically to continuously accept input from the user until the user enters something like 'end'. One way to go about this is to separate out the while-loop logic from the function. The overarching while-loop logic is at the bottom half of the code, where we continuously accept input from the user until the user inputs some lower or upper case variant of 'end'. If this condition is not met, we proceed to printing out the result of the function call keyword(word).
Minimal modifications were made to the original keyword() function, but here are a few changes worthy of note:
The while type(word) == str is unnecessary, since the result stored from the input() function will always be a string. In other words, the condition will always return True.
Having return statements within a while loop defeats the purpose of a loop, since the loop will only be executed once. After returning the specified value, the function will exit out of the loop. This is why we need to separate out the loop logic from the function.
Although %s works, it's a relic of C. This might be a matter of personal choice, but I find f-strings to be much more pythonic.
You are using the worng condition.
type((3,4))== list
is False. You must use
type((3,4)) == tuple
I want to take user input and compare it to a list of key words through a function, if any of the words input by the user match a key word, the condition is met and breaks the loop. If none of the words match a key word, then the console asks for input again. I have been manipulating this loop and have either gotten it to continuously ask for input no matter if a key word is met or validate every word input. Any advice on how to correct it would be great appreciated.
def validated_response(user_complaint):
valid_list = user_complaint.split()
while True:
if user_complaint == "stop":
break
for valid in valid_list:
if valid.lower() not in user_complaint.lower():
print("Response not recognized, please try again")
input("Enter response: ")
continue
else:
print("response validated: ")
break
return True
This function will continue getting user input until the input matches "kwrd1", "kwrd2", or "kwrd3":
def get_input():
keywords = ['kwrd1', 'kwrd2', 'kwrd3']
user_input = None
while True:
user_input = input()
if user_input in keywords:
break
return user_input
If you are matching it against a python keyword, there is a builtin keyword module:
import keyword
def get_input():
user_input = None
while True:
user_input = input()
if keyword.iskeyword(user_input):
break
return user_input
You are always reaching the else statement if the first element in valid_list is not a substring of the user_complaint string. That means you're always breaking out of the for loop and reentering the infinite while loop. Try this instead:
def validated_response(user_complaint):
valid_list = user_complaint.split()
if user_complaint == "stop":
return
inp = input("Enter response: ")
while inp.lower() not in valid_list:
inp = input("Enter response: ")
The provided code has a number of problems. The example does also not show how the function would be called, but I assumed you'd want to call it with a text that has all the keywords you're looking for.
The first problem is you are calling input, but not storing its return value, so you're not actually collecting the user input.
Secondly, you're comparing the various parts of valid_list to the contents of user_complaint.lower(), but that means you're compare a string to the characters in another string - not what you want.
Thirdly, you're asking for new input in a single clause of a condition, inside your loop, so this will lead to messages printing repeatedly and the user having to enter new text before all the comparisons are done.
Finally, you're mixing continue, break and return in a way that doesn't work. continue tells Python to move on to the next cycle of a loop, skipping any remaining code in the current cycle. break tells Python to get out of the current block (in this case the loop). return tells Python to exit the function altogether and return a provided value (or None if none is provided).
Here is an example that more or less follows the structure you set up, but with all of the problems remedied:
def validated_response(keywords):
valid_list = keywords.split()
while True:
user_input = input('Enter response: ').lower().split()
if user_input == ['stop']:
return False
for valid in valid_list:
if valid.lower() in user_input:
print('response validated: ')
return True
print('Response not recognized, please try again')
print(validated_response('trigger test'))
I want to assign word, translation, and notes to one index in the list, but I keep getting errors. I want to go increment the index each time it goes through the loop, assigning the variables to the same index. I'm new to Python so any help is appreciated. I want to be able to search for the words later so if there is a better way to do so please explain it.
num = 0
listOfWords = [[] for i in range(3)]
def WriteToFile():
word = ""
while word != "quit":
word = input(str("Enter the word: "))
if word != "quit":
listOfWords[num][num][num].append(word,translation,notes)
num += 1
else:
break
I think you're complicating yourself a bit much. You can append any number of lists to a listOfWords, and thus get the data structure you need.
Here's what I would, though I assume you define translation and notes elsewhere, I also input them:
listOfWords = []
word = ""
while word != "quit":
word = input(str("Enter the word: "))
if word != "quit":
translation = input(str("Enter the translation: "))
notes = input(str("Enter the notes: "))
listOfWords.append([word, translation, notes])
print(listOfWords)
Output:
Enter the word: Hola
Enter the translation: Hello
Enter the notes: greeting
Enter the word: Perro
Enter the translation: Dog
Enter the notes: animal
Enter the word: quit
[['Hola', 'Hello', 'greeting'], ['Perro', 'Dog', 'animal']]
I'm new to python and I'm trying to create a program that lets the user send words to the program and it will add them to a list then make the list a string and print it.
class joinString():
op_list = [] # this is what i was told to do to initialize a list
def init(self): # idk what this is used for to be honest
print("Hello")
def main(self):
string_in = "" # string input
print("Enter strings, to stop enter a '0'")
while string_in != '0': #while loop checks if string equals '0', stop
string_in = input("String: ") #asks user for inputs
joinString().op_list.append(string_in)
final_string = ''.join(joinString().op_list) # makes final string
print("Final Product: " + final_string) # prints final string
if __name__ == "__main__": #idk what a name is
test = joinString()
test.main()
# I took AP computer science A (coding in java) and scored pretty well but I
# didn't know where to go from there so I'm trying to learn java.
In your main you're using joinString() when you should be using self. A larger issue is that you're writing Java style code in Python. Here's a more Pythonic solution to your problem:
print('Type a word then hit enter. Leave blank to exit.')
words = []
while True:
word = input('Word: ')
if not word:
break
words.append(word)
print(*words)
First we print out a message telling the user how to use the program. We use the empty string to indicate that the users wants to exit.
print('Type a word then hit enter. Leave blank to exit.')
Then we create an empty list, words, to store the user's input.
words = []
Next, we enter an infinity loop (don't worry we'll break out of it later).
while True:
We ask the user to enter a word and store it in word.
word = input('Word: ')
In Python, the empty string is false. So we check if the user entered nothing.
if not word:
If they enter nothing, we break out of the infinite loop.
break
If they entered something, we add the word they entered to the end of words and loop back around.
words.append(word)
Be default, print() puts a space between each object it prints. So, we use the * operate to pass each element of words as an argument to print(). This causes each word to be printed with a space between them.
print(*words)
Hope that helps you learn Python.
Your main method should refer to the instance with self rather than instantiating another instance of joinString with joinString().
Replace:
joinString().op_list.append(string_in)
with:
self.op_list.append(string_in)
and replace:
final_string = ''.join(joinString().op_list)
with:
final_string = ''.join(self.op_list)
Also, the init method should be spelled __init__, and is used to initialize the object when it's being instantiated.
class joinString():
op_list = []
def main(self):
string_in = "" # string input
print("Enter strings, to stop enter a '0'")
while True:
string_in = input("String: ") #asks user for inputs
if string_in == '0':
break
joinString().op_list.append(string_in)
final_string = ''.join(joinString().op_list) # makes final string
print("Final Product: " + final_string) # prints final string
if __name__ == "__main__":
test = joinString()
test.main()
This code is working on my end. I changed your while condition because it was adding 0 to the final string