lundi 4 mai 2015

Alternate way to use elif in python?

I'm creating a code which does a basic math game.

Here is a part of my code which does the calculation:

first_num = random.randint(1,10) #for the first number generate a random number
second_num = random.randint(1,10) #for the second number generate a random number
ran_calculation = (first_num+second_num,first_num-second_num,first_num*second_num) #List of random calculations
calculation =(random.choice(ran_calculation)) #Choose a random calculation from the list above

if calculation == first_num+second_num: #If question is addition
    print ("Question (%d)" % (i+1)) 
    print (first_num) #Print first number
    print("Add (+)") #Followed by the add symbol
    print(second_num) #Then the second number

elif calculation == first_num-second_num: #If question is subtraction
    print ("Question (%d)" % (i+1))
    print(first_num) #Print first number
    print("Subtract (-)") #Followed by the subtraction symbol
    print(second_num) #Then the second number

elif calculation == first_num*second_num: #If question is multiplication 
    print ("Question (%d)" % (i+1))
    print(first_num) #Print first number 
    print("Multiply (*)") #Followed by the multiplication  symbol
    print(second_num) #Then the second number

However it is long and I'm repeating myself using the elif function. Is there a easier way to do the same thing in a easy and shorter way?

Perhaps something like this: filename = 'class{}.csv'.format(form) which I used to choose the class the student is in.

Aucun commentaire:

Enregistrer un commentaire