简体   繁体   English

为什么会出现语法错误?

[英]Why does this come up with a syntax error?

This is my code (of which IDLE highlights 'print' and says 'Invalid Syntax': 这是我的代码(其中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")

Why does it do this? 为什么这样做? It's probably extremely obvious, but I'm new to programming. 这可能非常明显,但我是编程新手。 Many Thanks 非常感谢

The preceding line is missing a closing ) parenthesis: 一行缺少结束)括号:

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)

The str( function call was never closed. str(函数调用从未关闭。

Use string formatting and """ triple-quoted string instead for a far more readable declaration: 使用字符串格式和"""三重引号”字符串代替更易读的声明:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 Python 中会出现此 Traceback 错误? - Why does this Traceback error come up in Python? 为什么这一段代码出错了,而另一段代码没有出错? - Why does this one chunk of code come up with error but the other one doesn't? 为什么我的第一列出现“'DataFrame' 对象没有属性'date_time'”错误? - Why does a "'DataFrame' object has no attribute 'date_time'" error come up for my first column? 我的PySide2脚本中的语法错误从何而来? - Where does this syntax error in my PySide2 script come from? 为什么会出现“ TypeError:'undefined'对象不可调用”的问题? - Why does “TypeError: 'undefined' object is not callable” come up? 为什么代码为我的两个变量提出了NameError? - Why does the code come up with a NameError for two of my variables? 为什么使用 time.sleep 时会出现“none”? - Why does “none” come up when using time.sleep? 试图了解为什么我不断出现此错误 - trying to understand why I keep getting this error come up MySQL 查询中的语法错误:检查“?”附近的语法。 “?”在哪里? 来自? - Syntax error in MySQL query: check the syntax near '?'. Where does the '?' come from? 为什么我的 if 循环会抛出语法错误? - Why is my if loop throwing up a syntax error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM