好吧,如果你在Python中运行下面的代码,它只打印问题变量的第一个字母,但是它打印其余的就好了。只有在我的Python脚本中有for循环函数时才会发生这种情况。关于如何修复它的任何想法让我得到整个问题变量打印?
import random
global nouns
global verbs
global question
nouns =["website","browser","server","printer","computer","disc","software","desktop","a internet connection","the internet","site","forum","smf forum","phpbb forum","money making website","money making blog","firefox","chrome","opera","",""]
verbs = ["cosntruct","build","create","design","update","reconstruct","clean","fix","repair","browse","discover","formualte","form","plan"]
question = ["How do I","How would I", "how do i", "how would i", "what is a", "what is the", "how would i", "how should i", "when does a", "When does a", "How should I"]
def q_gen():
global nouns
global verbs
global question
noun_pick = random.choice(nouns)
verb_pick = random.choice(verbs)
question = random.choice(question)
create = question+" "+verb_pick+" "+noun_pick+"?"
print create
num_count = 0
for num_count in range(1, 100):
num_count=num_count+1
q_gen()
答案 0 :(得分:9)
这种情况正在发生,因为您在此行覆盖了全局变量question
,其中一个值为question
:
question = random.choice(question)
这意味着会发生以下情况:
question = [...] # question is a list of strings
question = random.choice(question) # question is a single string
question = random.choice(question) # question is a character from that string
解决方案是用其他东西替换变量名:
question_pick = random.choice(question)
create = question_pick+" "+verb_pick+" "+noun_pick+"?"
您可以对代码进行一些改进。这些更改可以提高可读性,提高性能,并使您的代码更加惯用。
声明变量。这不是在Python中完成的。分配给变量时,它会弹出。这包括for
语句
global a # Unnecessary and dangerous
a = 0
迭代。当您说for x in ...
时,您一次又一次地执行一套语句。每次通过套件时,x
都会分配给下一个项目。 您无需自己分配或增加x
。
x = 0 # Not necessary; x is about to be assigned to the first
# element of range(10), which is 0
for x in range(10):
...
x = x + 1 # Not necessary; as soon as this statement is done,
# x will be assigned to the next element of range(10)
<强>全局强>
您不需要它们。当您使用name = ...
时,您正在创建模块级变量。每个变量都可以在模块中的任何位置访问(即,在当前的.py文件中)
他们很危险。如果其他一些模块正在使用名为name
的变量,那么您可能会遇到令人讨厌的惊喜。如果您计划进一步开发此代码,请记住这一点。
字符串格式化。我们的想法是创建一个模板,然后将标记放在您想要放入值的位置。%s
标记表示“将下一个变量解释为字符串并把它放在这里“。
create = "%s %s %s?" % (question, verb_pick, noun_pick)
样式。 Python有一个称为PEP 8的样式指南。确保您的代码符合PEP 8,使其可读并使其看起来与其他Python代码更相似。例如,运算符应该被一个空格包围,逗号后面应该有一个空格等。
答案 1 :(得分:1)
此行修改您的全局变量:
question = random.choice(question)
在第一次之后,random.choice被赋予一个字符串而不是一个列表,所以它随机选择一个字母。从那时起,random.choice被赋予一个字符串,因此它总是使用相同的字母。
发生此错误是因为您不必要地使用了global
。在没有全局的情况下编写它会产生编译错误,因为问题被修改了。
以下是没有global
的代码:
import random
nouns =["website","browser","server"]
verbs = ["construct","build","create"]
question = ["How do I","How would I", "how do i"]
def q_gen():
noun_pick = random.choice(nouns)
verb_pick = random.choice(verbs)
question_pick = random.choice(question)
create = question_pick+" "+verb_pick+" "+noun_pick+"?"
print create
for num_count in range(1, 100):
q_gen()