Search code examples
pythonundefined

I am having problem in my variable "p. Can someone help me?


import random


def question1():
        print("What is the Capital of Bangladesh?")
        print("Your options are: 1)Dhaka 2)Cumilla 3)Rangpur 4)Barishal")
        # p is answer
        p = 1

def question2():
    print("Where is Bangladesh?")
    print("Your options are: 1)in Africa 2)in Asia 3)in Europe 4)in Antertica")
    # p is answer
    p = 2


n= 1
e= 5000
x= ["a","b"]

while (n==1):
    w= random.randint(0,1)
    y= x[w]
    
    if "a" in y:
        question1()
        l= int(input("Type your option number:"))
        x.remove(y)
        
        if (p == l):
            e=e*2
            print("Congrats!You have won" + e)
        else:
            print("You heve lost!")
            print("You answered" + "answers!")
            n=n+1
        
    elif "b" in y:
        question2()
        l= int(input("Type your option number:"))
        x.remove(y)
        
        if (p == 2):
            e=e*2
            print("Congrats!You have won" + e)
        else:
            print("You heve lost!")
            print("You answered" + "answers!")
            n=n+1

            
print("Your total point is:" + e)

I defined "p" variable as the answer of the MCQ questions calling a function. But inside the loop, when I call the function, the "p" variable still stays undefined. I had run that function in the loop in if statement but it seems still undefined. Why is it happening? And how to fix it?


Solution

  • Here is a version of your code that works. You had several problems. For example, this doesn't work because e is an integer, and you can't add strings and integers.

               print("Congrats!You have won" + e)
    

    Note that I have eliminated the ["a","b"] nonsense, and have simply created a list with the question functions. Now I can choose one at random and call it, so I don't have to have a bunch of duplicated code. One chunk of code handles all the questions.

    import random
    
    def question1():
        print("What is the Capital of Bangladesh?")
        print("Your options are: 1)Dhaka 2)Cumilla 3)Rangpur 4)Barishal")
        # p is answer
        return 1
    
    def question2():
        print("Where is Bangladesh?")
        print("Your options are: 1)in Africa 2)in Asia 3)in Europe 4)in Antertica")
        # p is answer
        return 2
    
    n= 0
    e= 5000
    questions = [question1, question2]
    
    while questions:
        question = random.choice(questions)
        answer = question()
    
        l= int(input("Type your option number:"))
            
        if answer == l:
            questions.remove( question )
            n += 1
            e *= 2
            print("Congrats!You have won", e)
        else:
            print("You heve lost!")
            print("You answered", n,  "answers!")
            break
        
    print("Your total point is:", e)