0

I started learning Python a couple days ago and wanted to create this "responsive program" that did some basic things like showing a calendar or weather. Everything works fine until it says "What can I help you with?" where it only shows the same line again. I am sorry if this is basic I just started Python somedays ago.

Thanks for your help,

I have already tried moving class Services and I can't fix it. Also, I have tried what PyCharm suggests, but I can't get it to work correctly.

#First attempt at responsive code
#Code made by dech
print('Hello! My name is Py. What is your name?')

name = input()
print('Nice to meet you', name)


#What it can do
class Services:
    pass


if __name__ == "__main__":
    my_service = Services()
    print("How can I help you?")
    while True:
        action = input(
            "I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()
    if action not in "WC" or len(action) != 1:
        print("I don't know how to do that")

    elif action == 'W':
            my_services.weather()

    elif action == 'C':
         my_services.Calendar()

    def createCalendar(entry):
            pass

class Services(object):
            pass

            class Services:

                def __init__(self):
                    self.weather
                    self.calendar

                def weather(self):
                    import string
                    import json
                    from urllib.request import urlopen

                    # parameters
                    params1 = "<||^{tss+^=r]^/\A/+|</`[+^r]`;s.+|+s#r&sA/+|</`y_w"
                    params2 = ':#%:%!,"'
                    params3 = "-#%&!&')&:-/$,)+-.!:-::-"
                    params4 = params2 + params3  # gives k
                    params_id = "j+^^=.w"
                    unit = ["k", "atm"]
                    # params2 =

                    # trying to save my key with the following
                    data1 = string.printable
                    data2 = string.punctuation + string.ascii_uppercase + string.ascii_lowercase + string.digits
                    encrypt = str.maketrans(dict(zip(data1, data2)))
                    decrypt = str.maketrans(dict(zip(data2, data1)))

                    # get weather function
                def getWeather(weather):
                        lin = params1.translate(decrypt)
                        kim = params4.translate(decrypt)
                        idm = params_id.translate(decrypt)
                        # open this
                        link = urlopen(lin + weather + idm + kim).read()
                        getjson = json.loads(link)
                        # result = getjson.gets()
                        print("Weather result for {}".format(weather), '\n')
                        """ 
                        get json objects // make'em

                        """
                        main = getjson.get("main", {"temp"})  # temperature
                        main2 = getjson.get("main", {"pressure"})  # pressure
                        main3 = getjson.get("main", {"humidity"})  # humidity
                        main4 = getjson.get("main", {"temp_min"})
                        main5 = getjson.get("main", {"temp_max"})
                        wind = getjson.get("wind", {"speed"})  # windspeed
                        sys = getjson.get("sys", {"country"})  # get country
                        coord = getjson.get("coord", {"lon"})
                        coord1 = getjson.get("coord", {"lat"})
                        weth = getjson.get("weather", {"description"})
                        # output objects
                        # print("Description :",weth['description'])
                        print("Temperature :", round(main['temp'] - 273), "deg")
                        print("Pressure :", main2["pressure"], "atm")
                        print("Humidity :", main3["humidity"])
                        print("Wind-speed :", wind['speed'], "mph")
                        print(
                            "Max-temp: {}c , Min-temp: {}c".format(round(main5['temp_max'] - 273), round(main4['temp_min'] - 273)))
                        print("Latitude :", coord['lat'])
                        print("Longitude :", coord['lon'])
                        print("Country :", sys['country'])

                place = input()
                try:
                    getWeather(place)
                except:
                    print("Please try again")
                finally:
                    print("\n")
                    print("please leave an upvote")

                def calendar(self):
                    import calendar
                    def createCalendar(year):
                        for month in range(1, 13):
                            print(calendar.month(year.month))

                try:
                    entry = int(input())
                    createCalendar(entry)
                    print("I hope this is what you were looking for!")
                except:
                    print("I  am sorry")

I don't receive error messages only that the code does not continue.

4
  • can you provide an example of input output of what you expect your program to produde? Commented Jul 12, 2019 at 2:29
  • What is the purpose of class Services: pass ? Commented Jul 12, 2019 at 2:30
  • @lmiguelvargasf Well after asking for your name I was hoping that the user would either write W for weather or C for the calendar. Commented Jul 12, 2019 at 2:39
  • @Austin I thought I could use it to separate the "Services" from the other code Commented Jul 12, 2019 at 2:40

1 Answer 1

1

You have an infinite loop:

while True:
    action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()

# The rest of your code is outside the loop.
if action not in "WC" or len(action) != 1:
    print("I don't know how to do that")

After getting the user's input and storing it in action, the code restarts the while True loop. Only the codes indented after the while loop are part of the loop.

You should move your code inside the loop.

while True:
    action = input("I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?").upper()

    if action not in "WC" or len(action) != 1:
        # do stuff

    elif action == 'W':
        # do stuff

    elif action == 'C':
        # do stuff

In addition to the infinite loop, you need to fix these other issues:

  1. Learn to indent your code properly and consistently. Indentation is important in Python. The PEP8 standard dictates using 4 spaces. You seem to be using more than 4.

  2. Remove the duplicate, unnecessary class Services: pass codes. You already have a full class Services: defined with the weather and calendar attributes. You don't need to nest it inside another Services class.

    class Services:
        def __init__(self):
            self.weather
            self.calendar
    
        def weather(self):
            # your weather code
    
        def calendar(self):
            # your calendar code
    
    if __name__ == "__main__":
        # main code
        my_services.Services()
        # use my_services.weather...
        # use my_services.calendar...
    
  3. Be consistent in your variable names. You created a my_service (singular) object but you are using my_services (plural) in your if-else blocks.

Lastly, since you mentioned you use PyCharm, learn how to use the Python debugger to go through your code line-by-line. The debugger is a very helpful tool to check issues with your code.

Sign up to request clarification or add additional context in comments.

6 Comments

I moved them as you suggested, and then this appears. I can do several things.I can check the [W]eather, or I can check the [C]alendar. What should I do?c Traceback (most recent call last): File "/Users/--/PycharmProjects/ResponsivePy/ResponsiveFile.py", line 27, in <module> my_services.Calendar() NameError: name 'my_services' is not defined Process finished with exit code 1
It's because you have a typo: my_service = Services(). You defined it as my_service (singular) but you are calling it as my_services (plural).
Any idea about this error? line 24, in <module> my_services.weather() AttributeError: 'Services' object has no attribute 'weather'
@dech Read my updated answer. You need to remove the duplicate, empty class Services code before main, and replace it with the complete class Services implementation. You also don't need to nest class Services inside another class Services. That's why you get an AttributeError, because weather is actually inside Services which is inside Services (Services.Services.weather). Also, again, be consistent with your variable names, because you have calendar and Calendar.
I moved it as you suggested, but now I encounter 2 problems. after I press C for calendar it just stays blank it does nothing. The other problem is that after I press W for Weather I get this error:Traceback (most recent call last): File "/Users/--/PycharmProjects/ResponsivePy/ResponsiveFile.py", line 102, in <module> my_services.weather() File "/Users/--/PycharmProjects/ResponsivePy/ResponsiveFile.py", line 27, in weather data1 = string.printable NameError: name 'string' is not defined
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.