gpt4 book ai didi

python - 初学者Python用户: trouble with error code - too many values to unpack (expected 2)

转载 作者:行者123 更新时间:2023-12-01 05:31:05 24 4
gpt4 key购买 nike

该程序旨在接收用户名和密码并验证它们。我现在只查看用户名部分。

这是我的功能:

def valid_username(username):
if not username.isalpha():
reason = ('username can only contain alpha numeric numbers')
return reason

numupper =0
for c in username:
if not c.isupper():
numupper = numupper + 1

if numupper <= 0:
reason=('username must contain at least one uppercase character')
return reason

numlower =0
for c in username:
if not c.islower():
numlower = numlower + 1

if numlower <= 0:
reason=('username must contain at least one lowercase character')
return reason

if len(username)<8:
reason = ('username must be greater than 8 characters')
return reason

numdigit=0
for c in username:
if not c.isdigit():
numdigit = numdigit + 1

if numdigit <= 0:
reason= ('username must contain at least one number')
return reason

这是我的程序:

import uservalidation

# get a username from the user
username = input("Username: ")

# validate username
result, reason = uservalidation.valid_username(username)

# if it isn't valid we should tell them why
if not(result):
print (reason)

(the next else is the password part)

但我收到此错误代码:

Traceback (most recent call last):
File "/Users/katiemoore/Documents/MooreKatie_assign9.py", line 7, in <module>
result, reason = uservalidation.valid_username(username)
ValueError: too many values to unpack (expected 2)

我真的不知道这是什么意思,有人可以帮忙吗?

最佳答案

函数valid_username仅返回一个字符串reason。但是您在函数调用时收到两个参数。因此出现了错误。因此,返回一个空字符串是合适的,因为分配给 result 变量将是正确的

而不是

return reason

使用

return '',reason

这会起作用

关于python - 初学者Python用户: trouble with error code - too many values to unpack (expected 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20296528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com