Du må være registrert og logget inn for å kunne legge ut innlegg på freak.no
X
LOGG INN
... eller du kan registrere deg nå
Dette nettstedet er avhengig av annonseinntekter for å holde driften og videre utvikling igang. Vi liker ikke reklame heller, men alternativene er ikke mange. Vær snill å vurder å slå av annonseblokkering, eller å abonnere på en reklamefri utgave av nettstedet.
  23 3482
Hei, er enda noob i python, vel koding generelt, starta for litt over 1 uke sia, men uansett. Skulle hatt hjelp til og loope et program til starten av programmet via input fra brukeren. y = restart, n = quit

Koden er:

Kode

# - Good Morning Program -

#Import
import datetime
import requests

#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')
        break

Det som skjer er:

Trykker y:

What is your name?: Hvagjordo
City Name: Oslo

Good afternoon Hvagjordo.

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

(Da looper den selve spørsmålet med svaret fra før, men ikke helt fra starten)

Trykker n

Good afternoon Hvagjordo.

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

Process finished with exit code 0




Så, n funker, men y looper ikke heeeeelt fra starten, men looper med all infoen og spør om man vil loope på nytt. Vil at den skal loope så jeg kan spørre om en annen by

Har googla, men ikke funnet frem til noe som fungerer
Put enda en while True: løkke rundt hele programmet ditt, og legg inn break under y, og raise SystemExit under n, så skal det nok fungere
Sist endret av Sinken; 1. mai 2019 kl. 15:30. Grunn: Automatisk sammenslåing med etterfølgende innlegg.
Tenkte du sånn her?:

Kode

#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
while True:
    restart = input('Would you like to check another city (y/n) ?: ')
    if restart == 'y':
        break
    else:
        print('Goodbye')
        SystemExit

Prøvde den vertfall, når jeg starter scriptet så looper den dette uendelig:

The temperature is a mild 16.5°C, you might need a jacket.

Good afternoon o.

The date today is: 01 May 2019
The current time is: 15:31:21
The humidity is: 42%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 16.5°C, you might need a jacket.


Skrev jeg noe feil? Takk

Kode

import sys #settes sammen med dine øvrige imports
sys.exit() # settes hvor du vil avslutte programmet
Ja, enten som Myxo skriver, eller:

Kode

else:
     print('Goodbye')
     Raise SystemExit
på bunnen. Du må som sagt huske å wrappe hele koden (altså, fra under importene) i en while True: løkke
Sist endret av Sinken; 1. mai 2019 kl. 18:17.
Sitat av Myoxocephalus Vis innlegg

Kode

import sys #settes sammen med dine øvrige imports
sys.exit() # settes hvor du vil avslutte programmet
Vis hele sitatet...

Sånn som det her ikke sant?

Kode

# - Good Morning 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
while True:
    restart = input('Would you like to check another city (y/n) ?: ')
    if restart == 'y':
        break
    else:
        print('Goodbye')
        sys.exit()
Da får jeg dette som looper i det uendelige uten at jeg trykker y eller n fremdeles :


What is your name?: Hvagjordo
City Name: Oslo

Good afternoon Hvagjordo.

The date today is: 01 May 2019
The current time is: 17:13:16
The humidity is: 47%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 15.9°C, you might need a jacket.

Good afternoon Hvagjordo.

The date today is: 01 May 2019
The current time is: 17:13:16
The humidity is: 47%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 15.9°C, you might need a jacket.

Good afternoon Hvagjordo.

The date today is: 01 May 2019
The current time is: 17:13:16
The humidity is: 47%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 15.9°C, you might need a jacket.
Hei. Jeg gjorde følgende:

1. Først legger jeg hele koden i en funksjon som heter "def_start_the_program"(gjøre det mer "pythonic" som de kaller det)
2. Så kaller jeg på denne funksjonen helt på slutten av programmet
3. Så fjerner jeg "continue" og kaller funksjonen istedenfor.

Funker fint her

her er koden:

Kode

# - Good Morning Program -

# Import
import datetime
import requests
import sys

def start_program():
    # 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':
            start_program()
        else:
            print('Goodbye')
            break
start_program()
Til admin "Vidarlo" og dere andre, hope you are watching (Kysse-emoji)
Sist endret av cplpro; 1. mai 2019 kl. 20:49.
Sitat av cplpro Vis innlegg
Hei. Jeg gjorde følgende:

1. Først legger jeg hele koden i en funksjon som heter "def_start_the_program"(gjøre det mer "pythonic" som de kaller det)
2. Så kaller jeg på denne funksjonen helt på slutten av programmet
3. Så fjerner jeg "continue" og kaller funksjonen istedenfor.

Funker fint her

her er koden:
Vis hele sitatet...
Denne fungerer ikke. Når du kaller funksjonen etter å ha trykket y, exiter du aldri loopen. Som om du trykker y første gang, og deretter n, så blir du promptet en gang til.

Her er 'fasit':

Kode

# - Good Morning Program -
 
#Import
import datetime
import requests
import sys
while True:
    #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':
            break
        else:
            print('Goodbye')
            sys.exit()
Når jeg sa wrappe hele programmet i en while True, så mente jeg hele :P
Min måte funker hele fint. Men ja, din måte funker også
Sitat av cplpro Vis innlegg
Min måte funker hele fint. Men ja, din måte funker også
Vis hele sitatet...
Nei, det gjør den ikke. Kjører du den, og så trykker y, og deretter n, blir du spurt en gang til. Det som skal skjer er at dersom du trykker n, så skal den avslutte programmet helt. Se under.

What is your name?: Sinken
City Name: Oslo

Good afternoon Sinken.

The date today is: 01 May 2019
The current time is: 22:09:37
The humidity is: 87%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 10.7°C, you might need a jacket.
Would you like to check another city (y/n) ?: y
What is your name?: Sinken
City Name: London

Good afternoon Sinken.

The date today is: 01 May 2019
The current time is: 22:09:42
The humidity is: 71%
Latitude and longitude for London is: -0.13 51.51
The temperature is a mild 12.2°C, you might need a jacket.
Would you like to check another city (y/n) ?: n
Goodbye

Good afternoon Sinken.

The date today is: 01 May 2019
The current time is: 22:09:37
The humidity is: 87%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 10.7°C, you might need a jacket.
Would you like to check another city (y/n) ?:
Vis hele sitatet...
Aha, nå forstår jeg hva du mener. Den avslutter kun den aktuelle brukeren ja.

Men ja, da må man selvfølgelig bytte ut break med sys.exit(). Gjorde det nå på min kode og funker perfekt :P
Sist endret av cplpro; 1. mai 2019 kl. 23:17.
Nå fungerer det endelig!
Takk for alle svar, KP gitt

Kode

# - Good Morning Program -

#Import
import datetime
import requests
import sys

#Input
name_of_user = input("What is your name?: ")

#Loop
while True:

    #Input
    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']

    #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.")

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

Ser sånn her ut:


What is your name?: Hvagjordo
City Name: Stavanger

Good afternoon Hvagjordo.

The date today is: 01 May 2019
The current time is: 22:14:56
The humidity is: 93%
Latitude and longitude for Stavanger is: 5.73 58.97
The temperature is a mild 7.2°C, you might need a jacket.
Would you like to check another city (y/n)?: y
City Name: Oslo

Good afternoon Hvagjordo.

The date today is: 01 May 2019
The current time is: 22:15:00
The humidity is: 87%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 10.7°C, you might need a jacket.
Would you like to check another city (y/n)?: y
City Name: Svinesund

Good afternoon Hvagjordo.

The date today is: 01 May 2019
The current time is: 22:16:16
The humidity is: 47%
Latitude and longitude for Svinesund is: 11.27 59.1
The temperature is a mild 12.2°C, you might need a jacket.
Would you like to check another city (y/n)?: n
Goodbye

Process finished with exit code 0
NOOOOOOOOOOOOOOOOOO-
robhol's Avatar
En ting du kan vurdere, som er litt på siden av det du spør om, men fortsatt relevant: se på koden din og finn steder du gjentar deg. Du kan for eksempel lage en metode (funksjon) som inneholder den delen av programmet du skriver flere ganger, men med parametere som du kan endre på når du trenger det. Sluttresultatet kommer på ca. halvparten av antall kodelinjer, og du slipper å endre ting flere steder.
Sitat av robhol Vis innlegg
En ting du kan vurdere, som er litt på siden av det du spør om, men fortsatt relevant: se på koden din og finn steder du gjentar deg. Du kan for eksempel lage en metode (funksjon) som inneholder den delen av programmet du skriver flere ganger, men med parametere som du kan endre på når du trenger det. Sluttresultatet kommer på ca. halvparten av antall kodelinjer, og du slipper å endre ting flere steder.
Vis hele sitatet...
Ja det er en god ide
Tenker du da spesielt på alle printene jeg har som er repeat om å om igjen?

Eks:

Kode

    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.")
NOOOOOOOOOOOOOOOOOO-
robhol's Avatar
Det, og at du har en del tilfeller du tester flere ganger, både tid og temperatur - dette fordi du tester mot alle "kombinasjoner" av morgen/kveld og varmt/kaldt. Du kan med fordel dele opp den "iffen" og i stedet bruke én if for hver ting du vil skal variere, for eksempel. Da vil du ikke nødvendigvis trenge noen funksjon lenger, men jeg tenkte det først og fremst som et "mellomsteg".

PS: tror sammenlikningen på tiden er potensielt litt wonky - du oversetter til en string for å sammenlikne, og det er ofte noe man vil unngå.
Sitat av robhol Vis innlegg
Det, og at du har en del tilfeller du tester flere ganger, både tid og temperatur - dette fordi du tester mot alle "kombinasjoner" av morgen/kveld og varmt/kaldt. Du kan med fordel dele opp den "iffen" og i stedet bruke én if for hver ting du vil skal variere, for eksempel. Da vil du ikke nødvendigvis trenge noen funksjon lenger, men jeg tenkte det først og fremst som et "mellomsteg".

PS: tror sammenlikningen på tiden er potensielt litt wonky - du oversetter til en string for å sammenlikne, og det er ofte noe man vil unngå.
Vis hele sitatet...
Takk for tipsene, det er noe jeg skal se på
Sitat av cplpro
1. Først legger jeg hele koden i en funksjon som heter "def_start_the_program"(gjøre det mer "pythonic" som de kaller det)
Vis hele sitatet...
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
Ville det vært problematisk, kodemessig, å bytte ut

Kode

api_info = api_usage(city)
prog_logic(api_info, name_of_user, city)
med

Kode

prog_logic(api_usage(city), name_of_user, city)
eller er det rett og slett for leselighetens skyld?
Sist endret av Sinken; 2. mai 2019 kl. 17:41.
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
Sitat av Sinken Vis innlegg
Ville det vært problematisk, kodemessig, å bytte ut

Kode

api_info = api_usage(city)
prog_logic(api_info, name_of_user, city)
med

Kode

prog_logic(api_usage(city), name_of_user, city)
eller er det rett og slett for leselighetens skyld?
Vis hele sitatet...
Helt greit og bytte ut til det,skrev det sånn fordi jeg først gjorde en test alene med api_usage(city) funksjon.
NOOOOOOOOOOOOOOOOOO-
robhol's Avatar
Et tips når man skriver navn på klasser, funksjoner osv. er at de bør være beskrivende og forklare hva som blir gjort. Konvensjonen for funksjoner/metoder i de fleste språk, Python inkludert, er at de inneholder verb. På den måten er user_input, api_usage, prog_logic og menu noe sære navn på slikt, i tillegg til at noen av dem ikke nødvendigvis er logiske måter å dele inn programmet på uansett.
Et til spørsmål om noen gidder og se på det da
Har nå lagt til sånn at man mottar kopi av søket på emailen sin.
MEN..men, alltid et men. Hvordan skal jeg klare og få den til å sende søket som flere søk hver gang man velger en ny by?

Kode

# - Good Morning Program -

#Import
import datetime
import requests
import sys
import smtplib
import ad_pw
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#Input
name_of_user = input("What is your name?: ")
receiver_email = input("Your e-mail: ")

#Email
sender_email = ad_pw.email_address
password = ad_pw.email_password
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(sender_email, password)

#Loop
while True:

    #Input
    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']

    #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.")

    restart = input('Would you like to check another city (y/n)?: ')
    if restart == 'y':
        continue
    else:
        break


#HTML
html_message = """\
<html>
  <head></head>
  <body>
    <p>Hi, """ + str(name_of_user) + """<br>
    Here is the data from your weather search:<br>
    <br>
    City: """ + str(city) + """<br>
    Temperature: """ + "{:.1f}".format(degrees) + """°C<br>
     Humidity: """ + str(humidity) + """%<b>
    </p>
  </body>
</html>
"""

#Email
msg = MIMEMultipart('alternative')
msg['From'] = sender_email
msg['To'] = receiver_email
msg = MIMEText(html_message, "html")

#Send email
server.sendmail(sender_email, receiver_email, msg.as_string())

#Final print
print('Goodbye, an email has been sent to ' + receiver_email + " and you will receive a copy for data from your searched cities there")

#Exit
sys.exit()

Jeg tenkte jeg kunne legge det i loopen (ligger utenfor loopen nå), men sånn jeg tenker det så vil den sende en ny email for hver gang man velger en ny by, istedenfor at alt havner i EN email (om dette var forståelig hehe ). Klarer ikke forstå hvordan jeg skal få sendt alt i EN epost.

Regner med at jeg på en måte må lagre hvert svar + søk, så sende det på slutten av koden eller slutten av loopen på en måte?

PS: Prøvde med yagmail men når jeg brukte yagmail ville ikke pw og email bli godkjent. Og bruker HTML fordi når jeg skrev alt som vanlig tekst ble bare meldingen helt blank jo flere variable jeg addet i mailen



En annen ting. Prøvde å legge til at man kunne velge med y/n om man vil motta svaret på email så det ikke blir tvang å motta været på email (ikke det at jeg skal publisere det her, bare øver meg), men får invalid syntax.

Kode

    restart = input('Would you like to check another city (y/n)?: ')
    if restart == 'y':
        continue
    else:
        # HTML
        html_message = """\
        <html>
          <head></head>
          <body>
            <p>Hi, """ + str(name_of_user) + """<br>
            Here is the data from your weather search:<br>
            <br>
            City: """ + str(city) + """<br>
            Temperature: """ + "{:.1f}".format(degrees) + """°C<br>
             Humidity: """ + str(humidity) + """%<b>
            </p>
          </body>
        </html>
        """

        # Email
        msg = MIMEMultipart('alternative')
        msg['From'] = sender_email
        msg['To'] = receiver_email
        msg = MIMEText(html_message, "html")
        receive_email = input("Do you want to receive a copy from you search (y/n)?: ")
        if receive_email = "y":
            print(
            'Goodbye, an email has been sent to ' + receiver_email + " and you will receive a copy for data from your searched cities there")
            server.sendmail(sender_email, receiver_email, msg.as_string())
        else:
            print('Goodbye')
            break

#Exit
sys.exit()
Kommer rød strek under

Kode

f receive_email = "y":
Holder jeg over den streken står det "colon expected", men har jo colon?

Det med og spørre om man vil motta emailen fikk jeg fiksa, hadde vist bare slurva ser jeg.

Kode

    restart = input('Would you like to check another city (y/n)?: ')
    if restart == 'y':
        continue
    else:
        # HTML
        html_message = """\
        <html>
          <head></head>
          <body>
            <p>Hi, """ + str(name_of_user) + """<br>
            Here is the data from your weather search:<br>
            <br>
            City: """ + str(city) + """<br>
            Temperature: """ + "{:.1f}".format(degrees) + """°C<br>
             Humidity: """ + str(humidity) + """%<b>
            </p>
          </body>
        </html>
        """

        # Email
        msg = MIMEMultipart('alternative')
        msg = MIMEText(html_message, "html")
        receive_email = input("Do you want to receive a copy from you search (y/n)?: ")
        if receive_email == 'y':
            receiver_email = input("Your e-mail: ")
            msg['From'] = sender_email
            msg['To'] = receiver_email
            print(
            'Goodbye, an email has been sent to ' + receiver_email + " and you will receive a copy for data from your searched cities there")
            server.sendmail(sender_email, receiver_email, msg.as_string())
            sys.exit()
        else:
            print('Goodbye')
            sys.exit()
Sist endret av hvagjordo; 4. mai 2019 kl. 14:09. Grunn: Automatisk sammenslåing med etterfølgende innlegg.
Queen of Blades
Jonta's Avatar
DonorCrew
Vurdér å legge til noe som fanger ugyldige bynavn

«Trondheim9» gir

Kode

Traceback (most recent call last):
  File "morning.py", line 24, in <module>
    format_add = json_data['main']['temp']
KeyError: 'main'
Sitat av Jonta Vis innlegg
Vurdér å legge til noe som fanger ugyldige bynavn

«Trondheim9» gir

Kode

Traceback (most recent call last):
  File "morning.py", line 24, in <module>
    format_add = json_data['main']['temp']
KeyError: 'main'
Vis hele sitatet...
Ahh! Det hadde jeg faktisk glemt. Ja jo, det må jeg jo selvfølgelig ha Takk