turn my for loop into a function in python - python

I would like to know how can I turn my for loop into a function.
I wrote a code which asks the user to input an address, then the code iterate through preset addresses and return me the closest address to the input one.
I would like to make it a function so I can call it in my GUI.
Here is my code:
import urllib.request
import json
# Google Maps directions API endpoint
endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'MY API KEY'
# donner l'adresse en code postal
origin = input("Inserer l'adresse du fabricant : ").replace(' ', '+')
destinations = ['H7N 5H9', 'H4N 1P9', 'K4A 0G2']
distances = []
# Parcourt la liste des adresses et calcule chacune de leurs distances
def proximity():
for i in range(len(destinations)):
currentDestination = destinations[i].replace(' ', '+')
nav_request = 'origin={}&destination={}&key={}'.format(origin, currentDestination, api_key)
request = endpoint + nav_request
response = urllib.request.urlopen(request).read()
directions = json.loads(response)
distance = directions["routes"][0]["legs"][0]["distance"]["text"]
distances.append(distance)
closestDistance = min(distances)
return closestDistance
print("the distance is: " + proximity())
print("closest address is : " + destinations[distances.index(proximity())])
EDIT :
i'm not getting the error below anymore though
I'm getting this error:
Traceback (most recent call last):
File "/Users/cn/PycharmProjects/Calendrier/venv/proximity.py", line 25, in <module>
print("the distance is: " + closestDistance)
NameError: name 'closestDistance' is not defined
What I want, is to be able to call this function in my other module.
The code works perfectly with the for loop, I just want to be able to transform it into a function.

Related

BeautifulSoup4 and Requests Module 'IndexError: list index out of range'

I'm new to web scraping with python and am having a problem with the weather web scraping script I wrote. Here is the whole code 'weather.py':
#! python3
import bs4, requests
weatherSite = requests.get('https://weather.com/en-CA/weather/today/l/eef019cb4dca2160f08eb9714e30f28e05e624bbae351ccb6a855dbc7f14f017')
weatherSoup = bs4.BeautifulSoup(weatherSite.text, 'html.parser')
weatherLoc = weatherSoup.select('.CurrentConditions--location--kyTeL')
weatherTime = weatherSoup.select('.CurrentConditions--timestamp--23dfw')
weatherTemp = weatherSoup.select('.CurrentConditions--tempValue--3a50n')
weatherCondition = weatherSoup.select('.CurrentConditions--phraseValue--2Z18W')
weatherDet = weatherSoup.select('.CurrentConditions--precipValue--3nxCj > span:nth-child(1)')
location = weatherLoc[0].text
time = weatherTime[0].text
temp = weatherTemp[0].text
condition = weatherCondition[0].text
det = weatherDet[0].text
print(location)
print(time)
print(temp + 'C')
print(condition)
print(det)
It basically parses the weather information from 'The Weather Channel' and prints it out. This code was working fine yesterday when I wrote it. But, I tried today and it is giving me the following error:
Traceback (most recent call last):
File "C:\Users\username\filesAndStuff\weather.py", line 16, in <module>
location = weatherLoc[0].text
IndexError: list index out of range
Replace:
weatherLoc = weatherSoup.select('.CurrentConditions--location--kyTeL')
# print(weatherLoc)
# []
By:
weatherLoc = weatherSoup.select('h1[class*="CurrentConditions--location--"]')
# print(weatherLoc)
# [<h1 class="CurrentConditions--location--2_osB">Hamilton, Ontario Weather</h1>]
As you can see, your suffix kYTeL is not the same for me 2_osB. You need a partial match on class attribute (class*=) (note the *)

KeyError in Weather API Response

I was making a python program which tells about weather but facing the following error
Please tell how to correct it?
CODE
import requests
import json
api = "<MY_API_KEY>"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
print("for which city?")
CITY = input("city?: ")
URL = BASE_URL + "q=" + CITY + "&appid=" + api
response = requests.get(URL)
if __name__ == "__main__":
data = response.json()
main = data['main']
temperature = main['temp']
humidity = main['humidity']
pressure = main['pressure']
report = data['weather']
print(f"{CITY:-^30}")
print(f"Temperature: {temperature}")
print(f"Humidity: {humidity}")
print(f"Pressure: {pressure}")
print(f"Weather Report: {report[0]['description']}")
TERMINAL
PS C:\Users\mamta\Documents\PythonPanti\JARVISprj> c:; cd 'c:\Users\mamta\Documents\PythonPanti\JARVISprj'; & 'C:\Users\mamta\AppData\Local\Programs\Python\Python39\python.exe' 'c:\Users\mamta\.vscode\extensions\ms-python.python-2021.5.842923320\pythonFiles\lib\python\debugpy\launcher'
'53873' '--' 'c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py'
for which city?
city?: Delhi
Traceback (most recent call last):
File "c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py", line 13, in <module>
main = data['main']
KeyError: 'main'
Your code is perfectly fine only problem here I see is when you enter any garbage value. You need to do error handling.

Python code in Zapier (invalid syntax (usercode.py, line 42))

This code is pre-made in a Zapier forum to pull failed responses from another piece of software called iAuditor. When I plug in the code and update the API token and webhook URL this error pops up:
Traceback (most recent call last):
SyntaxError: invalid syntax (usercode.py, line 42)
Here is the code:
[code]
import json
import requests
auth_header = {'Authorization': 'a4fca847d3f203bd7306ef5d1857ba67a2b3d66aa455e06fac0ad0be87b9d226'}
webhook_url = 'https://hooks.zapier.com/hooks/catch/3950922/efka9n/'
api_url = 'https://api.safetyculture.io/audits/'
audit_id = input['audit_id']
audit_doc = requests.get(api_url + audit_id, headers=auth_header).json()
failed_items = []
audit_author = audit_doc['audit_data']['authorship']['author']
conducted_on = audit_doc['audit_data']['date_completed']
conducted_on = conducted_on[:conducted_on.index('T')]
audit_title = audit_doc['template_data']['metadata']['name']
for item in audit_doc['items']:
if item.get('responses') and item['responses'].get('failed') == True:
label = item.get('label')
if label is None:
label = 'no_label'
responses = item['responses']
response_label = responses['selected'][0]['label']
notes = responses.get('text')
if notes is None:
notes = ''
failed_items.append({'label': label,
'response_label': response_label,
'conducted_on': conducted_on,
'notes': notes,
'author': audit_author
})
for item in failed_items:
r = requests.post(webhook_url, data = item)
return response.json()
[/code]
This looks like an error from the platform. It looks like Zapier uses a script called usercode.py to bootstrap launching your script and the error seems to be coming from that part.

star wars api => IndexError: list index out of range error

I am working with a star wars API from http://swapi.co/api/. I can connect to it just fine and my project is coming along fine. However, I am running into the following error message: IndexError: list index out of range error. Looking at other stack overflow questions it appears that this could be an off by one error. I am not sure how to fix it in regards to my Program. Here is the code:
url = ('http://swapi.co/api/' + str(view))
#Setting up a get request to pull the data from the URL
r = requests.get(url)
if r.status_code == 200:
print("status_code", r.status_code)
else:
print("Sorry it appears your connection failed!")
#Storing the API response in a variable
response_dict = r.json()
print("There are currently", response_dict['count'], "items to view")
repo_dicts = response_dict['results']
num = 0
while num < response_dict['count']:
if view == 'films':
repo_dict = repo_dicts[num]['title']
print(str(num) + " " + repo_dict)
elif view == 'starships':
repo_dict = repo_dicts[num]['name']
print(str(num) + " " + repo_dict)
num += 1
Now the line that is giving me the problem is in that elif view == 'starships' area. Actually if one goes to the API you can see certain categories like films, people, starships etc. All of the categories, except films, have greater than 10 things in them. I also notice that if I go to http://swapi.co/api/starships/4/ there will be no detail found. Could the fact that some of the categories have no data be causing my problem? Thank you for any insight!!
Here is the traceback error message:
Traceback (most recent call last):
File "main.py", line 102, in <module>
main()
File "main.py", line 98, in main
began()
File "main.py", line 87, in began
connect(view)
File "main.py", line 31, in connect
repo_dict = repo_dicts[num]['name']
IndexError: list index out of range
Iterate through results you have using foreach loop like this:
for item in repo_dicts:
if view == 'films':
repo_dict = item['title']
print(str(num) + " " + repo_dict)
elif view == 'starships':
repo_dict = item['name']
print(str(num) + " " + repo_dict)
Reason is because api returns 10 items in response_dict['results'] but response_dict['count'] is 37. Consult api documentation on why this happens. My guess this is possible pagination happening.

Python - NameError

I have the following code that uses 3 strings 'us dollars','euro', '02-11-2014',
and a number to calculate the exchange rate for that given date. I modified the
code to pass those arguments but I get an error when I try to call it with
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
Traceback (most recent call last):
File "currencyManager.py", line 37. in <module>
currencyManager(currTo,currFrom,currAmount,currDate)
NameError: name 'currTo' is not defined
I'm fairly new to Python so my knowledge is limited. Any help would be greatly appreciated. Thanks.
Also the version of Python I'm using is 3.4.2.
import urllib.request
import re
def currencyManager(currTo,currFrom,currAmount,currDate):
try:
currency_to = currTo #'us dollars'
currency_from = currFrom #'euro'
currency_from_amount = currAmount
on_date = currDate # Day-Month-Year
currency_from = currency_from.replace(' ', '+')
currency_to = currency_to.replace(' ', '+')
url = 'http://www.wolframalpha.com/input/?i=' + str(currency_from_amount) + '+' + str(currency_from) + '+to+' + str(currency_to) + '+on+' + str(on_date)
req = urllib.request.Request(url)
output = ''
urllib.request.urlopen(req)
page_fetch = urllib.request.urlopen(req)
output = page_fetch.read().decode('utf-8')
search = '<area shape="rect.*href="\/input\/\?i=(.*?)\+.*?&lk=1'
result = re.findall(r'' + search, output, re.S)
if len(result) > 0:
amount = float(result[0])
print(str(amount))
else:
print('No match found')
except URLError as e:
print(e)
currencyManager(currTo,currFrom,currAmount,currDate)
The command line
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
does not automatically assign "us dollars" "euro" 100 "02-11-2014" to currTo,currFrom,currAmount,currDate.
Instead the command line arguments are stored in a list, sys.argv.
You need to parse sys.argv and/or pass its values on to the call to currencyManager:
For example, change
currencyManager(currTo,currFrom,currAmount,currDate)
to
import sys
currencyManager(*sys.argv[1:5])
The first element in sys.argv is the script name. Thus sys.argv[1:5] consists of the next 4 arguments after the script name (assuming 4 arguments were entered on the command line.) You may want to check that the right number of arguments are passed on the command line and that they are of the right type. The argparse module can help you here.
The * in *sys.argv[1:5] unpacks the list sys.argv[1:5] and passes the items in the list as arguments to the function currencyManager.

Categories

Resources