How to match exact user input - python

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

Related

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)

Python & API user input

My code is
import requests
from pprint import pprint
from pip._vendor.distlib.compat import raw_input
recipe_ingredients = input("What is the recipe ingredients? ")
number_recipes = input("How many recipes do you want? ")
url = 'https://api.spoonacular.com/recipes/findByIngredients?ingredients={}&number={}&'.format(recipe_ingredients,number_recipes)
response = requests.get(url)
print(response)
However, when I am inputting more than one ingredient in the format of (two ingredients) cheese and potato it is returning results for either the first variable or tells me there is a syntax error with and.
Is there any way I am able to program my search function to accept and ,whereby it can display all the results for both words, as it is likely a user will put 'and' within their search for more than one ingredient.
( I am using pycharm btw)
You are only requesting one string from the user. Whenever you try to enter 2 strings separated by Enter, the second string cannot be saved and thus the exception.
You may fix it like:
n = int(input("Number of ingredients: "))
recipe_ingredients = []
print("Enter " + str(n) + " recipe ingredients")
for i in range(n):
recipe_ingredients.append(input())

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

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

Python - Searching for a value in CSV column and return string

I am very new to Python and am working on a simple project that part of which is supposed to search for a user defined variable, and if found, return a string based on the row it was found.
I've read many posts that lead me to the code that I have, but when ran, while I don't get an error, the code continues onto the next part. In this case I omitted the following parts, but if run by itself, breaks after the input variable.
import csv #CSV File Handling
#Define variables for customer file reading and appending
custData = open('custData.csv', 'a+')
custFields = ['ContactLast','ContactFirst','Company','Credit','Phone','Address','City','State','Zip']
reader = csv.DictReader(custData, delimiter=',')
writer = csv.DictWriter(custData, fieldnames=custFields)
search = ''
#Open the file
with custData:
#Display the Welcome Message and Main Menu
mainmenugo = 'Y'
while (mainmenugo.upper() == 'Y'):
print ('-------------------- What would you like to do? ------------------\n'
'--- (1) Lookup Account (2) New Account (quit) Shutdown ---\n'
'------------------------------------------------------------------')
mainmenugo = 'n' #Stop the loop from itirating forever on start
mainmenuselect = input('Type your selection and press return : ')
if mainmenuselect == '1': ## Account Options Mode
search = input('Enter the contact last name to search : ')
for row in reader:
if search == row['ContactLast']:
print (row['Company'], 'has a balance of $', row['Credit'], '. What would you like to do?')
Part of the code was omitted for clarity, but that is why I have it setup as it is, though I am sure there are simpler ways of going about it. I have tried a few different things but am really not sure where to begin as I am getting very few errors with this one but no output. Thanks!
I think you are experiencing the following problem. input() in Python 3 would evaluate the user input effectively converting a user input 1 to an integer 1 which then you are trying to compare with a string '1'.
In other words, here is what is happening:
In [1]: search = input('Enter the contact last name to search : ')
Enter the contact last name to search : 1
In [2]: type(search)
Out[2]: int
In [3]: search == '1'
Out[3]: False
In your case, if the user types 1, the if mainmenuselect == '1': comparison would be falsy.

How to receive a list of unknown length of strings

I'd like to receive a list of user aliases for the purpose of looking up an email. As of now, I can do this for only 1 input with the following code:
def Lookup(Dict_list):
user_alias = raw_input("Please enter User Alias: ")
data = []
for row in Dict_list:
#print "row test"
#print row
if user_alias in row.values():
print row
for row in Dict_list:
if user_alias == row['_cn6ca']:
email = row['_chk2m']
print email
return email
But I want to be able to have the user enter in an unknown amount of these aliases (probably no more than 10) and store the resulting emails that are looked up in a way that will allow for their placement in a .csv
I was thinking I could have the user enter a list [PaulW, RandomQ, SaraHu, etc...] or have the user enter all aliases until done, in which case they enter 'Done'
How can I alter this code (I'm guessing the raw_data command) to accomplish this?
This will accept input until it reaches an empty line (or whatever sentinel you define).
#! /usr/bin/python2.7
print 'Please enter one alias per line. Leave blank when finished.'
aliases = [alias for alias in iter (raw_input, '') ]
print (aliases)
You can ask the user to enter a list of aliases, separated by spaces, and then split the string:
In [15]: user_aliases = raw_input("Please enter User Aliases: ")
Please enter User Aliases: John Marry Harry
In [16]: for alias in user_aliases.split(): print alias
John
Marry
Harry
In [17]:
In case the user aliases can have spaces in them, ask them to use, say, a comma as a separator and split by that: user_aliases.split(',')

Categories

Resources