Search code examples
pythonif-statementpyautogui

How do I use the if / then command in python


So very recently, I have started learning python, and I have come up with a very basic script that should ask the user a question, and move the cursor to a spot on the screen based on the answer that the program receives. But when I run the program it runs the first part of the code, then closes the interpreter as if the program was finished.

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)

I believe that the issue is with the if / then command but is could be something as simple as an indention error.

I apologise in advance for any formatting mistakes that I made when typing up this question as I am quite new to stack overflow.


Solution

  • I'd like to elaborate on top of @zerecees's already excellent answer to account for possible edge cases that might break down your program.

    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
    

    The try and except statement accounts for cases in which the user inputs something that cannot be casted into int. For example, imagine a situation where the user inputs one instead of 1; in such cases, type conversion will not work. Therefore, we use a while loop to prompt the user to input a valid input until a valid input is entered.

    Then, since we have converted the input from a string to an integer, the conditionals will work as expected.