ryand
ryand

Reputation: 131

break in for loop python program

i try to make program if sum of program 1000 the program wil print finished but if the number when we input = 0 the program return error. i try it with break in python but i dont get the right output. i need your oppinion about this.

this my program
banyak = int(input('Masukan banyak angka yang ingin dimasukkan = '))
for j in range(banyak):
    A = int(input("enter the number of 1 : "))
    B = int(input("enter the number of 2 : "))
    C = int(input("enter the number  of 3 : "))
    if(A + B + C == 1000):
        print("finished")
        break
    elif(A==0 or B==0 or C==0):
        print("error")
        break

the program should input :

100
0

output:

error

input:

400
300
300

output:

finished

Upvotes: 0

Views: 70

Answers (2)

Shawn
Shawn

Reputation: 16

when you input

1    # banyak
100  # A
0    # B

then the program's current line is

    C = int(input("enter the number  of 3 : "))

so it can't break. you can try this

banyak = int(input('Masukan banyak angka yang ingin dimasukkan = '))

for j in range(banyak):
    A = int(input("enter the number of 1 : "))
    if A == 0:
        print("error")

    B = int(input("enter the number of 2 : "))
    if B == 0:
        print("error")

    C = int(input("enter the number  of 3 : "))
    if C == 0:
        print("error")


    if A + B + C == 1000:
        print("finished")
        break

but is so foolish. And you can try this

banyak = int(input('Masukan banyak angka yang ingin dimasukkan = '))

for j in range(banyak):

    number_list = []
    for _ in range(3):
        input_number = int(input("enter the number : "))
        if input_number == 0:
            print("error")
            break
        number_list.append(input_number)


    if sum(number_list) == 1000:
        print("finished")
        break

    print('=============')

Upvotes: 0

azro
azro

Reputation: 54168

The easiest is to use an assert statement after each input, if it is incorrect, it'll raise an AssertionError that you can catch. The second element for assert is the exeception message, that can be use in the except section

banyak = int(input('Masukan banyak angka yang ingin dimasukkan = '))
for j in range(banyak):
    print(f"Round {j + 1}/{banyak}")
    try:
        A = int(input("enter the number of 1 : "))
        assert A != 0, "A is 0"
        B = int(input("enter the number of 2 : "))
        assert B != 0, "B is 0"
        C = int(input("enter the number  of 3 : "))
        assert C != 0, "C is 0"
        if A + B + C == 1000:
            print("finished")
            break
    except AssertionError as e:
        print("Error:", e)
        break

Masukan banyak angka yang ingin dimasukkan = 5
Round 1/5
enter the number of 1 : 200
enter the number of 2 : 300
enter the number  of 3 : 100
Round 2/5
enter the number of 1 : 400
enter the number of 2 : 0
Error: B is 0

Upvotes: 2

Related Questions