+ 2

Hi everyone in this code

https://www.sololearn.com/en/compiler-playground/c3UUOFjodZDM I have faced a problem I don't know why it says hour is not defined although I defined it as global variable

12th Feb 2024, 5:49 PM
Yusof
Yusof - avatar
7 ответов
0
main() is requesting the hour and minute as parameters though they still have not been defined by convert(), since they are only defined there, note that convert() is only called inside main(), while it is running, main() is supposed to have its parameters filled at the start when running, before convert() gets called in its code, so this is a egg-chicken problem, try to remove the main() parameters and use the global variables created by convert() instead, that is, "hour" and "minute" instead of "h" and "m", if you prefer to use those variable names in main() simply create aliases by redefining the variables: "h, m = hour, minute", but in your code it isn't even necessary to do that, you don't need those global variables, just unpack the return values of convert() inside main(): "h, m = convert()"
14th Feb 2024, 1:21 PM
Gabi_kun :3
Gabi_kun :3 - avatar
+ 9
Yusof , there are two reasons that make the code unnecessarily complicated. > on the one hand it is the use of the main() function > on the other hand it is the use of global variables. i used your code and commented the unnecessary things. i turned the main() function into a completely normal code that is in the global scope. see the code in the attached file. https://sololearn.com/compiler-playground/cVPbD1WqV7vZ/?ref=app
12th Feb 2024, 8:10 PM
Lothar
Lothar - avatar
+ 4
In oder you to modify any global state in a function 1. You need to define it at top level 2. You need the global keyword defined inside the function
12th Feb 2024, 6:07 PM
Ion Kare
Ion Kare - avatar
+ 3
any reason you done that way ? Instead of passing it directly?
12th Feb 2024, 6:05 PM
Ion Kare
Ion Kare - avatar
+ 2
I make the code simpler and working check this https://www.sololearn.com/en/compiler-playground/czfk3DDXPav8
14th Feb 2024, 12:55 PM
Nihap Mrm
Nihap Mrm - avatar
+ 1
ThanksLothar but this code is a solution of problem set from cs50 course it is required to use two functions main and convert
14th Feb 2024, 8:16 AM
Yusof
Yusof - avatar
+ 1
This way it works: def convert(time): hour,minute=time.split(":") hour=int(hour) minute=int(minute) return hour,minute def main(): tim=input("Enter time: ") h, m = convert(tim) if h in range(7,9): if m in range(0,60): print("breakfast time") elif h in range(12,14): if m in range(0,60): print("lunch time") elif h in range(18,20): if m in range(0,60): print("dinner time") main() It is good practique to define the main() function as the last function and its utilities before
14th Feb 2024, 1:33 PM
Gabi_kun :3
Gabi_kun :3 - avatar