Python Forum
my first attempt, please advise me of any thing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
my first attempt, please advise me of any thing
#2
I didn't realize all those lines were tuples rather than just long strings. I realize the tuple parenthesis are optional, but I strongly recommend you use them in cases like these, as it makes the code a lot more readable.

Here's my refactor of your code, with comments though admittedly not tested (minus some questions; should be easy to add back in):
from random import choice 

# I changed this so that individual questions are stored with their answers.
# I don't organize questions with the same answer as being together, instead
# preferring to use comments to track the kind of question it is.
questions_answers = [
        # arithmetic
        ("4 / 2", 2),
        ("864 - 482 - 380 =", 2),
        # word problems
        ("a baby conceive two years and nine months ago, the answer is the baby's age. ", 2),
        ("2 Squared", 4),
        ("3 Squared", 9),
]

# this is called tuple unpacking, if you're unfamiliar with it
question, answer = random.choice(question_answers)
 
guess = input("What do you think the answer is ? ")

# I turn the guess into an int and compare that, instead of turning both to strs.
# My thought process is, I want to know if they have the right number, so I don't
# want it to say "wrong!" if for example they had trailing whitespace (which the
# int function ignores). The int function will also raise an exception when the
# guess is not an int. This might be too ugly for you in terms of output, but
# you can catch the exception and do whatever you want (e.g. complain, ask for a
# new attempt).
if int(guess) == answer:
        print("well done!")
else:
        print("wrong!")
Reply


Messages In This Thread
RE: my first attempt, please advise me of any thing - by micseydel - Jan-24-2020, 07:47 PM

Forum Jump:

User Panel Messages

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