I need to create a personality task for this assignment and I’ve written this block of code. I know it’s probably not the best way but I would like to know why it is not working.
I have 3 questions (Only 1 shown here) and their structures are all the same with the exception that instead of num_1, I used num_2 and num_3 for questions 2 and 3.
I’m getting the error: ‘<‘ not supported between instances of ‘int’ and ‘str. I have tried putting num_1 into int(num_1) but that didn’t work. Any help would be appreciated, thanks!
def question1():
print("What's your favorite genre of music?")
print("1. Pop")
print("2. Rap")
print("3. Metal")
music = int(input("Enter 1, 2, or 3: "))
if music == 1:
num_1 = 3
elif music == 2:
num_1 = 2
else:
num_1 = 1
def main():
question1()
if "num_1" + "num_2" + "num_3" == 9:
print("Your favorite color is red")
elif 5 < "num_1" + "num_2" + "num_3" < 9:
print("Your favorite color is blue")
else:
print("Your favorite color is green")
main()
>Solution :
There are a few errors in your code:
-
In your
main()function, you put the variablesnum1,num2, andnum3in quotation marks in the if statements. This is incorrect because we want the compare the variable values, not the variable name. -
Even if you made functions to declare
num2andnum3, because those variables (includingnum1) are local to the functions you would declare them in, they will not be recognized by yourmain()function.
To solve this problem, we can define num1, num2, and num3 as global variables.
With all these changes taken into account, your code could look something like this (with question2() and question3() modified of course so it’s an actual personality quiz haha):
def question1():
print("What's your favorite genre of music?")
print("1. Pop")
print("2. Rap")
print("3. Metal")
music = int(input("Enter 1, 2, or 3: "))
global num_1
if music == 1:
num_1 = 3
elif music == 2:
num_1 = 2
else:
num_1 = 1
def question2():
global num_2
num_2 = 2
def question3():
global num_3
num_3 = 2
def main():
question1()
question2()
question3()
if num_1 + num_2 + num_3 == 9:
print("Your favorite color is red")
elif 5 < num_1 + num_2 + num_3 < 9:
print("Your favorite color is blue")
else:
print("Your favorite color is green")
main()
I hope this helped answer your question! Please let me know if you need any further clarification or details 🙂