【问题标题】:Identify python errors识别python错误
【发布时间】:2017-11-08 19:06:19
【问题描述】:

有人可以帮忙找出这个循环中的错误吗?

我对 Python 完全陌生。

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print p + " rolls a " + dice + " out of " + str(x*2)
    if dice > x: 
       print p + " wins!"
    elif dice == x:
           print p + "gets a tie."
    else:
           print p + " loses."}

谢谢!!

【问题讨论】:

  • 它引发了哪些错误?为什么你的最后一行末尾有一个}?为什么 x 在你的 if 语句中大写?
  • 第 1 行引发的错误 NameError: player not defined。 X 在练习中大写(这是其中的学习练习之一。最后的“}”是我的错误。
  • 你还没定义什么是玩家???究竟是什么玩家??是随机数列表吗??
  • 您是否事先定义了players?您应该使用tour 并提供Minimal, Complete, and Verifiable example
  • 是的抱歉玩家被识别为;玩家 =['汤姆', '简']

标签: python compiler-errors


【解决方案1】:

适用于 Python 3.x

import random

players = ["Player 1", "Player 2"]

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
    if dice > x:
        print(p + " wins!")
    elif dice == x:
        print(p + "gets a tie.")
    else:
        print(p + " loses.")

对于 Python 2.x

import random

players = ["Player 1", "Player 2"]

for p in players:
    x = len(p)
    dice = random.randint(0, x*2)
    print(str(p) + " rolls a " + str(dice) + " out of " + str(x*2))
    if dice > x:
        print p + " wins!"
    elif dice == x:
        print p + "gets a tie." 
    else:
        print p + " loses."

或在第一个示例中添加 from __future__ import print_function 以确保 Python 3 和 2 之间的兼容性。

【讨论】:

  • 谢谢 anatol;给了我很多参考。非常感谢
猜你喜欢
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
相关资源
最近更新 更多