0

I am trying to write a function to get 2 int values from a user until their sum is 21, Simple!!

The aim is to keep prompting the user to pass 2 int values until the condition is met. I am not sure where the code breaks as it stops when either conditions is met, both if true or false.

def check_for_21(n1,n2):
    result = 0
    while True:
        while result != 21:
            try:
                n1 = int(input("Enter first number >> "))
                n2 = int(input("Enter second number >> "))

                if n1+n2 != 21:
                    print("You did not get to 21! ")
                else:
                    print("You got it! ")

            except:
                if n1+n2 == 21:
                    print("You got it! ")
            else:
                break

        break
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Fathi
  • 9
  • 1
  • 6

4 Answers4

1

This is what you are looking for you had multiple logical errors! However, the idea was there but wrongly formatted. In this program, it runs continuously until you enter two numbers and their sum is 21

def check_for_21():
    while True:
        n1 = int(input("Enter first number >> "))
        n2 = int(input("Enter second number >> "))

        if n1+n2 != 21:
            print("You did not get to 21! ")
        else:
            print("You got it! ")
            break

check_for_21()
ksa
  • 118
  • 8
1

Try this. This will meet your requirment.

a = 5
while (a<6):
        n1 = int(input("Enter first number >> "))
        n2 = int(input("Enter second number >> "))

        if n1+n2 == 21:
                print("You got it ")
                break
        else:
                print("You did not get to 21!  ")
124x
  • 43
  • 7
0

Take the input, check for result, if you get 21, break the loop.

def check_for_21(n1,n2):
    result = 0
    while True:
        try:
            n1 = int(input("Enter first number >> "))
            n2 = int(input("Enter second number >> "))

            if n1+n2 != 21:
                print("You did not get to 21! ")
            else:
                print("You got it! ")
                break

        except:
            pass
0

Below is the test result of the code that worked for me:

enter image description here

Lucifer
  • 156
  • 4
  • 15