您的位置:首页 >python什么时候用input_Python input 使用
发布于2026-05-02 阅读(0)
扫一扫,手机访问
在Python的版本演进中,input函数的行为变化堪称一个经典的“坑”。不少从Python 2迁移到Python 3的开发者,都曾在这里栽过跟头。今天,我们就来彻底厘清这个差异,确保你的代码在不同版本间都能顺畅运行。
一句话概括:在Python 3中,input()函数完全取代了Python 2中的raw_input()。这意味着,Python 3的input()总是将用户的输入作为字符串(str)返回,而Python 2中的input()则有着完全不同的行为。
先来看一个Python 3.5中的标准用法:
1 #!C:\Program Files\Python35/bin
2 #-*- conding:utf-8 -*-
3 #author: Frank
4 user_input = input("please input your name:") #input 函数的使用
5 print("User input Msg:", user_input)6
7 #显示结果
8>>>please input your name: Frank9User input Msg:Frank
这段代码在Python 3中运行良好。用户输入“Frank”,程序将其作为字符串接收并打印出来。整个过程直观且符合预期。
然而,如果把同样的思维带到Python 2.7,麻烦就来了。在Python 2.7的环境中,如果你错误地使用了input,会看到如下场景:
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>> user_input = input("your name:") # For python2.7 , 这是错误的写法
your name:is
Traceback (most recent call last):
File "", line 1, in
File "", line 1
is
^
SyntaxError: unexpected EOF while parsing
看到了吗?程序直接抛出了一个语法错误(SyntaxError)。这是因为Python 2中的input()函数会试图将用户的输入当作一个Python表达式来求值。当你输入“is”时,它试图将其解析为代码,自然就失败了。
那么,在Python 2.7中正确的打开方式是什么呢?答案是使用raw_input:
>> user_input = raw_input("your name:")# For python 2.7 , raw_input 是正确的.
your name: Frank
>> print user_input
Frank
raw_input才是那个老老实实把输入当作原始字符串返回的函数,这也正是Python 3中input函数的行为。
在python3.0 中, input 默认接受的都是 string。这是一个重要的安全特性,但也带来了新的注意事项:当你需要其他数据类型时,必须进行显式转换。
举个例子,下面的代码将出错:
# -*- conding:utf-8 -*-
# author: Frank
name = input("please input your name:")
age = input("please input your age:") # 注意,这里age是字符串!
job = input("please input your job:")
# 这里用了一个变量Msg,多行模式
Msg = '''
Information of user Frank:%s
------------------------
Name : %s
Age : %d # 格式化符号 %d 期待一个整数(decimal)
Job :%s
------------End---------
''' %(name,name, age, job)
print(Msg)
运行这段代码,结果会如何?
please input your name: frank bian
please input your age:34
please input your job:it
Traceback (most recent call last):
File "", line 16, in
TypeError: %d format: a number is required, not str
错误信息非常明确:TypeError: %d format: a number is required, not str。格式化字符串中的%d要求一个整数,但我们传递的age变量却是一个字符串。这正是因为Python 3的input()无论你输入什么数字,都会先把它变成字符串“34”,而不是整数34。
解决办法很简单:在需要数值的时候,使用int()或float()函数进行强制转换。例如:age = int(input(“please input your age:”))。
总结一下,这个差异看似微小,却直接影响代码的兼容性和健壮性。理解它,是编写跨版本Python代码的基本功之一。
下一篇:JAVA 入门
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9