python 3.3 中的同时赋值
Simultaneous assignment in python 3.3
我是 python 的新手 programming.I 我指的是一本书 "Python Programming: An Introduction to Computer Science." 面向 python 2.Since 我无法下手一本面向python3的基础书,我遇到了如下图的语法问题
>>> def f():
x,y=input("enter two numbers seperated by a comma: ")
s=x+y
d=x-y
print (s,d)
f()
我得到的结果是
>>> f()
enter two numbers seperated by a comma: 2,3
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
f()
File "<pyshell#9>", line 2, in f
x,y=input("enter two numbers seperated by a comma: ")
ValueError: too many values to unpack (expected 2)
我试图在一些书中找到解决方案,例如深入 python 3 和核心 python 编程,但我认为它们对我来说太高级了 now.Please帮助。
input
函数returns一个str
(在Python3),不会自动拆分成两个变量。您需要执行以下操作:
x, y = input('enter two numbers separated by a comma:').split(',')
"input" returns一次只有一个值,所以你不能真正为两个变量赋值。如果您期望两个值,您可能希望通过 space 或任何其他方便的分隔符拆分字符串。
>>> x,y = map(int, input("Enter x and y separated by comma: ").split(',', 1))
Enter x and y separated by comma: 1, 2
>>> x
1
>>> y
2
split(var, 1) - 确保只将字符串分成两部分。
map(int...) - 将每个字符串片段值转换为整数。
我是 python 的新手 programming.I 我指的是一本书 "Python Programming: An Introduction to Computer Science." 面向 python 2.Since 我无法下手一本面向python3的基础书,我遇到了如下图的语法问题
>>> def f():
x,y=input("enter two numbers seperated by a comma: ")
s=x+y
d=x-y
print (s,d)
f()
我得到的结果是
>>> f()
enter two numbers seperated by a comma: 2,3
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
f()
File "<pyshell#9>", line 2, in f
x,y=input("enter two numbers seperated by a comma: ")
ValueError: too many values to unpack (expected 2)
我试图在一些书中找到解决方案,例如深入 python 3 和核心 python 编程,但我认为它们对我来说太高级了 now.Please帮助。
input
函数returns一个str
(在Python3),不会自动拆分成两个变量。您需要执行以下操作:
x, y = input('enter two numbers separated by a comma:').split(',')
"input" returns一次只有一个值,所以你不能真正为两个变量赋值。如果您期望两个值,您可能希望通过 space 或任何其他方便的分隔符拆分字符串。
>>> x,y = map(int, input("Enter x and y separated by comma: ").split(',', 1))
Enter x and y separated by comma: 1, 2
>>> x
1
>>> y
2
split(var, 1) - 确保只将字符串分成两部分。 map(int...) - 将每个字符串片段值转换为整数。