Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to tidy up the code
#1
how to tidy up the playeranswer part with list or other methods?
import random
question = list()
question1 = input ("Question 1")
question.append(question1)
question2 = input ("Question 2")
question.append(question2)
question3 = input ("Question 3")
question.append(question3)
question4 = input ("Question 4")
question.append(question4)
answer = list()
answer1 = input ("Answer of question 1")
answer.append(answer1)
answer2 = input ("Answer of question 2")
answer.append(answer2)
answer3 = input ("Answer of question 3")
answer.append(answer3)
answer4 = input ("Answer of question 4")
answer.append(answer4)
random = random.randint(1,4)
if random == 1:
    playeranswer1 = input (question[1])
    if playeranswer1 == answer[1]:
        print("You are right!")
    else:
        print("You are wrong...")
if random == 2:
    playeranswer2 = input (question[2])
    if playeranswer2 == answer[2]:
        print("You are right!")
    else:
        print("You are wrong...")
if random == 3:
    playeranswer3 = input (question[3])
    if playeranswer3 == answer[3]:
        print("You are right!")
    else:
        print("You are wrong...")
if random == 4:
    playeranswer4 = input (question[4])
    if playeranswer4 == answer[4]:
        print("You are right!")
    else:
        print("You are wrong...")
Reply
#2
Have two lists: questions and answers. Use a for loop to input them from the user, appending each one as you get it. Then get a random index and use it to pull the question and answer out of the two lists.

Even better, have one list. The items in the list are a tuple of (question, answer). Then you can use random.choice to pick them both out without having to mess with indexes.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  what function should i use to tidy up my code (extreme beginner) scraig0117 4 2,342 Dec-16-2019, 04:03 PM
Last Post: scraig0117

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020