代码在Python3中运行,而不是在Python2中运行

2024-10-02 12:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还很陌生,我只是在做一些练习。 这是其中之一,一个简单的掷骰子。 它在ATOM中运行得非常好,当我尝试在空闲状态下运行它时,问题就出现了。我不明白为什么会发生这个问题。我很确定这是一个很难回答的问题。 代码:

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):

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):

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'

谢谢你的耐心!你知道吗


Tags: toinpynumberinputlinedicefile
1条回答
网友
1楼 · 发布于 2024-10-02 12:27:45

这是因为在atom编辑器中,使用python3,空闲使用python2。在python2中,读取用户输入的函数被称为raw_input()it was renamed to ^{} 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

并用... = compatible_input(...)替换代码中... = input(...)的所有用法。你知道吗

相关问题 更多 >

    热门问题