我是 Python 的新手,我只是在做一些练习。 这是其中之一,一个简单的 DiceRoller。 它在 ATOM 中工作得很好,当我尝试在 IDLE 中运行它时出现问题。我无法弄清楚为什么会发生这个问题。很确定这是一个菜鸟问题。 代码:
import random
dices=[2, 3, 4, 6, 8, 10, 12, 20, 100]
Y= ['yes', 'y']
N= ['no', 'n']
def DiceRoller():
dice_selection=input('Please, choose the dice(d2, d3, etc. - only the number): ')
try:
dice = int(dice_selection)
except ValueError:
print('You have to select a number, try again')
DiceRoller()
if dice not in dices:
print('You have to select a 2, 3, 4, 6, 8, 10, 12, 20, 100 faces dice, try again')
DiceRoller()
number=input('How many dice(s) do you want to roll? ')
try:
numint = int(number)
except ValueError:
print('You have to select a number, try again')
DiceRoller()
ripet=0
while ripet < numint:
ripet += 1
if dice in dices:
result=random.randint(1,dice)
print(result)
else:
Continue()
def Continue():
risposta=input('Do you want to roll again? (Y/N) ')
rispostal= risposta.lower()
if rispostal in Y:
DiceRoller()
elif rispostal in N:
return 'Goodbye'
quit()
else:
print('Please, answer Yes or No')
Continue()
DiceRoller()
程序询问我是否要再次滚动(输入 y 或 n)后出现 IDLE 错误:
Traceback (most recent call last):
File "E:\Corso Python\DiceRoller.py", line 44, in <module>
DiceRoller()
File "E:\Corso Python\DiceRoller.py", line 30, in DiceRoller
Continue()
File "E:\Corso Python\DiceRoller.py", line 33, in Continue
risposta=input('Do you want to roll again? (Y/N) ')
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
程序询问我是否要再次滚动(输入 Y 或 N)后出现 IDLE 错误:
Traceback (most recent call last):
File "E:\Corso Python\DiceRoller.py", line 44, in <module>
DiceRoller()
File "E:\Corso Python\DiceRoller.py", line 30, in DiceRoller
Continue()
File "E:\Corso Python\DiceRoller.py", line 34, in Continue
rispostal= risposta.lower()
AttributeError: 'list' object has no attribute 'lower'
感谢您的耐心等待!
请您参考如下方法:
那是因为在原子编辑器中,您使用的是python3,而您的IDLE 使用的是python2。在 Python 2 中,读取用户输入的函数称为 raw_input(); it was renamed to input() in Python 3 (以 PEP 3111 开头的部分:raw_input() 已重命名为 input())。
您可以确保默认使用 python3 或使代码与 python2 兼容:添加代码块
import sys
compatible_input = raw_input if sys.version_info < (3, 0) else input
并用 ... = compatible_input(...) 替换代码中所有 ... = input(...) 的用法。
