python input 整数_如何在列表中输入整数值(python3.x)?

REPL演示

好吧,因为输入将被解析为字符串,int只能将数字字符串强制为整数。。。如果输入错误,你就麻烦大了,因为它会立即停止你的程序。在

我建议使用while循环和try-except异常语句进行错误处理。在

python2.x注意事项:使用raw_input,因为如果传递没有字符串引号的字符,input将导致NameError: name is not defined。在>>> my_array = [] # camelCase is not the convention in Python

>>>

>>> array_length = None

>>> while array_length is None:

... try:

... array_length = int(input("Please enter the length of array you wish to create: "))

... except ValueError:

... print("Invalid input - please enter a finite number for the array length.")

...

Please enter the length of array you wish to create: 4

>>>

>>> print(array_length)

4

>>> while len(my_array) < array_length:

... try:

... my_array.append(int(input()))

... except ValueError:

... print("Invalid input - please enter a number!")

...

1

abc

Invalid input - please enter a number!

2

3

4

>>>

>>> print(my_array)

[1, 2, 3, 4]

作为脚本运行

^{pr2}$

在我的控制台中运行:$ python3 input-program.py

Please enter the length of array you wish to create: 4

Your array length is 4.

1

2

3

4

Your array is [1, 2, 3, 4]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值