pythonperformancesimplifycoding-efficiency

Is there a way to simplify this python code?


approach #1 rogram gives the user two tries to answer correctly, the user will only get credit for a correct answer on the first try, program will display the correct answer after the second try is incorrect.

question = '1+1= '
answer = '2'
correct = 0

user_answer = input(question)
if user_answer == answer:
  print('Correct! ')
  correct += 1
else:
  user_answer = input('Try Again: ')
  if user_answer == answer:
    print('Correct! ')
  else:
    print(f'The answer is: {answer}')

print(correct)

approach #2

question = '1+1= '
answer = '2'
correct = 0

user_answer = input(question)
for try_ in range(2):
  if user_answer != answer:
    if try_ == 0:
      user_answer = input('Try Again: ')
    else:
      print(f'The answer is: {answer}')
  else:
    print('Correct! ')
    if try_ == 0:
      correct += 1
    break

print(f'number correct on the first try: {correct}')

approach #3

question = '1+1= '
answer = '2'
correct = 0

user_answer = input(question)
for try_ in range(2):
  if try_ <= 1:
    if user_answer == answer:
      print('Correct! ')
      if try_ == 0:
        correct += 1
      break
    else:
      if try_ == 0:
        user_answer = input('Try Again: ')
      else:
        print(f'The answer is: {answer}')

print(f'number correct on the first try: {correct}')

approach #4

question = '1+1= '
answer = '2'
correct = 0

user_answer = input(question)
for try_ in range(2):
  if try_ == 1 and user_answer != answer:
    print(f'The answer is: {answer}')
    break
  if user_answer == answer:
    print('Correct! ')
    if try_ == 0:
      correct += 1
      break
  else:
    user_answer = input('Try Again: ')

print(f'number correct on the first try: {correct}')

All approaches work. I prefer approach #1, but I feel like this can be simplified even more. I don't like seeing this part of the code twice:

    if user_answer == answer:
      print('Correct! ')

But I'm not sure how to simplify or even if it is possible. Any help would be appreciated.

Thanks.


Solution

  • Using a for loop to iterate twice is the right idea to reduce repeated code, and since the two iterations differ only in the user prompts, you can make the loop iterate over the two prompts instead. Moreover, correct behaves more like a Boolean, so make it one:

    question = '1+1= '
    answer = '2'
    
    for prompt in question, 'Try Again: ':
        if correct := input(prompt) == answer:
            print('Correct! ')
            break
    else:
        print(f'The answer is: {answer}')
    print(correct)