ValueError: invalid literal for int() with base 10: 'q'

相识满天下,知心能几人

源码

def even_odd():
    n = input('please input a num: ')
    n = int(n)
    if n<22:
        print('you are young')
    else:
        print('you are old')

def main():
    while(True):
        even_odd()
        
if __name__=='__main__':
    main()

报错

================= RESTART: C:/Users/Lin/Desktop/test/test.py =================
please input a num: q
Traceback (most recent call last):
  File "C:/Users/Lin/Desktop/test/test.py", line 14, in <module>
    main()
  File "C:/Users/Lin/Desktop/test/test.py", line 11, in main
    even_odd()
  File "C:/Users/Lin/Desktop/test/test.py", line 3, in even_odd
    n = int(n)
ValueError: invalid literal for int() with base 10: 'w'
>>> 

原因

input函数接收用户输入返回的是一个字符串,即便接收的是数字,返回的也是纯数字的字符串。
int函数只能转换纯数字的字符串为整型,上面就是因为输入了字母 q才报错

补坑

如果将 '2.6' 强行转换为 int 也不可,因为有小数点,不是纯数字。可以使用 float('2.6') 进行转换。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值