为什么我的打印语句会产生SyntaxError:无效的语法?

时间:2019-03-20 09:51:15

标签: python

有人知道如何进行这项工作吗? (在python中) 顺便说一句,我是初学者:)

import random
def roll():
    input1 = input("Player1, type 'ROLL' to roll.")
    if (input1 == "ROLL"):
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        print("You rolled a " + dice1() + " and a " + dice2() ".")

    else:
        pass

roll()

我得到:

  File "main.py", line 9
    print("You rolled a " + dice1() + " and a " + dice2() ".")
                                                            ^
SyntaxError: invalid syntax

我还希望它重复“ Player1,键入'ROLL'滚动”。如果输入不等于ROLL 请:)谢谢

5 个答案:

答案 0 :(得分:3)

您附近的语法无效:

print("You rolled a " + dice1() + " and a " + dice2() ".")

使用string format

替换

print("You rolled a " + dice1() + " and a " + dice2() ".")

使用此

print("You rolled a {} and {}".format(dice1,dice2))
  

注意:除非while loopuser-input匹配,否则您可以使用input继续服用ROLL

因此

import random

def roll():
    while True:
        input1 = input("Player1, type 'ROLL' to roll.")
        if input1 == "ROLL":
            dice1 = random.randint(1,6)
            dice2 = random.randint(1,6)
            print("You rolled a {} and {}".format(dice1, dice2))
            break  
roll()

输出

Player1, type 'ROLL' to roll.whaaaat?
Player1, type 'ROLL' to roll.okay
Player1, type 'ROLL' to roll.roll
Player1, type 'ROLL' to roll.ROLL
You rolled a 2 and 2

答案 1 :(得分:1)

typedef中存在语法错误。

两个print值都必须使用int强制转换为字符串。

str()dice1不是函数,因此我们不能在它们旁边写上dice2

()

应该是

print("You rolled a " + dice1() + " and a " + dice2() ".")

最好使用任何字符串附带的print("You rolled a " + str(dice1) + " and a " + str(dice2) + ".") 函数。

format

答案 2 :(得分:0)

整个功能应该是:

import random
def roll():
    input1 = input("Player1, type 'ROLL' to roll.")
    if (input1 == "ROLL"):
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        print("You rolled a %s and a %s." % (dice1,dice2))

    else:
        pass

roll()

如果要显示两个变量dice1dice2

使用:

print("You rolled a %s and a %s." % (dice1,dice2))

代替:

print("You rolled a " + dice1() + " and a " + dice2() ".")

答案 3 :(得分:0)

您在打印语句中忘记了逗号或+。 您也将变量dice1 dice2称为函数。

import random

def roll():
    input1 = input("Player1, type 'ROLL' to roll. ")
    print(input1)
    if input1 == 'ROLL':
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        print("You rolled a " + str(dice1) + " and a " + str(dice2) + ".")
    else:
        pass

roll()

答案 4 :(得分:-2)

Python的random.randint返回一个整数,因此您无需调用dice1dice2变量。 替换此行:

print("You rolled a " + dice1() + " and a " + dice2() ".")

与此:

print("You rolled a " + dice1 + " and a " + dice2 ".")

Python random module的参考