我是python的新手,为什么冒号是无效的语法?

时间:2019-12-16 14:26:14

标签: python

我是python的新手,正在尝试构建头尾系统。但是,每当我在if语句的末尾添加冒号时,它就将其声明为无效语法。不过,当我删除冒号时,它会指出下一行的语法无效。

import random

def coinToss (
coinFlip = random.choice([1, 2])

  if coinFlip == 1:
    print("You got Heads!")
  else
    print("You got Tails!")
):

 usrFlip = input("Press Enter to Flip a Coin")

 if usrFlip == str:
   coinToss():

3 个答案:

答案 0 :(得分:2)

您有很多语法和缩进错误。这是更正的代码:

import random

def coinToss ():
  coinFlip = random.choice([1, 2])
  if coinFlip == 1:
    print("You got Heads!")
  else:
    print("You got Tails!")


usrFlip = input("Press Enter to Flip a Coin")

if usrFlip == str:
  coinToss()

答案 1 :(得分:0)

这不是在python中定义函数的方式。

这是正确的方法:

import random

def coinToss():
    coinFlip = random.choice([1, 2])

    if coinFlip == 1:
        print("You got Heads!")
    else:
        print("You got Tails!")

usrFlip = input("Press Enter to Flip a Coin")

if type(usrFlip) == str:
    coinToss()

答案 2 :(得分:-1)

import random

def coinToss():
    coinFlip = random.choice([1, 2])

    if coinFlip == 1:
        print("You got Heads!")
    else:
        print("You got Tails!")

usrFlip = input("Press Enter to Flip a Coin")

if type(usrFlip) == str:
    coinToss()