UCI-ICS32Python第一周笔记

本文探讨了如何通过在代码中实施错误处理和输入验证,以防止因用户意外行为导致的程序崩溃。作者介绍了使用try-except块、is_int函数和适当的数据类型检查,确保代码在面对非预期输入时仍能正常运行。
摘要由CSDN通过智能技术生成

错误常常发生,可能是代码的逻辑出问题,也可能是自己不能控制的外部原因。

这里便会谈到我们该如何去保护我们的代码,避免可预见错误和不可预见场景,举个例子来说明。


>>> n = int(input("What is your age? "))
What is your age? 12

写代码时很自然的会想到是填数字,但是会出现意外情况。


>>> n = int(input("What is your age? "))
What is your age? twelve

也就是用户不填阿拉伯数字,填英文(因为这是国外)

就会出错

Trackeback (most recent call last):
  File "<pyshell#1>, line 1, in <module>
	  n = int(input("What is your age? "))
ValueError: invalid literal for int() with base 10: 'twelve'

所以我们该怎么做才能保证我们的代码在用户出现我们意想不到的行为正常工作呢?

我们先从一个模块开始

# error_handling.py

def run():
  a = input()
  b = input()

if __name__ == '__main__':
  run()

然后加入一个函数

# error_handling.py

def add(a, b):
  return int(a) + int(b)

def run():
  a = input()
  b = input()
  r = add(a,b)
  print(r)

if __name__ == '__main__':
  run()

当我们输入我们理想的阿拉伯数字当然不会出错,但是如果是入twelve就会有很大问题

Traceback (most recent call last):
  File "/usr/lib64/python3.10/idlelib/run.py", line 580, in runcode
    exec(code, self.locals)
  File "/home/mark/ics32/error_handling.py", line 12, in <module>
    run()
  File "/home/mark/ics32/error_handling.py", line 8, in run
    r = add(a,b)
  File "/home/mark/ics32/error_handling.py", line 3, in add
    return int(a) + int(b)
ValueError: invalid literal for int() with base 10: 'twelve'

这里是想将输入值换为整数。这里有几种方法,我们可以尝试将输入的值确实地转为整数,但这会使代码变得很多。最简单地办法是,解决可能地问题。试试try...except

用法:

try:
    # Operation to perform
except:
    # Operation to perform if an error occurs on the first operation
else:
    # Operation to perform in an error does not occur on the first operation
finally:
    # Operation to perform regardless of what happens to the first operation

 可以变成

# error_handling.py

if __name__ == '__main__':
  try:
    run()
  except:
    print("An error has occurred")

这样当然可以运行不出错,但是当代码越来越复杂,这样会很不方便,所以我们直接在有问题的地方进行尝试。

# error_handling.py

def add(a, b):
  r = 0
  try:
    r = int(a) + int(b)
  except:
    print("An error has occurred")
  return r 

def run():
  a = input()
  b = input()
  r = add(a,b)
  print(r)

if __name__ == '__main__':
  run()

但是这样也有2点不好:(1)我们不知道是那个变量不能转换(2)用户是在run函数出问题,我们却在add函数上改进

所以可以单独加一个函数


def is_int(val):
  try:
    int(val)
    return True
  except ValueError:
    return False

变成

# error_handling.py

def is_int(val):
  try:
    int(val)
    return True
  except ValueError:
    return False

def add(a, b):
  return int(a) + int(b)

def run():
  a = input()
  b = input()
  if is_int(a) == False or is_int(b) == False:
    print("Unable to perform operation with supplied values")
  else:
    r = add(a,b)
    print(r)

if __name__ == '__main__':
  run()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值