1

I don't understand the purposed of the last two lines in the prescribed structure / how to format program in this structure. Prescribed structure:

def main():
    ...


def convert(time):
    ...


if __name__ == "__main__":
    main()

currently I have the following code which seems to output correct meal times but doesn't meet requirements for check50 - not sure how to properly adjust the structure of my code to include the last bit of the prescribed structure and pass check50

def main():
    x=input('What time is it? ')
    x=convert(x)
    if 7<=x<=8:
        print('breakfast time')
    elif 12<=x<=13:
        print('lunch time')
    elif 18<=x<=19:
        print('breakfast time')

def convert(time):
    h,m=time.split(':')
    time=float(h)+(float(m)/60)
    return(time)

main()

Any guidance on what I am missing here would be greatly appreciated :)

0

2 Answers 2

3

Are you still working on this? If so, just modify your code to match the template format. Replace the last line:

main()

with these 2 lines:

if __name__ == "__main__":
    main()

Or add the if statement and indent main() - your call.

Both methods will call main() when run as a Python script. There are good reasons to use the 2nd format. However, they are not explained in the pset instructions, or during the lecture (AFAIK). First, it's just good Python coding practice. :-) Why it's good practice will come into play on the Unit Test psets.

[Some quick jargon: Python names that start/end with 2 underscores (like __name__ and __main__ are called "dunder" variable names (for double underscore).]

This structure lets you to define code that is executed when the file is run as a script (eg as python your_file.py), but it does not run when it’s imported as a module (e.g. import your_file). We haven't covered import yet. Libraries (modules) are introduced in Lecture 4, and they become more important when we do Unit Tests in Lecture 5.

For more details, read this Real Python tutorial (maybe more than you want to know): What Does if __name__ == "__main__" Do in Python?

1
  • thanks for this
    – ron
    Commented Jun 27, 2023 at 14:10
-1

try this.

def main():
    time = input("What time is it? ").strip()
    converted_time = convert(time)
    if 7 <= converted_time <= 8:
        print("breakfast time")
    elif 12 <= converted_time <= 13:
        print("lunch time")
    elif 18 <= converted_time <= 19:
        print("dinner time")
    else:
        print("")

def convert(time):
    x, y = map(int, time.split(":"))
    converted_time = x + y/60
    return converted_time

1
  • how is this different from his answer and other answers. code only answers are frowned upon highly. you havent explained anything.
    – UpAndAdam
    Commented Jan 2 at 17:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .