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())
Related
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
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))
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
So I am trying to use the re module to see if a number plate matches with how a number plate should be, but I keep getting errors with the module, my code is below.
def nplatec():
import re
r_plate = "^[Aa-Zz]{2}[0-9][Aa-Zz]{3}$"
while True:
u_plate = input("Enter your number plate WITHOUT spaces please : ")
a_speed = int(input("Enter you average speed : "))
s_limit = 70
if re.match(r_plate, u_plate):
print("InCorrect number plate")
break
nplatec()
Errors:
I found the answer, its meant to be "^[A-Za-z]{2}[0-9][A-Za-z]{3}$" rather than "^[Aa-Zz]{2}[0-9][Aa-Zz]{3}$"
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