python - 我看似简单的整数比较不起作用?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.
解决方案
你的代码是正确的。
但input
回报str
您正在将 int 与 str 进行比较。
我建议你将str
你得到input
的int
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
推荐阅读
- java - 使用循环的 AsyncTask 示例
- c++ - 重载运算符 + 用于向量:命名空间 std
- batch-file - 如何将 FOR 命令中的变量与 FOR 命令之外的变量进行比较?
- javascript - 包含在 wordpress 网站中时,javascript 不会触发
- docker - 在树莓派 3 B+ 上运行 ASP .NET Core
- arrays - Angular 6 在 Index[i][j] 插值问题处获取数组的值
- python - Keras 如何使用 class_weight 参数?
- azure - 动态创建 ARM 参数名称
- java - 在数据库中找到同名用户时如何更改变量的值?
- c# - Task.WaitAny() — 检查结果