2014-03-26 235 views
0

這是我的代碼(其中IDLE亮點「打印」,並說「無效語法」:爲什麼會出現語法錯誤?

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") 

它爲什麼這樣做很可能是非常明顯的,但我是新來的編程 非常感謝。

回答

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)