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

问题描述 投票:0回答:3

[最近,我开始学习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命令,但可能像缩进错误一样简单。

由于在堆栈溢出方面还很陌生,所以我在键入此问题时所犯的任何格式错误均会提前致歉。

python if-statement pyautogui
3个回答
1
投票

pyautogui.prompt()返回string,并且您正在检查int。尝试在if .. "1", elif .. "2"周围加上引号,以使int成为string

或者,尝试:

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


0
投票

我想在@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循环提示用户输入有效输入,直到输入有效输入为止。

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


0
投票

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

检查返回类型

打印(类型(选择))

因此更改类型。如果仍然卡住(如果没有得到提示窗口),则可能存在一些安全问题,因此您将需要明确允许应用程序使用鼠标/键盘。只需查看安全性首选项中的可访问性,然后采取适当的措施即可。希望这会有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.