Python while loop to prompt until stop is entered - python

I need the code to ask the user to enter a word and print them out in a sentence once stop is entered. I have the following code:
`a = input("Enter a word: ")
sentence = ()
while a != ("stop"):
sentence = sentence , a
a = input("Enter a word: ")
print (sentence)`
However I don't know how to set the variable 'Sentence' so that nothing prints at the start. How can I rectify this?

In order to get a string, you need to use raw_input() instead input() (input saves as int, double etc...).
Replace input() to raw_input().
In addition, sentence = () - saves tuple and sentence = sentence , a - adds more tuples and not a string as i think you want.
Try to explain again what you mean.

You can try the following:
a = input("Enter a word: ")
sentence = ""
while a != "stop":
sentence = sentence + " " + a
a = input("Enter a word: ")
print (sentence)
input (raw_input in python 2) will allow you to write strings without the need for quotes. Sentence has to be initialized to an empty string "", and concatenated as a string (here with a simple + ).

Related

Printing individual letters in a list

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]

The user must be prompt to input the string and choose which characters to make replace

I need to prompt the user to input a string and I should prompt an input that will ask the user to input which characters to replace from the string.
string = input('Enter sentence: ')
string = string.replace(" ","")
print (string)
print ("\n")
Like this:
In [1677]: string = input('Enter sentence: ')
Enter sentence: I am James Bond
In [1678]: replace_input = input("Enter chars to be replaced:")
Enter chars to be replaced:a
In [1679]: string.replace(replace_input, ' ')
Out[1679]: 'I m J mes Bond'
I need to prompt the user to input a string. You have this part done correctly.
string = input('Enter sentence: ')
and I should prompt an input that will ask the user to input which characters to replace from the string. I can't see where you asked for a second input.
replace_input = input('Enter string to replace: ')
now you can continue with your code
string = string.replace(replace)input, "")
print(string + "\n")

Simple search and replace in Python using recursion and user input

I have this simple program that takes input of a word, asks the user what part they would like to substring out and then asks what to replace it with and lastly print the result. But i need to convert it into working recursively.
I've created it in a basic sense working in Python here.
word = input("Enter a word: ")
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)
It should work recursively and display like:
Enter a word: world
Please enter the substring you wish to find: or
Please enter a string to replace the given substring PP
Your new string: is wPPld
Help would be greatly appreciated.
You can use a while loop, but you need to define a stop word to have a way out. In this example, I defined the stop word as quit:
word = ''
while (word != 'quit'):
word = input("Enter a word: ")
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)
I think that this is what you want, but please note that this is not recursion.
EDIT: a version of the code using recursion with the same stop word:
def str_replace_interface():
word = input("Enter a word: ")
if word != 'quit':
substring = input("Please enter the substring you wish to find: ")
new_entry = input("Please enter a string to replace the given substring: ")
new_word = word.replace(substring, new_entry)
print("Your new string is: " + new_word)
str_replace_interface()
str_replace_interface()

Replacing part of a string using a For loop

I need to get a user to enter a sentence for an assignment. Using a for loop, I then need to replace all spaces with %20 in order to prep the string to be used as a URL. I cannot for the life of me figure it out.
sentence = str(input("Please enter sentence:"))
space = (" ")
for space in sentence:
space.replace(sentence, space, "%20", 500)
print(sentence)
This is what I have entered so far but it is completely wrong.
String in Python can't be modified. The replace() function returns a new string with all the replacements done. You need to assign this result somewhere. So you can do:
sentence = sentence.replace(" ", "%20")
If you want to do it with a loop, you need to build the result in another variable.
new_sentence = ""
for char in sentence:
if char == " ":
new_sentence += "%20"
else:
new_sentence += char
There's no point in using replace() in the loop.
Replace everything after the first line with print(sentence.replace(" ","%20"))
or, if you really must use a loop:
s = ''
for x in sentence:
if x == ' ':
s += "%20"
else:
s += x
print(s)
you've got a few problems here:
the variable space that you define before the loop is equal to " " but then you're using the same name for the for loop variable, which is going to iterate through the string the sentence string, in the loop, it's going to use the value defined by the loop.
You're giving the replace method too many arguments, it's a method of the string object so you don't need to pass it the large string to operate on Replace Method
You're using the replace method on the space string and not on the sentence string
Good way to do it in real life:
old = ' '
new = '%20'
sentence = str(input("Please enter sentence:"))
print(sentence.replace(old,new))
The way your teacher is probably after:
sentence = str(input("Please enter sentence:"))
old = ' '
new = '%20'
newSentence = ''
for letter in sentence:
if letter == ' ':
newSentence += new
else:
newSentence += letter
print(newSentence)

Python, list, index

I'm trying to write a small program for my python course(teaching myself), kinda like a dictionary using lists. One list has a phrase/word in it and the other list has the meaning of the phrase/word. Through user input the user can type the word they are searching for and the words meaning would be shown. I'm having trouble trying to get the meaning to be shown. My code is below: "aldo" is my first input(word), "my name" is my second input(meaning)
word = []
meaning = []
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
print(word)
print(meaning)
word = word + [user_word]
meaning = meaning + [user_meaning]
user_search = input("What word/phrase would you like to search: ")
search_index = word.index(user_search)
print(user_search + meaning.index(search_index))
There are a few bugs/issues in your code.
Printing empty lists, not sure if this is intended as a check for debugging but you are printing the lists before appending values to them, so they will always be empty. So I'm assuming you want to print the user's input here; if not then first append the values and then print the lists.
Use list.append(item) instead of list = list + [item]
meaning.index(search_index) should be meaning[search_index] as list.index(item) returns index value for the first occurrence of that item in the list and not the value itself.
Lastly, not very important but more of a readability issue, make sure there is a space between the word and the meaning or some kind of deliminator.
Here's the code assuming the expected behaviour:
word = []
meaning = []
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
print(user_word)
print(user_meaning)
word.append(user_word)
meaning.append(user_meaning)
print(word)
print(meaning)
user_search = input("What word/phrase would you like to search: ")
print(user_search)
search_index = word.index(user_search)
print(user_search, meaning[search_index])
.index() finds an index, not a value
Did you mean to use meaning[search_index]?
Also, to add to lists, using .append(value) is preferred over + [value]
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
word.append(user_word.strip())
meaning.append(user_meaning)
user_search = input("What word/phrase would you like to search: ")
search_index = word.index(user_search.strip())
print(user_search + " " + meaning[search_index])
If you are trying to create dictionary, instead of list you can use dictionary to store words and meaning and later use it for searching word (for learning more about dictionary, you can look into documentation).
You can try following:
my_dictionary = {} # dictionary to store word and meaning
user_word = input("Enter word: ").lower() # .lower() for not being case sensitive
user_meaning = input("Enter Meaning: ").lower() # .lower()
# add word and meaning to dictionary
my_dictionary[user_word] = user_meaning
# search word
user_search = input("What word/phrase would you like to search: ").lower()
print("Meaning of {0} is: {1}".format(user_search, my_dictionary[user_search]))

Categories