求問各路python大神! try 和except 如何在其中加入迴圈效果!

如題所述

try:

    num = int(input("請輸入一個整數"))

    result = 8 / num

    print(result)

except ValueError:

    print("請輸入正確整數")


except ZeroDivisionError:

    print("除0錯誤")


這本來是一個捕獲異常的小練習,其目的是將輸入整數的兩種錯誤捕獲出來,讓使用者不要看到原始錯誤,而改為
輸出我所設定的文字。

但接下來我設想到,若僅止於輸出該錯誤,而無法讓程序重新讓使用者輸入是非常不便的,於是我便想要在其中加入迴圈,但卻不斷失敗,請各路大神幫幫忙,思考思考。

以下是我的失敗代碼

try:
    count = 0
    def test():

        num = int(input("請輸入一個整數: "))

        result = 8 / num

        return result

    a = test()
    count = count + 1
    print(a)


except ValueError:

    while count == 0:

        print("請輸入正確整數: ")

        test()



except ZeroDivisionError:

    while count == 0:

        print("除0錯誤: ")

        test()

其中若輸入正常可以正常執行,但若是輸入0,或是字符串則會成功回到function一次,然後就會出現紅色錯誤。

在这里插入图片描述

剛剛五分鐘後又更新~

try:
    count = 0
    def test():

        num = int(input("請輸入一個整數: "))

        result = 8 / num

        return result

    a = test()
    print(a)


except ValueError:

    while count == 0:

        print("請輸入正確整數: ")

        count = count +1

        a = test()
        print(a)



except ZeroDivisionError:

    while count == 0:

        print("除0錯誤: ")

        count = count +1

        a = test()
        print(a)


這個版本可以讓我重新輸入整數一次,並成功的輸出我想要的錯誤提醒。
但第二次之後就會一樣顯示出紅色錯誤。

希望大神能再幫我修正到 只要沒有輸入正確都能一直以我想輸出的錯誤提醒,並且一再重輸入
函數。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值