compare string

Asked

Viewed 68 times

1

I have an input with the name "city" which is a string and I need to make sure that if the user enters a number or does not type anything he receives an error message, as I could do?

Follows the code

import requests
import json
from googletrans import Translator


class Temperatura():
    while True:
        cidade = input("Escreva sua cidade para consultar o tempo: ")
        requisicao = requests.get("http://api.openweathermap.org/data/2.5/weather?q=" + cidade +
                                  "&appid=KEY")
        tempo = json.loads(requisicao.text)
        des = tempo['weather'][0]['description']
        hu = tempo['main']['humidity']
        t = tempo['main']['temp'] -273.15
        #tradução
        translator = Translator()
        des_t = translator.translate(des, dest='pt').text
        print('Condição do tempo:', des_t,',temperatura de', round(t),'graus','e umidade a',hu,'%')
  • That class Temperatura has a while just like that? No methods?

  • yes, but further down I have another input, which depending on the answer it to the class and starts another.

  • 2

    It seems that you used class the wrong way there. This could be a function only.

  • Already corrected, thanks for the idea.

  • There are several other mistakes there, even if you change class for def no request will be made. recommend a better reading on the doc of the api. besides these two links for references classes and function

1 answer

0

How your input is of the type str even if the user type 12345, for example, the program will not understand how int. So I suggest creating a variable and putting in there everything you want not accept, such as numbers, special characters, etc.

class Temperatura():

excluir = r"/\?%0123456789,."
while True:
    cidade = input("Escreva sua cidade para consultar o tempo: ")
    invalido = any(elem in cidade for elem in excluir)
    if cidade != '' and invalido == False:
        requisicao = requests.get("http://api.openweathermap.org/data/2.5/weather?q=" + cidade +
                                  "&appid=KEY")
        tempo = json.loads(requisicao.text)
        des = tempo['weather'][0]['description']
        hu = tempo['main']['humidity']
        t = tempo['main']['temp'] -273.15
        #tradução
        translator = Translator()
        des_t = translator.translate(des, dest='pt').text
        print('Condição do tempo:', des_t,',temperatura de', round(t),'graus','e umidade a',hu,'%')
    else:
      print('mensagem de erro')
  • 1

    I suggest correcting the class that is not class either; and I need to say that it has become quite confusing to display an error message when valido is true. If it is valid, why would it make a mistake?

  • Truth haha. I corrected for invalido

Browser other questions tagged

You are not signed in. Login or sign up in order to post.