如何将用户输入的zipCode以字符串形式传入API请求?
问题分析与修复方案
你的代码存在几个关键问题,导致无法将用户输入的邮编正确传入API请求:
user_input函数里错误地把zipCode_format赋值为字符串"zipCode",而非用户实际输入的内容;同时你对全局变量的使用方式有误,导致函数内外的变量互不关联。input()函数本身返回的就是字符串类型,你完全没必要额外声明变量来做格式转换。- 调用
user_input()后没有保存返回值,weather_report根本拿不到用户输入的邮编。
修正后的代码
import requests def get_user_zipcode(): # input()返回的直接是字符串,无需额外转换 return input('What is your zipcode? Zipcode: ') def weather_report(zip_code): params = { 'access_key': 'your_api_key_here', # 替换为你的实际API密钥 'query': zip_code, # 直接传入用户输入的字符串邮编 'units': 'f' } api_result = requests.get('http://api.weatherstack.com/current', params) api_response = api_result.json() # 增加简单错误处理,避免API返回异常时程序崩溃 if 'location' in api_response and 'current' in api_response: print(f'Current temperature in {api_response["location"]["name"]} is {api_response["current"]["temperature"]} degrees Fahrenheit.') else: print('获取天气数据失败,请检查邮编或API密钥是否正确。') # 获取用户输入的邮编 user_zip = get_user_zipcode() # 传入天气查询函数 weather_report(user_zip)
关键说明
- 直接使用
input()获取用户输入即可,它返回的字符串完全符合API对query参数的格式要求,无需额外格式化。 - 用函数传参替代全局变量,代码逻辑更清晰,也避免了全局变量带来的作用域混乱问题。
- 新增的错误判断能在API返回异常数据时给出提示,避免程序直接崩溃。
内容的提问来源于stack exchange,提问作者Candace
相关产品推荐
相关产品推荐

