请教一个python问题,如何返回到指定的代码行?经小杰大牛指点,终于实现了。

如题,请看下面这段代码:

print("Please give me two numbers.")
print("I print out the sum of these two numbers")
print("If you enter 'q' ,quit.")
while True:
    num1 = input("Please input the first number:")
    if num1 == 'q':
        break
    try:
        int(num1)
    except ValueError:
        print("You can only input integers!")
        continue
    num2 = input("Please input the second number:")
    if num2 == 'q':
        break
    try:
        int(num2)
    except ValueError:
        print("You can only input integers!")
        """
        如何加一行代码,如果num2出现类型错误,
        不要返回重新输入num1和num2,只输入num2
        """
    answer = int(num1) + int(num2)
    print(answer)

显然,这段代码现在还不完善,当num2输入是非整型时,会提示类型错误,因为我answer = int(num1) + int(num2) 没有使用try-except语句。这里我是想当输入是非整型时,第一时间提示用户,并返回重新输入。num1输入这里已经做到了,但是如果在num2后面加上continue,会返回到循环开始,从num1开始输入,这样并不科学,我是想哪出的问题,就返回到哪里,请教大神如何实现?

经过小杰大牛的指点,终于实现了,再次感谢小杰,请看代码:

print("Please give me two numbers.")
print("I print out the sum of these two numbers")
print("If you enter 'q' ,quit.")
while True:
    num1 = input("Please input the first number:")
    if num1 == 'q':
        break
    try:
        int(num1)
    except ValueError:
        print("You can only input integers!")
        continue

    while True:
        num2 = input("Please input the second number:")
        if num2 == 'q':
            break
        try:
            int(num2)
            break
        except ValueError:
            print("You can only input integers!")
            continue
    answer = int(num1) + int(num2)
    print(answer)

你可能感兴趣的:(python编程快速上手)