Нужна помощь, чтобы сделать пока цикл перезапустить мою программу Python сверху - PullRequest
0 голосов
/ 01 мая 2019

Я хотел бы получить помощь по этой программе, которую я сделал. Функция кода заключается в том, что пользователи могут вводить город в любой точке мира, а затем получать данные о погоде для этого города.

Я хочу, чтобы он перезапустил программу сверху, но он только перезапускает программу с того места, где есть результаты.

# - Weather Program -

#Import
import datetime
import requests
import sys

#Input
name_of_user = input("What is your name?: ")
city = input('City Name: ')

#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
url = api_address + city
json_data = requests.get(url).json()

#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']

#Loop
while True:

    #Program
    if degrees < 20 and time > str(12.00):
        print("\nGood afternoon " + name_of_user + ".")
        print("\nThe date today is: " +
              day_of_month +
              month +
              year)
        print("The current time is: " + time)
        print("The humidity is: " + str(humidity) + '%')
        print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
        print("The temperature is a mild " + "{:.1f}".format(degrees) +
              "°C, you might need a jacket.")

    elif degrees < 20 and time < str(12.00):
        print("\nGood morning " + name_of_user + ".")
        print("\nThe date today is: " +
              day_of_month +
              month +
              year)
        print("The current time is: " + time)
        print("The humidity is: " + str(humidity) + '%')
        print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
        print("The temperature is a mild " + "{:.1f}".format(degrees) +
              "°C, you might need a jacket.")

    elif degrees >= 20 and time > str(12.00):
        print("\nGood afternoon " + name_of_user + ".")
        print("\nThe date today is: " +
              day_of_month +
              month +
              year)
        print("The current time is: " + time)
        print("The humidity is: " + str(humidity) + '%')
        print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
        print("The temperature is a warm " + "{:.1f}".format(degrees) +
              "°C, don't forget to drink water.")

    elif degrees >= 20 and time < str(12.00):
        print("\nGood morning " + name_of_user + ".")
        print("\nThe date today is: " +
              day_of_month +
              month +
              year)
        print("The current time is: " + time)
        print("The humidity is: " + str(humidity) + '%')
        print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
        print("The temperature is a warm " + "{:.1f}".format(degrees) +
              "°C, don't forget to drink water.")

    #Loop
    restart = input('Would you like to check another city (y/n)?: ')
    if restart == 'y':
        continue
    else:
        print('Goodbye')
        sys.exit()

Так вот что происходит .. Цикл только зацикливает вопрос с уже введенными данными и данными.

What is your name?: Test
City Name: Oslo

Good afternoon Test.

The date today is: 01 May 2019 
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: y

Good afternoon Test.

The date today is: 01 May 2019 
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: n
Goodbye

Process finished with exit code 0

Я хочу, чтобы код зацикливался сверху, чтобы я мог нажать y, чтобы программа попросила ввести другой город.

Ответы [ 4 ]

0 голосов
/ 01 мая 2019

Все, что вам нужно, это поместить секцию ввода и секции API в ваш цикл while true.

Скажу, я не смог на самом деле протестировать свое решение, но я почти полностью уверен, что оно будет работать. Удачи!

0 голосов
/ 01 мая 2019

Вы никогда не обновляете свои значения.Давайте возьмем более простой пример:

x = int(input("What is the number you choose? "))

while True:
    if x >3:
        print(x)
        continue
    else:
        break

Если я запущу это, я напечатаю x навсегда, если я выберу, скажем 5.Код, определяющий x, никогда не будет перезапущен, потому что он находится вне цикла.Чтобы это исправить, я могу переместить свой код для x в цикл while:

while True:
    x = int(input("What number do you choose? "))
    if x>3:
        print(x)
    else:
        break

Это будет запускать код для x каждый раз, когда выполняется цикл, поэтому x теперь можетменять.Применение этого к вашему коду:

# loop is now up near the top
while True:
    # You want these values to change on each iteration of the while
    # loop, so they must be contained within the loop
    name_of_user = input("What is your name?: ")
    city = input('City Name: ')

    #API
    api_address='http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
    url = api_address + city
    json_data = requests.get(url).json()

    #Variables
    format_add = json_data['main']['temp']
    day_of_month = str(datetime.date.today().strftime("%d "))
    month = datetime.date.today().strftime("%b ")
    year = str(datetime.date.today().strftime("%Y "))
    time = str(datetime.datetime.now().strftime("%H:%M:%S"))
    degrees = format_add - 273.15
    humidity = json_data['main']['humidity']
    latitude = json_data['coord']['lon']
    longitude = json_data['coord']['lat']

    if degrees... # rest of your statements

Теперь значение для City может измениться, и вы можете применить это к другим структурам данных

0 голосов
/ 01 мая 2019

Цикл while охватывает только код, отображающий результаты, код, который принимает данные и запрашивает результаты, выполняется только один раз. В цикле while должно быть все, кроме операторов import

0 голосов
/ 01 мая 2019

Поместите цикл while, начиная с первого входа. Не забудьте объявить ваши постоянные переменные над основным циклом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...