这里非常新手-今天才开始学习!陷入这里的语法错误:
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
我在做什么错了?
答案 0 :(得分:1)
首先,我们(希望回答的人)缺少一些信息,while
在第5
行,其中while
在第{{1 }},有很多可能会导致错误在下一行弹出;例如。缺少报价。看来12
到最后一点已经不存在了,因为错误通常来自前一行。在这种情况下,我的建议是找到一个对开发人员友好的文本编辑器(IDE),该编辑器将通过语法高亮指出较小的错别字。 Atom很时髦,尤其是带有一些附加组件,但是还有很多其他文本编辑器可以玩。
第二,如G. Anderson
所评论,这些选项卡在您的代码片段中不存在!如果您的源代码看起来与已发布的代码相同,则您的踩踏错误才刚刚开始。
第三,因为您曾说过Python不是您的第一语言,所以了解CoffeeTableEspresso
字符串(例如...
__doc__
... Python中的许多内容都可以通过>>> 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.
方法进行记录和访问,例如,也可以使用__doc__
进行访问。 help()
,并可以使用以下语法编写自己的语法...
help(random.randrange)
最后,就目前而言,用不熟悉的语言写作时,最好使用大量注释并将内容分解成能表达您意图的较小部分,这是一个好主意。例如...
def test_func(arg):
"""
This is a __doc__ string
"""
print("arg -> {0}".format(arg))
P.S。坚持下去,最终所有学习都会开始 click ,并且以下与RP相关的示例类将为您带来更多收益,因为...
#!/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()
这是您的代码块 正确缩进后的样子……
#!/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")
做同样的事情时,几乎没有理由使用if
某物 break
,考虑到当前问题的代码样本。
将 while
的分配移动到循环中可确保每次迭代都有一个新数字的机会,尽管没有声明,但我有种感觉,这就是您的意图
希望使用x
并更新显示的消息是有意义的。尽管我不确定为什么您在input(message)
中包裹东西,但是在我测试时似乎并没有什么区别。
答案 1 :(得分:0)
首先,您似乎混淆了两个变量名user_start
和user_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")
当然,变量名可以提供更多信息,并且可以更好地构造代码以提高性能和用户友好性,但是总体而言,对于初学者而言,这是一项很棒的工作!