Python中的变量从int移动到string

时间:2017-10-04 15:44:06

标签: string python-3.x variables integer global

def round1():
    global Rod, Jane, Freddy
    Rod=int(input("please enter Rod's score"))
    Jane=int(input("please enter Jane's score"))
    Freddy=int(input("please enter Freddy's score"))
    print("The loser is")
    loser=min(Rod, Jane, Freddy)
    print(loser)
    round2()


def round2():
    print("are you ready for the next scores?")


round1()

我希望最高得分手的前两名能够为下一轮提供这个 - 这甚至可能吗?!请放轻松,我不是一个程序员,只是一个老师试图尽我所能!

2 个答案:

答案 0 :(得分:0)

我会使用名为'字典'的Python数据结构。因为您想为名称指定值。这样就很容易删除“失败者”。

dic1 = {'Rod': 0, 'Jane': 0, 'Freddy' : 0}

def round1():

    dic1['Rod'] = input("please enter Rod's score") #here we add the input values to the keys
    dic1['Jane'] = input("please enter Janes's score")
    dic1['Freddy'] = input("please enter Freddys's score")


    print("The loser is")

    loser=min(dic1.get('Rod'), dic1.get('Jane'), dic1.get('Freddy'))

    for key, value in dic1.items(): #here we loop over the dictionary to find the loser and delete him
        if value is loser:
            print(key) #here we print the key of the loser, in this case a String
            del dic1[key] #here we delete the loser out of the dictionary

    round2()

def round2():
    print("are you ready for the next scores?")
    print(dic1)

round1()

编辑刚看到你有一个Python3标签。在这种情况下,据我所知,你可能必须在for循环中封装带有list()的dic1.items()。那将使它成为列表(dic1.items())。这是因为Python3会像Python2.7一样返回视图而不是列表

答案 1 :(得分:0)

我们可以传递玩家得分和玩家名称的元组。由于这些是从得分开始的,因此我们可以在其上调用min(),就像他们的数字一样:

def round1(players):
    loser = min(*players)
    print("The loser is:", loser[1])

    remaining = [player for player in players if player != loser]

    round2(remaining)

def round2(players):
    print(", ".join(player[1] for player in players), "are still in the game.")
    print("Are you ready for the next scores?")

rod = int(input("Please enter Rod's score: "))
jane = int(input("Please enter Jane's score: "))
freddy = int(input("Please enter Freddy's score: "))

round1([(rod, 'Rod'), (jane, 'Jane'), (freddy, 'Freddy')])

<强> USAGE

% python3 test.py
Please enter Rod's score: 13
Please enter Jane's score: 34
Please enter Freddy's score: 56
The loser is: Rod
Jane, Freddy are still in the game.
Are you ready for the next scores?
%
  

如何才能让前两名只使用min?

我假设您不希望列表理解将剩余的玩家分开。我们摆脱它的一种方法是使players成为set而不是list

def round1(players):
    loser = min(*players)

    print("The loser is:", loser[1])

    round2(players - set(loser))

def round2(players):
    print(", ".join(player[1] for player in players), "are still in the game.")
    print("Are you ready for the next scores?")

rod = int(input("Please enter Rod's score: "))
jane = int(input("Please enter Jane's score: "))
freddy = int(input("Please enter Freddy's score: "))

round1({(rod, 'Rod'), (jane, 'Jane'), (freddy, 'Freddy')})

这是有道理的,因为没有隐含的特定顺序。