View Single Post
Trådstarter
131
Sitat av snippsat Vis innlegg
Nei,dette ble litt feil
Det og bruke funksjoner kan gjøre koden mer lesbar og lettere og teste,men da må man strukturere koden i flere funksjoner.
En funksjon skal helst ikke gjøre flere ting,men gjerne en oppgave godt for så returnere resultert ut.

Kan skiver om koden for og vise hva jeg mener.
Skriver også om som nevnt så man slipper like gjentagelse i print() funksjon.
Faller alltid tilbake til menu(),hvor man kjøre om igjen eller Quit.
Da slipper man også flere while true loop i koden.

Bruker også f-string,som var nytt i Python 3.6.
f-string kan gjør at print() ser mye berede ut.

Kode

>>> city = 'Oslo'
>>> latitude = 40.5
>>> longitude = 60.5
>>> print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
Latitude and longitude for Oslo is: 40.5 60.5
>>> 
>>> # With f-string
>>> print(f"Latitude and longitude for {city} is: {latitude} {longitude}")
Latitude and longitude for Oslo is: 40.5 60.5

>>> for word in 'f-strings are awesome'.split():
...     print(f'{word.upper():~^20}')
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~AWESOME~~~~~~~
Rewrite.

Kode

import datetime
import requests

def user_input():
    name_of_user = input("What is your name?: ")
    city = input('City Name: ')
    return name_of_user, city

def api_usage(city):
    api_address = f'http://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q={city}'
    json_data = requests.get(api_address).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']
    return day_of_month, month, year, degrees, time, humidity, latitude, longitude

def print_weather_info(api_info,name_of_user,city):
    day_of_month, month, year, degrees, time, humidity, latitude, longitude = api_info
    print(f"\nGood afternoon {name_of_user}.")
    print(f"\nThe date today is: {day_of_month} {month} {year}")
    print(f"The current time is: {time}")
    print(f"The humidity is: {humidity} %")
    print(f"Latitude and longitude for {city} is: {latitude} {longitude}")

def prog_logic(api_info,name_of_user,city):
    degrees = api_info[3]
    time = api_info[4]
    if degrees < 20 and time > '12.00':
        print_weather_info(api_info,name_of_user,city)
        print(f"The temperature is a mild {degrees:.1f} °C,you might need a jacket.\n")
    elif degrees < 20 and time < '12.00':
        print_weather_info(api_info,name_of_user,city)
        print(f"The temperature is a mild {degrees:.1f} °C,you might need a jacket.\n")
    elif degrees >= 20 and time > '12.00':
        print_weather_info(api_info,name_of_user,city)
        print(f"The temperature is a warm {degrees:.1f} °C,don't forget to drink water.\n")
    elif degrees >= 20 and time < '12.00':
        print_weather_info(api_info,name_of_user,city)
        print(f"The temperature is a warm {degrees:.1f} °C,don't forget to drink water.\n")

def menu():
   while True:
       print('(1) Check weather')
       print('(Q) Quit')
       choice = input('Enter your choice: ').lower()
       if choice == '1':
           name_of_user, city = user_input()
           api_info = api_usage(city)
           prog_logic(api_info, name_of_user, city)
       elif choice == 'q':
           return False
       else:
           print(f'Not a correct choice: {choice},try again\n')

if __name__ == '__main__':
   menu()
Test,kan kjøre dette @hvagjordo fordi du deler din private API nøkkel

Kode

E:\div_code
λ python temp_rewrite.py
(1) Check weather
(Q) Quit
Enter your choice: 99
Not a correct choice: 99,try again

(1) Check weather
(Q) Quit
Enter your choice: 1
What is your name?: Tom
City Name: Oslo

Good afternoon Tom.

The date today is: 02  May  2019
The current time is: 16:06:29
The humidity is: 30 %
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 8.5 °C,you might need a jacket.

(1) Check weather
(Q) Quit
Enter your choice: affas
Not a correct choice: affas,try again

(1) Check weather
(Q) Quit
Enter your choice: 1
What is your name?: Kent
City Name: Bangkok

Good afternoon Kent.

The date today is: 02  May  2019
The current time is: 16:06:52
The humidity is: 59 %
Latitude and longitude for Bangkok is: 100.49 13.75
The temperature is a warm 33.3 °C,don't forget to drink water.

(1) Check weather
(Q) Quit
Enter your choice: Q

E:\div_code
Vis hele sitatet...
Damn, fikk slanka koden med halvparten så lite linjer. Ser hva jeg har gjort "galt" ja