代码在Python 3中运行,而不是在Python 2中运行

时间:2017-11-24 13:50:57

标签: python python-3.x python-2.7

我是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)后,

ID 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'

感谢您的耐心等待!

1 个答案:

答案 0 :(得分:2)

那是因为在原子编辑器中,您使用python3,而您的IDLE使用python2。在Python 2中,用于读取用户输入的函数被称为raw_input(); it was renamed to input() in Python 3(以PEP 3111: raw_input() was renamed to input()开头的部分)。

您可以确保默认使用python3或使代码python2兼容:添加代码块

import sys
compatible_input = raw_input if sys.version_info < (3, 0) else input

并使用... = input(...)替换代码中... = compatible_input(...)的所有用法。