用Python写一段代码,实现接收用户输入两个的数字并输出数字相加后的结果,要求用户输入任何内容程序不会报错

分别采用基础方法和异常处理方法实现。

基础方法代码如下:

num1 = input('请输入数字1:')
if num1.strip() == '':
    print('输入错误。')
    exit()
elif num1[0] != '.':
    for i in num1:
        if not('0' <= i <= '9' or i == '.'):
            print('输入错误。')
            exit()
    num1 = float(num1)
else:
    print('输入错误。')
    exit()
num2 = input('请输入数字2:')
if num2.strip() == '':
    print('输入错误。')
    exit()
elif num2[0] != '.':
    for i in num2:
        if not('0' <= i <= '9' or i == '.'):
            print('输入错误。')
            exit()
    num2 = float(num2)
else:
    print('输入错误。')
    exit()
su = num1 + num2
su = [str(su), int(su)][int(su) == su]
num1 = [str(num1), int(num1)][int(num1) == num1]
num2 = [str(num2), int(num2)][int(num2) == num2]

print('{} + {} = {}'.format(num1,num2,su))

采用异常处理的代码如下:

try:
    num1 = float(input('请输入数字1:'))
    num2 = float(input('请输入数字2:'))
except ValueError:
    print('输入的不是数字。')
    exit()
s = num1 + num2
s = [str(s),int(s)][int(s)==s]
num1 = [str(num1),int(num1)][int(num1)==num1]
num2 = [str(num2),int(num2)][int(num2)==num2]

print('{} + {} = {}'.format(num1, num2, s))

 

你可能感兴趣的:(Python基础,Python基础)