0%

python2 python3 不同记录

记录下Python2和Python3的不同

input 区别

python2

有 input 和 raw_input 两个函数

input 传入值的时候 会区别 类型

传值给a ,1的时候,a的值就为1,为数值型变量

1
2
3
4
>>> a = input("input:")
input:1
>>> a
1

传给a HHH 的时候会报错,因为没有定义

1
2
3
4
5
6
>>> a = input("input:")
input:HHH
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'HHH' is not defined

如果要传字符串要用 “HHH”,这个时候a为字符串变量

1
2
3
4
5
>>> a = input("input:")
input:"HHH"
>>> a
'HHH'
>>>

raw_input 传递进去的统一被认为字符串

传值给a ,1的时候,a的值为1,为字符串

1
2
3
4
>>> a = raw_input("input:")
input:1
>>> a
'1'

传值给a ,HHH的时候,a的值为HHH,也是为字符串
1
2
3
4
>>> a = raw_input("input:")
input:HHH
>>> a
'HHH'

传值给a ,”HHH” 的时候,a的值为”HHH”,也是为字符串
1
2
3
4
5
>>> a = raw_input("input:")
input:"HHH"
>>> a
'"HHH"'
>>>

python3

只保留了 input 函数
而且这个函数和 python2里面的raw_input 是一个意思

一个 python 程序输入两个值进行计算

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-

a = input("please input a: ")

print("Input A:{0}".format(a))

b = input("please input b: ")

print("Input B:{0}".format(b))

print("{0} * {1} = {2}".format(a,b,a*b))

Python2 的结果是这样

1
2
3
4
5
6
[web@localhost 1.1]$ python2 calc.py
please input a: 1
Input A:1
please input b: 1
Input B:1
1 * 1 = 1

Python3 的结果是这样的

1
2
3
4
5
6
7
8
9
[web@localhost 1.1]$ python3 calc.py
please input a: 1
Input A:1
please input b: 1
Input B:1
Traceback (most recent call last):
File "calc.py", line 12, in <module>
print("{0} * {1} = {2}".format(a,b,a*b))
TypeError: can't multiply sequence by non-int of type 'str'

不能用字符串进行乘法运算

说明python3的input 函数接受的是字符串

需要对字符串进行转义

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-

a = input("please input a: ")

print("Input A:{0}".format(a))

b = input("please input b: ")

print("Input B:{0}".format(b))

print("{0} * {1} = {2}".format(a,b,int(a)*int(b))

欢迎关注我的其它发布渠道