如何在 python 中使用 if / then 命令

How do I use the if / then command in python

所以最近,我开始学习 python,我想出了一个非常基本的脚本,应该向用户提问,并根据程序收到的答案。但是当我 运行 程序是 运行 代码的第一部分时,然后关闭解释器,就好像程序已完成。

import pyautogui
import time
choice = 0
choice = pyautogui.prompt("Which option do you choose? ")
                                                                   # The code stops working here
if choice == 1:
    pyautogui.moveTo(670, 440)
elif choice == 2:
    pyautogui.moveTo(690, 440)
elif choice == 3:
    pyautogui.moveTo(670, 500)
elif choice == 4:
    pyautogui.moveTo(690, 500)

我认为问题出在 if / then 命令上,但也可能是缩进错误这样简单的问题。

对于在输入此问题时出现的任何格式错误,我提前表示歉意,因为我对堆栈溢出还很陌生。

pyautogui.prompt() returns a string,您正在检查 int。尝试在 if .. "1", elif .. "2" 周围加上引号,使 int 变成 string

或者,尝试:

int(pyautogui.prompt("...")string 转换为 int

我想在@zerecees 已经非常好的答案的基础上详细说明,以说明可能会破坏您的程序的边缘情况。

import time
import pyautogui

while True:
   try:
      choice = int(pyautogui.prompt("Which option do you choose? "))
      break
   except ValueError:
      print("Please type an integer value.")

if choice == 1:
    pyautogui.moveTo(670, 440)
elif choice == 2:
    pyautogui.moveTo(690, 440)
elif choice == 3:
    pyautogui.moveTo(670, 500)
elif choice == 4:
    pyautogui.moveTo(690, 500)
else:
    # Some default fallback code

tryexcept 语句说明了用户输入无法转换为 int 的内容的情况。例如,假设用户输入 one 而不是 1 的情况;在这种情况下,类型转换将不起作用。因此,我们使用while循环来提示用户输入有效输入,直到输入有效输入为止。

然后,由于我们已将输入从字符串转换为整数,因此条件将按预期工作。

这里的问题是 pyautogui.prompt() 是 return 一个字符串,而您正在检查整数。您可以使用

检查 return 类型

print(type(choice))

所以改变类型。如果您仍然卡住(如果您没有得到提示 window),则可能存在一些安全问题,因此您需要明确允许应用程序使用 mouse/keyboard。只需查看安全首选项中的可访问性并允许适当的操作。希望这会有所帮助:)