[Python]ValueError: not enough values to unpack 和 Possible unbalanced tuple unpacking with sequence
代码:
from sys import argvscript, user_name = argv
prompt = '> 'print(f"Hi {user_name}, I`m the {script} script.")
print("I`d like to ask you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)print(f"Where do you live {user_name}?")
lives = input(prompt)print("What kind of computer do you have?")
computer = input(prompt)print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}. No sure where that is.
And you have a {computer} computer. Nice.
""")
错误:
Traceback (most recent call last):File "E:\自学\python\project\ex13.py", line 3, in script, first, second, third = argv #解包
ValueError: not enough values to unpack (expected 4, got 1)
原因分析:
首先错误提示我没有按要求输入值,通过排除确定问题出在argv,于是在文档中查看argv。
# variables with complex valuesargv = [] # real value of type skipped
argv是sys模块中的函数,它本质上是一个列表函数。由此可见,我在命令行少打了3个参数,于是在命令行加上参数,并再次运行
运行结果:
PS C:\Users\31261> cd E:\自学\python\project
PS E:\自学\python\project> python .\ex13.py 1 two 三
The script is called: .\ex13.py
Your first variable is: 1
Your second variable is: two
Your third variable is: 三
运行成功,但是编辑器又报错了
错误:

原因分析:
翻译下就是:元组在按顺序解包时可能存在不平衡:左侧有4个,右侧有0个。
显然这是由于用argv创建变量时,“=”两边数量不对称导致的。
解决方案:
在解包时加上以下注释:
script, first, second, third = argv # pylint: disable=unbalanced-tuple-unpacking
参考文章:
ValueError: not enough values to unpack (expected 4, got 1) Python(笨办法学Python3)
Possible unbalanced tuple unpacking with sequence
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
