为什么会出现语法错误?

时间:2014-03-26 14:21:12

标签: python python-3.x printing

这是我的代码(其中IDLE突出显示' print'并说'无效的语法':

import random
initial_val = 10
attributes = str("Character 1's Strength: ",(random.randint(1,12)/random.randint(1,4) +         initial_val), \
"\nCharacter 1's Skill: ",(random.randint(1,12)/random.randint(1,4) + initial_val), \
"\n\nCharacter 2's Strength: ",(random.randint(1,12)/random.randint(1,4) + initial_val), \
"\nCharacter 2's Skill: ",(random.randint(1,12)/random.randint(1,4) + initial_val)
print(attributes)
file = open("Attribute.txt", "w")
file.write(attributes)
file.close()
input("\n\nPress enter to exit")

为什么这样做?它可能非常明显,但我是编程新手。 非常感谢

1 个答案:

答案 0 :(得分:2)

前面的行缺少结束)括号:

attributes = str("Character 1's Strength: ",(random.randint(1,12)/random.randint(1,4) +         initial_val), \
"\nCharacter 1's Skill: ",(random.randint(1,12)/random.randint(1,4) + initial_val), \
"\n\nCharacter 2's Strength: ",(random.randint(1,12)/random.randint(1,4) + initial_val), \
"\nCharacter 2's Skill: ",(random.randint(1,12)/random.randint(1,4) + initial_val)

str(函数调用从未关闭。

使用字符串格式和"""三引号字符串代替更易读的声明:

attributes = """\
Character 1's Strength: {}
Character 1's Skill: {}

Character 2's Strength: {}
Character 2's Skill: {}
""".format(
    random.randint(1, 12) / random.randint(1, 4) + initial_val,
    random.randint(1, 12) / random.randint(1, 4) + initial_val,
    random.randint(1, 12) / random.randint(1, 4) + initial_val,
    random.randint(1, 12) / random.randint(1, 4) + initial_val)