首页 > 解决方案 > 我看似简单的整数比较不起作用?Python

问题描述

我正在尝试制作一个随机打印 8 个选项的程序,其中 7 个为“向上”,其中 1 个为“向下”。然后,提示用户输入显示“向下”的数字。我的代码中唯一不起作用的是显示“向下”的位置的数字与用户输入之间的比较。完整代码:

import random


def game_1():
    # original list
    up_down_lst = ["Up","Up","Up","Up","Up","Up","Up","Down"]

    # shuffles the list's items so they're randomized
    up_down_lst_shuffled = up_down_lst[:]
    random.shuffle(up_down_lst_shuffled)

    # just a print statement
    print("Pull up the lever that's down")

    # prints shuffled list items with numbers corresponding to its input number
    for i in range(8):
        print("[{}]".format(i + 1), up_down_lst_shuffled[i])

    # goes through the shuffled printed list again and checks for which number corresponds to "down"
    for j in range(len(up_down_lst_shuffled)):
        if "Down" in up_down_lst_shuffled[j]:

    # assigns the "down" number to a variable called down_num
            down_num = (j + 1)

    # asks for user input
    choice0 = input("> ")

    # compares uer input to see if it's the same as the "down" number
    if choice0 == down_num:
        print("Correct")
    else:
        print("Wrong, try again.")


# calls the function
game_1()

应该输出什么:(示例)

Pull up the lever that's down
[1] Up
[2] Down
[3] Up
[4] Up
[5] Up
[6] Up
[7] Up
[8] Up
> 2
Correct

实际输出的内容:(示例)

Pull up the lever that's down
[1] Up
[2] Down
[3] Up
[4] Up
[5] Up
[6] Up
[7] Up
[8] Up
> 2
Wrong, try again.

标签: pythonpython-3.x

解决方案


你的代码是正确的。

input回报str

您正在将 int 与 str 进行比较。

我建议你将str你得到inputint

def game_1():
    # original list
    up_down_lst = ["Up","Up","Up","Up","Up","Up","Up","Down"]

    # shuffles the list's items so they're randomized
    up_down_lst_shuffled = up_down_lst[:]
    random.shuffle(up_down_lst_shuffled)

    # just a print statement
    print("Pull up the lever that's down")

    # prints shuffled list items with numbers corresponding to its input number
    for i in range(8):
        print("[{}]".format(i + 1), up_down_lst_shuffled[i])

    # goes through the shuffled printed list again and checks for which number corresponds to "down"
    for j in range(len(up_down_lst_shuffled)):
        if "Down" in up_down_lst_shuffled[j]:

    # assigns the "down" number to a variable called down_num
            down_num = (j + 1)

    # asks for user input
    choice0 = int(input("> ")) # type cast to int

    # compares uer input to see if it's the same as the "down" number
    if choice0 == down_num:
        print("Correct")
    else:
        print("Wrong, try again.")


# calls the function
game_1()
Pull up the lever that's down
[1] Up
[2] Up
[3] Up
[4] Up
[5] Up
[6] Up
[7] Up
[8] Down
> 8
Correct

推荐阅读