简体   繁体   English

使用python打印用户输入

[英]Print user input using python

I am trying to print the user input of a package name. 我正在尝试打印包名称的用户输入。 I have the following code. 我有以下代码。

packageList = []
package = input("Enter name: ")
while package == '' :
    print("Package name cannot be blank")
    packagename = input("Enter name: ")
    packageList.append(packageName)

print ((packageName) + "added")

I'm not sure what I'm doing wrong. 我不确定自己在做什么错。 An error is being displayed: UnboundLocalError: local variable 'packageName' referenced before assignment 显示错误:UnboundLocalError:分配前引用了本地变量'packageName'

Your code is giving you errors because you're mixing up the use of variables package and packageName , when it looks like you should be using the same variable in both places. 您的代码给您带来了错误,因为您混淆了使用变量packagepackageName ,这似乎是您在两个地方都使用了相同的变量。 The code in aj8uppal's answer corrects most of this (by replacing most references to both variables with packagename ), but he never clearly describes that this is the problem (and he still leaves one reference to package in the while condition). aj8uppal的答案中的代码纠正了大多数问题(通过使用packagename替换对这两个变量的大多数引用),但是他从来没有清楚地描述这是问题所在(他仍然在while条件中留下了对package引用)。

Here's some actually fixed code: 这是一些实际固定的代码:

packageList = []
package = input("Enter name: ")

while package == '' :
    print("Package name cannot be blank")
    package = input("Enter name: ")               # assign to package variable here

packageList.append(package)                       # unindent, and use package again

print ((package) + "added")                       # use package rather than packageName

Your packageList.append(packageName) should not be in the while loop. 您的packageList.append(packageName)不应在while循环中。 Your while loop just makes sure the input is not blank, so we don't want to append it. 您的while循环只是确保输入不为空,因此我们不想附加它。

What you are doing is not raising the error, so packageName doesn't exist. 您正在执行的操作不会引发错误,因此packageName不存在。 Therefore, you are printing an uncalled variable. 因此,您正在打印一个未调用的变量。

Also, you call package = input(...) , but if there is an error, you call packagename = input(...) . 另外,您调用package = input(...) ,但是如果发生错误,则调用packagename = input(...) You probably want to change that. 您可能想要更改它。

Here is your edited code: 这是您编辑的代码:

packageList = []
packagename = input("Enter name: ")
while package name == '' :
    print("Package name cannot be blank")
    packagename = input("Enter name: ")

packageList.append(packageName)
print ((packageName) + "added")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM