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!
Related
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.
I have a program which takes a series of strings from user input and should print "Yes" if the strings entered are in alphabetical order and "No" if not. The program ends by the user entering an empty input. I can do this when I specify the number of inputs it should have, eg 2:
finished = False
while not finished:
print("Please enter a string: ")
s = input()
x = input()
if len(s) != 0:
if s < x:
print("Yes")
else:
print("No")
else:
finished = True
However I can't seem to get my code to work when there is an indefinite amount of strings that can be entered. My current working method is to append all the strings to a list and perform the checks there, but I'm not sure exactly how to write the if statement to check this:
lst = []
i = range(len(lst))
finished = False
while not finished:
print("Please enter a string: ")
s = input()
lst.append(s)
if len(s) != 0:
if lst[i:] < lst[i: - 1]:
print("Yes")
else:
print("No")
else:
finished = True
Is there an easy way to achieve this without deviating too far from the intended structure above?
lst is a list of strings, slicing syntax on that will get you a list of strings back. But you want a string instead. Since you're appending to the list, the latest string appended will be present in the [-1] index, and the previous one will be present in [-2] index.
Change lst[i:] < lst[i: - 1] to lst[-2] < lst[-1]
There's still another problem though, in the first iteration lst[-2] does not exist, because there is only one string that has been inputted, to get rid of this - take one input and append it to the list before the loop starts-
print("Please enter a string: ")
s = input()
lst.append(s)
finished = False
while not finished:
# rest of your code
You can use the following to always compare the new item to the last item in the existing list. Therefore it always checks, if the next item is in order
new_input = input()
existing_list = ...
if sorted(existing_list[-1], new_input)[-1] == new_input
existing_list.append(new_input)
print("Yes")
else:
print("No")
That way, you don't have to enter the value to the list before checking
I have made some changes to your code. There is no need for two inputs and a master list. The code is as below.
Assumptions
Assumes that items in the list are separated by a single space
The difference between a capital case character and small case character is not important. If this is not true and ASCII ordering is important then remove ".lower()" from the third line.
while True:
print("Please enter a string: ")
s = input().lower() ## To avoid confusion between sorting ABb Abb and like strings
if not s: ## If nothing is entered break out of loop
break
SplitString = s.split(" ") ##Get elements separated by "single" space into list
SortedString = " ".join(sorted(SplitString)) ##Sort the list and then join into string
if s == SortedString: ##If the sorted and joined string is same as original then the string was already sorted when entered
print("Yes")
else: ## Else it was not sorted when entered
print("No")
The output is as below
Please enter a string:
AAA AAB ABA ABC
Yes
Please enter a string:
AAA AAB ABC ABA
No
Please enter a string:
aaa aab aba abc
Yes
Please enter a string:
aaa aab abc aba
No
Please enter a string:
f = open('num.txt','r')
temf = open('temp.txt','w')
n = f.readline()
num = input('please enter a number ')
found = False
while n != '':
if n != num:
temf.write(str(n))
else:
found = True
n = f.readline()
f.close()
temf.close()
if found:
print('found,and removed')
else:
print('no such number')
as you see the code above, my num.txt contained 0,1,2...100 and my temp.txt is empty. I've set a Boolean variable as 'found' and an if condition inside the loop as if the number is existed then its returned True. but when I put the existed number as input and its fail the if condition at the last line and always print 'no such number', I wonder why is that? I thought I already set the condition if the number is existed and set found to True? any explanation? I got new problem, it didn't deleted the number I put as input...any helps ?
The basic problem is that '123' != '123\n'. That is, a string without a newline at the end is not the same as that string with a newline a the end.
You obtain num by having the user enter a string using num = input('please enter a number '), which gets you a value like '123', which will not include a newline character.
You obtain n by calling f.readline(), which gets you a value like '123\n', because .readline() reads upto and including the newline character.
There's many ways to fix your problem, but since both values are supposed to be string representations of integer values and int() doesn't care about whitespace like a newline at the end, this may be the best fix:
if int(n) != int(num):
# etc.
However you could achieve the same with:
num = int(input('please enter a number '))
# and
n = int(f.readline())
Which has the advantage of throwing an error when it occurs, instead of later when you compare values.
Finally, if you do need to compare strings, you can get rid of the newline in various ways, like:
n = f.readline().rstrip('\n')
Your problem is that readline does not strip the line termination character \n but input does. The solution is to strip the lines being read of non-text characters on the right of the line.
f = open('num.txt','r')
temf = open('temp.txt','w')
n = f.readline()
num = input('please enter a number ')
found = False
while n != '':
print(repr(n), repr(num))
if n.rstrip() != num:
temf.write(str(n))
else:
found = True
n = f.readline()
f.close()
temf.close()
if found:
print('found,and removed')
else:
print('no such number')
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']
So the code below takes an input and makes sure the input consists of letters and not numbers. How would i make it also print orginal if the input contains a space
original = raw_input("Type the name of the application: ")
if original.isalpha() and len(original) > 0:
print original
else:
print "empty"
tried this code but worked when the input was a number too.
original = raw_input("Type the word you want to change: ")
if original.isalpha() or len(original) > 0:
print original
else:
print "empty"
It looks like that's just how string works.
Two options:
if all(x.isalpha() or x.isspace() for x in original):
(modified on inspectorG4dget's recommendation below)
or
original.replace(' ','').isalpha()
should work.