This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
What is the difference between Python's list methods append and extend?
(20 answers)
Closed 3 months ago.
I am trying to create a list with user input that has at least eight items in the list. I can make the list and put in the user input, but I need to validate that there are indeed eight items, and ask for more if there are not. Then I need the list to print.
I have tried using a while statement for len(list)<8, and an if/else statement for the same. Both are asking for the additional input, but neither are printing the list at the end. I tried a nested loop with while len(list)<8 and inside is an if/else loop, but that returned the same errors as the original while statement.
>>>def main():
... userinput= input("Enter a list of at least eight words separated by a comma: ")
... list= userinput.split(",")
... while len(list)<7:
... print("Please enter more words")
... more_input= input()
... more_input.split(",")
... list.append(more_input)
... print(list)
OR
>>> def main():
... userinput= input("Enter a list of at least eight words separated by a comma: ")
... list= userinput.split(",")
... if len(list)<7:
... print("Please enter more words")
... more_input= input()
... more_input.split(",")
... list.append(more_input)
... else:
... print(list)
Errors with while loop: It just keeps asking for more input even when the list has the minimum required input
>>> main()
Enter a list of at least eight words separated by a comma: This, is, a, list
Please enter more words
More, words
Please enter more words
Three, more, words
Please enter more words
Errors with if/else loop: It only checks once. If the length is good, it prints the list. If the length is not good, it asks for more input and then stops. It neither checks the length again nor prints the list.
Your code seems ok but the problem is that you are splitting the input coming from user but this split input does not have a variable. I mean, you are still adding the non split input to the list. I edited the code which you can see below.
def main():
userinput= input("Enter a list of at least eight words separated by a comma: ")
input_list = userinput.split(",")
while len(input_list)<7:
print("Please enter more words")
more_input= input()
splitted_more_input = more_input.split(",") # problem fixed here
for i in splitted_more_input: # split creates another list
input_list.append(i) # add inputs individual
print(input_list)
Try this if you want to merge the split sub-lists in the main list :
def main():
list_= []
print("Enter a list of at least eight words separated by a comma: ")
while len(list_)<7:
print("Please enter more words")
userinput = input()
temp = userinput.split(",")
list_ += temp
print(list_)
main()
Output :
Enter a list of at least eight words separated by a comma:
Please enter more words
This, is, a, list
Please enter more words
more, words
Please enter more words
three, more, words
['This', ' is', ' a', ' list', 'more', ' words', 'three', ' more', ' words']
Note : Avoid assigning variable name as list as it's builtin keyword in python.
Since you need to repeatedly execute a function till a certain condition is met, you could take the help of recursive functions as follows
def main():
userinput= input("Enter a list of at least eight words separated by a comma: ")
words = userinput.split(",")
if len(words) == 8:
print (words)
else:
A = reenter_words(words)
print (A)
def reenter_words(words):
if len(words) == 8:
return words
else:
IN = input("More words are needed:")
new_words = words + IN.split(",")
return reenter_words(new_words)
Here I am recursively calling the reenter_words function till we get eight words from the user.
SAMPLE OUTPUT
Enter a list of at least eight words separated by a comma: qq,ww,ee,rr,tt
More words are needed:gg,hh
More words are needed:kk
['qq', 'ww', 'ee', 'rr', 'tt', 'gg', 'hh', 'kk']
Related
I am trying to find a way to get input from the user which is a list of numbers and words. Then I want to print out only the numbers from that list. I can't figure out how to separate them, and then only print out the numbers. I think that the answer might be through exporting the items in the list that are numbers to a dictionary and then printing said dictionary, but I don't know how to do that. Here is the code that I have already:
string1=input("Please input a set of positive numbers and words separated by a space: ")
string2=string1.split(" ")
string3=[string2]
dicts={}
for i in string3:
if isinstance(i, int):
dicts[i]=string3[i]
print(dicts)
You just need to split the words into a list, then print the words in the list based on whether the characters in each word are all digits or not (using str.isdigit):
string1 = input("Please input a set of positive numbers and words separated by a space: ")
# split into words
words = string1.split(' ')
# filter words and print
for word in words:
if word.isdigit():
print(word)
For an input of abd 13 453 dsf a31 5b 42 ax12yz, this will print:
13
453
42
Alternatively you could filter the list of words (e.g. using a list comprehension) and print that:
numbers = [word for word in words if word.isdigit()]
print(numbers)
Output for the above sample data would be:
['13', '453', '42']
Here is a slight variation of #Nick 's answer that uses list comprehension, separating the input into a list that contains only the numbers.
string1 = input("Please input a set of positive numbers and words separated by a space: ")
numbers = [x for x in string1.split(" ") if x.isdigit()]
print(numbers)
So I was struggling with a question on how to ask for looped inputs. So when the user enters say 5 then the program will ask the user to enter the data 5 separate times. As I was looking through I found a program that solved that and I've tweaked it to suit my question and this is what I've gotten so far:
def doSomething():
x = int(input ("Enter how many words?\n"))
for count in range (x):
word1 = input ("Enter word1:\n")
doSomething()
This part of the program solves my initial problem of asking the user for their input as many times as they have stated, but my problem is how do I change the program so that when the user enters for x = 5 the then the program will ask the user to input Enter Word 1 and after the user enters the word the program asks for word 2 Enter Word 2 and so on until its asks for the amount of words the user asked for. So to be direct how do I change Enter Word 1 to Enter Word 2 and Enter Word 3 as the program loops the amount of times chosen by the user.
You can just get the number printed each time:
def doSomething():
x = int(input ("Enter how many words?\n"))
for count in range (x):
word1 = input (f"Enter word{count+1}:\n")
btw You need python 3.6 or higher for this.
You can use the formatting of strings or concatenation.
In the loop where you ask for input you can do any of the following
input("Enter word " + (count+1) + ":\n") - Using string concatenation
input("Enter word {0}:\n".format(count+1)) - Using .format() strings
input(f"Enter word {count+1}:\n") - Utilizing f-strings.
FYI, I'm adding 1 to each count because the range function starts from 0 and ends at n-1. Adding one will allow a range from 1 through n.
You should look up concatenation. Along with that take a look at f strings. These are very efficient ways of concatination
for count in range(1,x+1):
word1 = input (f"Enter word{count}:\n")
We can use an f string to achieve the required formatting.
def doSomething():
x = int(input ("Enter how many words?\n"))
for count in range (1, x+1): # count starts from 1 and goes till x
word = input (f"Enter word{count}:\n")
You can use a loop like this. Also, make sure to check that the first number the user inputs is actually a number.
while True:
try:
number_of_words = int(input('Enter the number of words: '))
break
except ValueError:
print('You must enter a number')
words = []
for word in range(number_of_words):
words.append(input(f'Enter word {word + 1}: '))
print(words)
You should use a list variable rather than five variables with separate names.
word = []
for count in range (x):
word[count] = input (f"Enter word[{count}]: ")
Now, word will contain someting like
['first', 'second', 'third', 'fourth', 'fifth']
Notice that the index is zero-based, so the first string 'first' is word[0] and 'second' is word[1]. You could loop over range(1, x+1) but you probably should not; to mask the "computer" numbering from the user, you can display count+1 to the user.
The design to require the user to decide ahead of time how much input to provide is unnecessary and rather cumbersome; a better design is to let them provide input into an ever-growing list until they separately indicate that they want to stop, by providing an empty input, or in a GUI by clicking a separate button.
Write a program allows user to input a string. End the program is printing out:
a. How many words that repeated itself.
For example: 'This is Jake and Jake is 24 years old'
The console must print out '4' because 'is' and 'Jake' are the word that repeated
b. Remove all the repeated word. Print out the rest: 'This and 24 years old'
c. Print out which repeated words have been removed
So the idea is the user can type whatever they want, 'This is Jake and Jake is 24 years old' is just an example. The hardest part is how can console check all the repeated words without a substring?
Does this work?
Here is what I am doing.
First I grab the user input, then I convert the string to a list splitting on spaces between words. Then I count the occurence of the words, if the wordcount is greater than 1, I add it to a dictionary , where the key is the word and the value is the count of the words that exist in the string.
After printing out the repeated words, I remove the strings that find a mention in the dictionary.
Note - This code can be improved so much but I purposely did it such a manner to make it easier to understand. You should not be using this code if its a production system.
string = input("Enter your string : ")
items = {}
words = string.split(" ")
for word in words:
wordCount = words.count(word)
if(wordCount > 1):
items[word] = wordCount
print("There are {0} repeated words".format(len(items)))
updateString = ""
for item in items:
updateString =string.replace(item,"")
print(updateString)
print(items)
Updated
string = input("Enter your string : ")
items = {}
words = string.split(" ")
for word in words:
wordCount = words.count(word)
if(wordCount > 1):
items[word] = wordCount
print("There are {0} repeated words".format(len(items)))
for item in items:
string = string.replace(" {0} ".format(item)," ")
print(string)
print(items)
I want users to enter random words/numbers/phrases. If they have entered more then 5 then they get an error message and if the enter 5 or less then I print out the list vertically. I don't know what code to use so that it does not count the white spaces. As well, I want to count the number of words/numbers, NOT the amount of characters. If you could just take a look at my code and give some help, that would be great!
myList = []
myList = raw_input("Enter words,numbers or a phrase (a phrase should be entered between two quotations)...")
if len(myList) > 5:
print('Error')
else:
#print output
for variable in L:
print variable
Try something like this using str.split() to return a list of the words in the string using the default delimiter of a space character:
myList = []
while(True):
myList = raw_input("Please enter words or numbers: ")
if(len(myList.split())) <= 5:
break
else:
print("Error: You entered more than 5 arguments, Try again...")
for item in myList.split():
print(item)
Try it here!
The working code for what you want is the following:
# I separate the input text by the spaces
data = raw_input("Enter something... ").split(" ")
# handle the data
if len(data) > 5:
print("Only 4 or less arguments allowed!")
else:
for variable in data:
print(variable)
Now, this doesn't prevent the user from inserting other characters like !, $%"#$, so to handle that case, you should check for some of the answers in this question: Stripping everything but alphanumeric chars from a string in Python
Have fun!
I'm working a question where I need to create a program that will ask the user to input a list and then it will print off the strings that start with letters A-I.
Question: Implement a program that asks for a list of student names from
the user and prints those names that start with letters A through I.
Create two test lists.
>>> phrase = input('Enter a list of Students: ')
Enter a list of Students: ['Albert', 'Ian', 'Bob', 'Dave', 'Edward']:
>>> for c in phrase:
if c in 'abcdefghiABCDEFGHI':
print(c)
Right now the print function results in:
A
b
e
I
a
B
b
D
a
e
E
d
a
d
It prints off letters in each of the name in alphabetical order, but what I want it do do is print off the entire names in alphabetical order. Once I can do it for one list, a 2nd list shouldn't be an issue.
To only print out the names that start with those letters you just need to index the first character c[0], e.g.:
phrase = input("Enter list of students")
for name in phrase:
if name[0] in 'ABCDEFGHI':
print(name)
Just be aware input() is generally considered unsafe because arbitrary code can be executed. A safer, but probably unnecessary at this level, approach would be:
import ast
phrase = ast.literal_eval(raw_input("Enter list of students"))
for name in phrase:
if name[0] in 'ABCDEFGHI':
print(name)
See my comment above, the phrase is a string when you input it. You have yet to make it into a list.
Try:
phrase = eval(input("Enter list of students")) #this evaluates the list put in
for names in phrase:
for letters in names:
if letters in 'abcdefghiABCDEFGHI':
print(names)
Next up
phrase = eval(input("Enter list of students"))
i = 0
while i < len(phrase): #for each item in phrase up to the end!
for letters in phrase[i]
if letters in 'abcdefghiABCDEFGHI':
print phrase[i]
phrase.pop(i)
i-=1 #set i backwards (as the incrementer downstairs will set it back to normal"
break #get out of this loop only one print please
i+=1 #fast way to increment