python 创建一个计算器,在重置循环时记住输入

python creating a calculator, remembering input while resetting loop

我希望输入能够记住给它的第一个数字,即使你在第二个输入上输入了一些愚蠢的东西。虽然现在显然循环再次开始并再次请求两个输入。有没有简单的方法可以做到这一点?

Calculator 
Give a number: 124 
Give a number: dwa 
This input is invalid. 
Give a number: 12 
Give a number:

虽然我希望它这样做:

Calculator
Give first number: 124
Give second number: dwa
This input is invalid.
Give second number: 12

这是完整的代码:

import math
import sys
print("Calculator")
def main():   
    while True:
        try:
            kek1 = int(input('Give a number: '))
            kek2 = int(input('Give a number: '))
            while True: 
                
                print('(1) +')
                print('(2) -')
                print('(3) *')
                print('(4) /')
                print('(5) sin(number1/number2')
                print('(6) cos(number1/number2)')
                print('(7) Change numbers')
                print('(8) Quit')
                print(f'Current numbers are: {kek1} {kek2}')
                kaka = input("Please select something (1-6):")
                plus = kek1 + kek2
                minus = kek1 - kek2
                times = kek1 * kek2
                divide = kek1 / kek2
                sin = math.sin(kek1/kek2)
                cos = math.cos(kek1/kek2)
                if kaka == "1":
                    print(f'The result is: {plus}')
                if kaka == "2":
                    print(f'The result is: {minus}')
                if kaka == "3":
                    print(f'The result is: {times}')
                if kaka == "4":
                    print(f'The result is: {divide}')
                if kaka == "5":
                    print(f'The result is: {sin}')
                if kaka == "6":
                    print(f'The result is: {cos}')
                if kaka == "7":
                    kek1 = int(input('Give a number: '))
                    kek2 = int(input('Give a number: '))
                if kaka == "8":
                    print("Thank you!")
                    sys.exit(0)
        except SystemExit: 
            sys.exit(0)
        except:
            print("This input is invalid.")
if __name__=="__main__":
    main()

如果您对如何执行此操作有任何想法,那将是一个很大的帮助。

为每个输入使用单独的 try 语句,每个输入都有自己的循环

while True:
      try:
        kek1 = input("First number")
        kek1 = int(kek1)
        break
      except:
        print("Invalid")
        continue
while True:
      try:
        kek2 = input("Second number")
        kek2 = int(kek2)
        break
      except:
        print("Invalid")
        continue

然后进入循环的其余部分。 很抱歉简短回答,但我正在 phone :P

您可以使用 .isnumeric() :

而不是使用 try catch
kek1 = input("First number")
while not kek1.isnumeric() :
    print("This input is invalid.")
    kek1 = input("First number")
kek1 =int(kek1)
kek2 = input("First number")
while not kek2.isnumeric() :
    print("This input is invalid.")
    kek2 = input("Second number")
kek2 =int(kek1)