So I'm trying to make a program for my Chinese class that gives me random characters to make a sentence with, but I keep getting the same error no matter what I try. Can someone tell me what is wrong with my code and how to fix it? Thank you!
#Chinese vocab character generator project
import random
characters = ['谁', '什么', '工作', '名字', '星期', '工程师', '做', '你', '您', '好', '多', '大', '姓', '学', '出生', '书', '年', '年纪', '妈妈', '爸爸', '上', '下', '我', '是', '太', '院', '电脑', '电话', '号', '吗', '吧', '春节', '在', '那', '哪', '哪儿', '爷爷', '老', '的', '号码', '手机', '公司', '就', '巧', '属', '先生', '中', '今', '天', '人', '岁', '一生']
numbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万']
particles = ['了', '的', '吧', '吗', '呢', '什么']
print("Welcome to the Random Character Generator!")
nr_characters= int(input("How many characters would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
nr_particles = int(input(f"How many particles would you like?\n"))
character_list = ("")
for characters in range(0, nr_characters 1):
character_list = characters[random.randint(0,30)]
for particle in range(0, 7 1):
character_list = particles[random.randint(0,5)]
for number in range(0, nr_numbers 1):
character_list = str(numbers[random.randint(0,13)])
print("Your characters are: " character_list)
CodePudding user response:
You're overwriting the characters
variable defined at the top with the for characters in ...
loop. Rename the variable in the first for loop:
#Chinese vocab character generator project
import random
characters = ['谁', '什么', '工作', '名字', '星期', '工程师', '做', '你', '您', '好', '多', '大', '姓', '学', '出生', '书', '年', '年纪', '妈妈', '爸爸', '上', '下', '我', '是', '太', '院', '电脑', '电话', '号', '吗', '吧', '春节', '在', '那', '哪', '哪儿', '爷爷', '老', '的', '号码', '手机', '公司', '就', '巧', '属', '先生', '中', '今', '天', '人', '岁', '一生']
numbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万']
particles = ['了', '的', '吧', '吗', '呢', '什么']
print("Welcome to the Random Character Generator!")
nr_characters= int(input("How many characters would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))
nr_particles = int(input(f"How many particles would you like?\n"))
character_list = ("")
for character in range(0, nr_characters 1):
character_list = characters[random.randint(0,30)]
for particle in range(0, 7 1):
character_list = particles[random.randint(0,5)]
for number in range(0, nr_numbers 1):
character_list = str(numbers[random.randint(0,13)])
print("Your characters are: " character_list)
CodePudding user response:
I believe there is an error in this line:
character_list = characters[random.randint(0,30)]
The problem is you want to access the characters
list, but you have also defined the same variable name for the loop. This is causing variable overwriting (mentioned by @sumit). Just change the variable name in the loop like this:
for character in range(0, nr_characters 1):