我正在尝试将代码(用于注册用户)转换为函数,但它给出了 output = None 而不是连接的字符串 (new_user_name + ", " + new_password)。谁能告诉我我犯了什么错误,代码本身在它不是函数时已经可以工作了。
def reg_user ():
#Input from the admin to enter the user name and password for the new user
new_user_name = input("Enter new Username: ").strip()
new_password = input("Enter new Password: ").strip()
confirm_new_password = input("Re-enter new Password: ").strip() #Password confirmation
while new_password != confirm_new_password:
print("Password does not match. Ensure you have put the same password")
print()
new_password = input("Enter new Password: ").strip()
confirm_new_password = input("Re-enter new Password: ").strip()
if new_password == confirm_new_password:
return (new_user_name + ", " + new_password)
new_user = reg_user()
print(new_user)
OUTPUT = None
Desired output = eg. (Sanele, 595dasdf)
答案 0 :(得分:0)
您在缩进时犯了一个小错误:
def reg_user ():
#Input from the admin to enter the user name and password for the new user
new_user_name = input("Enter new Username: ").strip()
new_password = input("Enter new Password: ").strip()
confirm_new_password = input("Re-enter new Password: ").strip() #Password confirmation
while new_password != confirm_new_password:
print("Password does not match. Ensure you have put the same password")
print()
new_password = input("Enter new Password: ").strip()
confirm_new_password = input("Re-enter new Password: ").strip()
return (new_user_name + ", " + new_password) # Has to be one tab less
new_user = reg_user()
print(new_user)
OUTPUT = None
# Desired output = eg. (Sanele, 595dasdf)
答案 1 :(得分:0)
正如其他人所说,您只需将 if
语句标识减少一级即可修复脚本。
但是,您的代码有一些糟糕的编码实践,比如它是WET(您编写所有内容两次)而不是保持它DRY( 不要重复自己)。这是我的版本:
def reg_user ():
new_user_name = input("Enter new Username: ").strip()
while True:
new_password = input("Enter new Password: ").strip()
confirm_new_password = input("Re-enter new Password: ").strip()
if new_password == confirm_new_password:
return new_user_name + ", " + new_password
print("Password does not match. Ensure you have put the same password")
new_user = reg_user()
print(new_user)