意想不到的功能

时间:2017-04-24 02:47:21

标签: python python-3.x

我得到了一个意想不到的unindent这个函数,即使代码正确缩进,我仍然会收到错误。我尝试过一个除了和多个,我仍然得到错误:

def showHand():

    print('This game will let you open your saved Dream Hand.')

    #getting the file name the user wants to open
    filename = input('Please enter your dream hand file name: ')

    try:
        #opening
        infile = open(filename, 'r')

        #reading the values inline
        card1 = int(infile.readline())
        card2 = int(infile.readline())
        card3 = int(infile.readline())
        card4 = int(infile.readline())
        card5 = int(infile.readline())

        #closing file
        infile.close()

        #printing values through face value
        print('Your Dream Hand is: ')
        faceValue(card1)
        faceValue(card2)
        faceValue(card3)
        faceValue(card4)
        faceValue(card5)

    except IOError:
        print('An error has occurred')

    finally:
        print('Thank you for playing')

2 个答案:

答案 0 :(得分:0)

缩进def showHand():

下的代码
def showHand():

     print('This game will let you open your saved Dream Hand.')

     #getting the file name the user wants to open
     filename = input('Please enter your dream hand file name: ')

     try:
         #opening
         infile = open(filename, 'r')

         #reading the values inline
         card1 = int(infile.readline())
         card2 = int(infile.readline())
         card3 = int(infile.readline())
         card4 = int(infile.readline())
         card5 = int(infile.readline())

         #closing file
         infile.close()

         #printing values through face value
         print('Your Dream Hand is: ')
         faceValue(card1)
         faceValue(card2)
         faceValue(card3)
         faceValue(card4)
         faceValue(card5)

     except IOError:
         print('An error has occurred')

     finally:
         print('Thank you for playing')

答案 1 :(得分:0)

好吧,我按原样复制你的代码,然后运行,所以这里是重构。

def faceValue(card):
    if card == 1:
        return 'A'
    if card > 10:
        return {11: 'J', 12: 'Q', 13: 'K'}[card]
    else: 
        return card

def showHand():

    print('This game will let you open your saved Dream Hand.')

    #getting the file name the user wants to open
    filename = input('Please enter your dream hand file name: ')

    try:
        #opening
        with open(filename) as infile:
            cards = [int(infile.readline()) for _ in range(5)]

        #printing values through face value
        print('Your Dream Hand is: ')
        for card in cards:
            print(faceValue(card))

    except IOError:
        print('An error has occurred')

    finally:
        print('Thank you for playing')

showHand()