繁体   English   中英

试图在 python while 循环中定位语法错误

[英]Trying to locate syntax error in python while loop

非常非常新的初学者 - 今天刚刚开始学习! 难倒这里的语法错误是什么:

import random
x = random.randrange(7)
user_start = "yes"
user_start_input = str(input("type 'yes' to generate random number. "))
while user_start_input == user_input:
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
if user_start_input != user_input:
break
print("done")

错误消息是: File "/Users/joel/Documents/Learning Python/Dice.py", line 12 while user_start_input == user_input: ^ SyntaxError: invalid syntax

我究竟做错了什么?

首先,我们(那些希望回答的人)缺少一些信息, while在第5行,当第12行报告错误while ,有很多可能导致错误在下一行弹出; 例如。 缺少报价。 看起来G. Anderson已经避开了最后一点,因为错误通常来自前一行。 在这种情况下,我的建议是找到一个开发人员友好的文本编辑器 (IDE),它会通过语法突出显示指出轻微的拼写错误; Atom非常棒,尤其是有一些插件,但还有很多其他文本编辑器可供使用。

其次,正如CoffeeTableEspresso所评论的,您的代码CoffeeTableEspresso中不存在标签! 如果您的源代码看起来与已发布的相同,那么您的错误踩踏才刚刚开始。

第三,因为你已经说过 Python 不是你的第一语言,所以了解__doc__字符串可能会有所帮助,例如……

>>> print(random.randrange.__doc__)
Choose a random item from range(start, stop[, step]).

        This fixes the problem with randint() which includes the
        endpoint; in Python this is usually not what you want.

... Python 中的许多内容都可以通过__doc__方法进行记录和访问,该方法也可以通过help()访问,例如。 help(random.randrange) ,并且可以使用以下语法编写自己的...

def test_func(arg):
    """
    This is a __doc__ string
    """
    print("arg -> {0}".format(arg))

最后,就目前而言,在用不熟悉的语言写作时,最好使用大量注释并将事情分成更小的部分来表达您的意图; 例如...

#!/usr/bin/env python

import random


def dice(sides = 6):
    """
    Returns random int between `1` and `sides`
    """
    return random.randrange(start = 1, stop = int(sides) + 1, step = 1)


def prompt(message, expected):
    """
    Returns `True` if user input matches `expected`
    """
    return expected == str(input("{0} ".format(message)))


def main_loop():
    """
    Returns list of `dice(...)` results, list length depends
     upon number of times `prompt(...)` returns `True`
    """
    roll_results = []
    user_start = 'yes'
    # Set message for first run of loop
    message = "Type '{0}' to roll the dice".format(user_start)
    while prompt(message = message, expected = user_start):
        # Save dice output to variable for later use and
        #  append to list of rolls that will be returned
        roll = dice(sides = 6)
        roll_results.append(roll)
        # For now just print each roll, but this is one
        #  aria to expand upon with your own edits
        print("Rolled {0}".format(roll))
        # Set new message line for following loop iterations
        message = 'Roll again?'
    return roll_results


# Do stuff if script is run directly instead of imported as a module
if __name__ == '__main__':
    main_loop()

PS坚持下去,最终所有的学习都会开始点击,以下与RP相关的示例类将变得更多,因为...

#!/usr/bin/env python

from __future__ import range

import random


class DiceBag(dict):
    """
    DiceBag is a collection of short-cuts to `random.randrange`.

    - `selection`, list of `n` sided dice, eg `[4, 20]` would _stock_ bag with d4 and d20
    """

    def __init__(self, selection = [2, 4, 20], **kwargs):
        super(DiceBag, self).__init__(**kwargs)
        self.update(selection = selection)

    def dice(self, sides = 6):
        """
        Returns random int between `1` and `sides`
        """
        return random.randrange(start = 1, stop = int(sides) + 1, step = 1)

    def handfull_of(self, dice = {}):
        """
        Returns `dict` with lists of dice rolls

        ## Example

            dice_bag = DiceBag()
            toss_results = dice_bag.handfull_of({20: 1, 4: 2})

        Should return results of one `d20` and two `d4` such as

            {
                20: [18],
                4: [1, 3]
            }
        """
        output = {}
        for sides, count in dice.items():
            if sides not in self['selection']:
                continue

            rolls = []
            for roll in range(count):
                rolls.append(self.dice(sides))

            output[sides] = rolls

        if not output:
            raise ValueError("No dice in bag matching sizes -> {0}".format(dice.keys()))

        return output

    """
    Short cuts for dice of a `n` sides, expand upon it if you wish
    """

    @property
    def coin(self):
        return self.dice(sides = 1)

    @property
    def d4(self):
        return self.dice(sides = 4)

    @property
    def d6(self):
        return self.dice(sides = 6)


class Flail(DiceBag):
    def __init__(self, damage_modifier = 0, damage_dice = {'sides': 6, 'count': 2}, **kwargs):
        super(Flail, self).__init__(selection = [damage_dice['sides'], 20], **kwargs)
        self.update(damage_modifier = damage_modifier)
        self.update(damage_dice = damage_dice)

    def attack(self, attack_modifier = 0):
        """
        Returns `dict` with `hit` chance + `attack_modifier`
         and `damage` rolls + `self['damage_modifier']`
        """
        rolls = self.handfull_of(dice = {
            20: 1,
            self['damage_dice']['sides']: self['damage_dice']['count']
        })
        return {
            'hit': rolls[20][0] + attack_modifier,
            'damage': sum(rolls[self['damage_dice']['sides']]) + self['damage_modifier']
        }

更新

这是您的代码块在适当缩进的情况下的样子......

import random

x = random.randrange(7)
user_start = "yes"
user_start_input = input("type 'yes' to generate random number. ")

while user_start_input == user_input:
    print("your random dice number is " + str(x))
    user_start_input = input("roll again?")

print("done")

......这是一个工作版本可能是什么样子......

import random

message = "type 'yes' to generate random number. "
expected = "yes"

while input(message) == expected:
    x = random.randrange(7)
    print("your random dice number is {num}".format(num = x))
    message = "roll again? "

print("done")

...在使用while做同样的事情时,几乎没有理由使用if something break ,考虑到当前问题的代码示例。

x的分配移到循环内可确保每次迭代都有机会出现新数字,但未说明我感觉这是您的意图。

使用input(message)并更新显示的消息希望是有意义的。 虽然我不确定为什么你在str()中包装东西,但在我测试时似乎没有什么不同。

首先,您似乎混淆了两个变量名user_startuser_input ,因此需要将它们更改为相同的变量名。

接下来,Python 用缩进构造代码:因此 while 循环等中的内容需要缩进。

因此,在这里,您将缩进 while 循环内的所有代码,并进一步缩进 while 循环内的 if 语句内的代码。

您的代码的目的似乎也是在每次 while 循环再次运行时模拟掷骰子。 在 while 循环中,您调用变量x进行掷骰子,但x永远不会改变。 您从未将x更改为不同的随机数,因此每次用户再次掷骰子时它只会显示相同的随机数。

要解决此问题,只需在每次运行 while 循环时重新定义x 所以只需将变量x的定义移动到 while 循环中。

通过所有这些修复,代码可以工作:

import random
user_start = "yes"
user_start_input = str(input("type 'yes' to generate random number. "))
while user_start_input == user_start:
        x = random.randrange(7)
        print("your random dice number is " + str(x))
        user_start_input = input("roll again?")
        if user_start_input != user_start:
                break
print("done")

当然,变量名称可以提供更多信息,并且可以更好地结构化代码以提高性能和用户友好性,但总的来说,对于初学者来说非常棒!

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM