[英]Break a loop and quit the program when user types ''quit'' in Python
[英]break in for loop python program
我嘗試制作程序,如果程序總和 1000 程序將打印完成,但如果我們輸入時的數字 = 0,程序返回錯誤。 我嘗試在 python 中中斷,但我沒有得到正確的 output。 我需要你的意見。
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
程序應輸入:
100
0
output:
error
輸入:
400
300
300
output:
finished
最簡單的方法是在每次輸入后使用assert
語句,如果不正確,它會引發一個AssertionError
,您可以捕獲它。 assert
的第二個元素是異常消息,可以在except
部分中使用
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
當你輸入
1 # banyak
100 # A
0 # B
那么程序的當前行是
C = int(input("enter the number of 3 : "))
所以它不能破裂。 你可以試試這個
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
但是太傻了。 你可以試試這個
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('=============')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.