Alright, if you run the below code in Python it only prints the first letter of the question variable, however it prints the rest just fine. This only happens \when I have the for loop function inside of my Python script. Any ideas on how to fix it so I get the entire question variable printing?
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()
This is happening because you are overwriting the global variable
questionwith one of the values ofquestionat this line:This means that the following occurs:
The solution is to replace the variable name with something else:
A few notes on style
There are a number of improvements you can make to your code. These changes could improve readability, improve performance, and otherwise make your code more idiomatic.
Declaring variables. This is not done in Python. When you assign to a variable, it springs into existence. This includes
forstatementsIteration. When you say
for x in ..., you’re executing a suite of statements again and again. Each time you go through the suite,xis assigned to the next item. You do not need to assign or incrementxyourself.Globals.
You don’t need them. When you use
name = ..., you are creating a module-level variable. Each variable is accessible everywhere in your module (that is, in your current .py file)They’re dangerous. If some other module is using a variable named
name, you could be in for a nasty surprise. Keep this in mind if you plan to develop this code further.String formatting. The idea is that you create a template, then put tags where you want values dropped in. The
%stag means “Interpret the next variable as a string and put it here”.Style. Python has a style guide known as PEP 8. Making sure your code adheres to PEP 8 keeps it readable and makes it look more similar to other Python code. For example, operators should be surrounded by a single space, there should be a single space after a comma, etc.