How to read input line by line, instead of by spacing - python

I'm trying to read a large number of user inputs line by line instead of by spacing.
code:
keyword = (input("\n Please enter the keywords "))
keywords = keyword.split(" ")
words:
a
abandon
ability
able
abortion

The input function ends by pressing enter or moving to a new line, so you have to define how you want to finish instead.
If you're looking for a way to enter 5 words like you did in your example, this should be enough:
print("\n Please enter the keywords ")
keywords = [input() for i in range(5)]
You can change range(5) to range(3000) or any other number that you wish.
If you would like in input an infinite amount of words until some special keyword is entered (like "quit") you can do this:
print("\n Please enter the keywords ")
keywords = []
while True:
k = input()
if k == 'quit':
break
else:
keywords.append(k)

You may want to read from the sys.stdin, for example:
import sys
it = iter(sys.stdin)
while True:
print(next(it))
Here you have a live example

Related

How to create a txt file with a user inputted name in python?

I have attached part of some python code that is designed to make 'decisions' based on user inputs. I currently cannot work out how to make the text file at the end (shown in the asterisks) have a name that is inputted by the user.
Also, sorry if this is worded confusingly- I am quite new to coding.
import csv
times = 1
Ops = []
print()
genre = input("Genre: ")
num = input("How many " + str(genre) + "s do I have to choose from? ")
**text_file= open(genre.txt, "w+")**
while int(times) <= int(num):
option = input("Option " + str(times) + ": ")
Ops.append(option)
text_file.write(option)
times = times + 1
print()
How would go about doing this???
After reading your code and attempting to understand it -- I think I know what you are trying to do, so here is my attempt and suggestions.
Remove "import csv" (not necessary), maybe later, not now.
It looks like you are creating a file based on the input into the variable "genre", so in the open statement should be: open(genre+".txt", "w+")
Instead of asking how many different options you will be inputting and writing to the file, let that be dynamic, and provide a end-of-input designation that will stop accepting options and write everything to the file.
Suggested code:
options = list()
genre = input("Genre: ")
option = ""
count = 1
while option != "done":
option = input("Option "+str(count)+": ")
if option != "done":
options.append(option)
count += 1
with open(genre+'.txt', 'w+') as text_file:
text_file.write("\n".join(options))
Explanations:
If using Python2, use raw_input() instead of input().
The while statement will continue to loop, accepting "options", and incrementing counter until you specify "done" by itself, which will not be included in the list of options, and the loop will end.
The "with" statement, tells python to execute everything indented under it with the context of the open file "text_file".
The ".join()" statement is an list operator that joins each element in the list with a "\n" which means "newline". So with a list of ["rock", "classical", "pop"] it would write: "rock\nclassical\npop\n" which when written to the file it will look like:
rock
classical
pop

The program repeats until the input string is quit and disregards the integer input that follows

Write a program that takes a string and an integer as input, and outputs a sentence using the input values as shown in the example below. The program repeats until the input string is quit and disregards the integer input that follows.
Ex: If the input is:
apples 5
shoes 2
quit 0
the output is:
Eating 5 apples a day keeps the doctor away.
Eating 2 shoes a day keeps the doctor away.
This is what I've got so far:
string = input().split()
string2 = input().split()
string3 = input().split()
all_input = (string + string2 + string3)
for word in all_input:
while word != 'quit':
print('Eating {} {} a day keeps the doctor away.'.format(string[1] , string[0]))
print('Eating {} {} a day keeps the doctor away.'.format(string2[1], string2[0]))
string = input().split()
string2 = input().split()
string3 = input().split()
all_input = (string + string2 + string3)
I get the correct output but also receive this error:
Traceback (most recent call last):
File "main.py", line 11, in <module>
string = input().split()
EOFError: EOF when reading a line
And when it tests with the inputs:
cars 99
quit 0
Then I get no output. I feel like I need to use a break statement somewhere but nowhere I put it seems to work.
you are using input() multiple times where you can use it once inside a loop and if the input_string contains 'quit' it will be terminated. try the following code, it will continue taking input till the user enters quit
while True:
input_string = input()
if 'quit' in input_string:
break
else:
a,b = input_string.split(' ')
print(f'Eating {b} {a} a day keeps the doctor away.')
OR
if you want to take all inputs at once, then find the code below, it will work as you expected
input_string = []
while True:
line = input()
if 'quit' in line:
break
else:
input_string.append(line)
for line in input_string:
a,b = line.split(' ')
print(f'Eating {b} {a} a day keeps the doctor away.')
You can use a loop to achieve the same result, and you can use it too for files with more and less lines.
You can use 'quit' not in variable_name as the exit condition of the loop. When the variable you test is a substing, this statement will look for "quit" as a substring.
To split the words in the lines str.split() is your friend. After calling it, it returns an array. The first element of this array will be the object, and the second the number of elements.
mad_lib = input()
while 'quit' not in mad_lib:
MD_list = mad_lib.split()
thing = MD_list[0]
integer = MD_list[1]
print("Eating {} {} a day keeps the doctor away.".format(integer,thing))
# Read the input again to process more lines
mad_lib = input()
The main roadblock may be splitting the input first, as others noted. Additionally, do not think of this exercise as there will be a set number of strings. Strings can be 0 to infinity -- that will be left to the user (or computer) to decide. Once you str.split() and loop input before the loop and in the loop, you can KISS (keep it simple stupid) with a not in rather than using breaks. Sure, the breaks look as if you paid attention during your lessons in the chapter, though so far I have found breaks to be only needed under select circumstances (if at all?). If your instructor does not have requirements on what you need to use in your program, use the following (also seen in #Jamal McDaniel / #Iñigo González above).
user_input = input() #initial input
while 'quit' not in user_input:
choices = user_input.split() #split the string
word = choices[0]
integer = choices[1]
print("Eating {} {} a day keeps the doctor away.".format(integer, word))
user_input = input() #get another input and loop until 'quit'
I solved the problem using this code.
var1 = input() #takes in string(apples 5)
mad_lib = var1.split() #splits user input into two strings (apples, 5)
while 'quit' not in mad_lib: #loop that only stops when 'quit' is entered
print('Eating {} {} a day keeps the doctor away.'.format(mad_lib[1], mad_lib[0]))
var1 = input() #increments loop with new input(shoes 2)
mad_lib = var1.split() #splits new user input into two strings again (shoes, 2)

How do I reset to the beginning of the code after it runs? [duplicate]

This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
After the code runs all the way for the first time, I want it to be able to go back to the first input and allow the user to input another word.
Do I need to create a for or while loop around the program?
import re
import requests
search = input('What word are you looking for?: ')
first = re.compile(search)
source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text
mo = first.findall(ar)
print (mo)
print('Frequency:', len(mo))
Yes, a loop is needed:
import re
import requests
while True:
search = input('What word are you looking for?: ')
# per comment, adding a conditional stop point.
if search == "stop":
break
first = re.compile(search)
source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text
mo = first.findall(ar)
print (mo)
print('Frequency:', len(mo))
Yep a while look is the way to go.
Make sure you don't have an infinite loop though. (You want some way to break out...
I would recommend just adding this to the search, so if they type exit it breaks out of the look. I have also added .lower() so Exit, EXIT, etc also work.
import re
import requests
while True:
search = input('What word are you looking for?: ')
if search.lower() == "exit": #break out of the loop if they type 'exit'
break
first = re.compile(search)
source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text
mo = first.findall(ar)
print (mo)
print('Frequency:', len(mo))

How do you add users multiple inputs to a list?

In terms of using this:
names = [] # Here we define an empty list.
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(eingabe)
How do you use it for multiple inputs?
Try this:
names = [] # Here we define an empty list.
flag = True
while flag:
eingabe = input('Please enter a name: ')
if not eingabe:
flag=False
names.append(eingabe)
print(eingabe)
So, until the flag not became False this while loop run continuously.
and if user does not entered any input value than it set the flag value False and loop will terminate.
If all you want is to convert multiple user inputs to a list, this will be the easiest way:
names = input('Please enter names (separated by space): ').split()
According to your question and given code above , it already takes multiple input from user but it seems that you are not printing them. If you want to get multiple input from user and add them to a empty list and print them out , then you've to change a bit more of your code.
names = []
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(names)
or you can do this simply just using split() method -
names = input('Enter name like : "apple microsoft facebook ...": ').split()
print(names)
Please let me know whether it is or not.

How to match exact user input

I have below code in test.py file:
#!/usr/bin/python
import sys,re
def disfun():
a = str(raw_input('Enter your choice [PRIMARY|SECONDARY]: ')).upper().strip()
p = re.compile(r'\s.+a+.\s')
result = p.findall("+a+")
print result
disfun()
When I run this code, it gives a prompt for Enter your choice and if I give my choice as PRIMARY. I am getting only blank output:
[oracle#localhost oracle]$ ./test.py
Enter your choice [PRIMARY|SECONDARY]: PRIMARY
[]
Here I want to get the same output as I given in user input. Please help me on this.
Not sure what your goal is but I think you mean this?? Mind the quotes, 'a' is your user input. If you write "+a+" it will be literaly the string '+a+'
def disfun():
a = str(raw_input('Enter your choice [PRIMARY|SECONDARY]: ')).upper().strip()
p = re.compile(r'.*'+a+'.*') <-- this will match anything containing your user input
result = p.findall(a)
print result

Categories

Resources