Python 中如何将用户输入读取为整数

Jinku Hu 2023年1月30日 2018年3月4日
  1. Python 2.x 将用户输入读取为整数
  2. Python 3.x 中将用户输入读取为整数
Python 中如何将用户输入读取为整数

Python 2.x 将用户输入读取为整数

Python 2.7 有两个函数来读取用户输入,即 raw_inputinput

raw_input 将用户输入作为原始字符串读取,其返回值类型很简单,是字符串类型 stringinput 获取用户输入,然后评估字符串的内容,并返回评估结果。

例如,

>>> number = raw_input("Enter a number: ")
Enter a number: 1 + 1
>>> number, type(number)
('1 + 1', <type 'str'>)

>>> number = input("Enter a number: ")
Enter a number: 1 + 1
>>> number, type(number)
(2, <type 'int'>)
友情提示

Python 2.x 中使用 input 时请三思,它有可能产生安全问题,因为它会评估编译用户输入的任意内容。举个例子,假设你已经调入了 os,然后你要求用户输入,

>>> number = input("Enter a number: ")
Enter a number: os.remove(*.*)

你输入的 os.remove(*.*) 会被执行,它会删除工作目录中的所有文件,而没有任何提示!

Python 3.x 中将用户输入读取为整数

raw_input 在 Python 3.x 中已经被弃用,它在 Python 3.x 中被替换为 input。它只获取用户输入字符串,但由于上述安全风险,因此不评估和执行字符串的内容。因此,你必须将用户输入从字符串显性转换为整数。

>>> number = int(input("Enter a number: "))
Enter a number: 123
>>> number
123
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相关文章 - Python Input