How do I use the if / then command in python - 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.

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.

pyautogui.prompt() returns a string, and you are checking for int. Try putting quotes around if .. "1", elif .. "2" to make the int's string's.
Or, try:
int(pyautogui.prompt("...") to convert string to int.

The problem here is pyautogui.prompt() is returning a string and you are checking for integer. You can check the return type using,
print(type(choice))
So change the type. If you still get stuck(if you didn't get the prompt window) then there may be some security issues, so you will need to explicitly allow application to use mouse/keyboard. Just have a look at accessibility in security preference and allow the appropriate action. Hope this will help :)

Related

Why is my if statement not executing when I start my code?

I'm a beginner programmer just starting out and learning and I'm wondering why my code finishes after the first line. If anyone can let me know what is wrong with it, would be greatly appreciated.
I wanted it to print my if statements properly but I'm not sure what's going on.
x = 10
try:
(input("Type in a number:"))
except ValueError:
print('Correct!')
if x > 10:
print('X is bigger than the number given')
if x < 10:
print('X is smaller than the number given')
Since you stated that you're a new programmer (welcome! we've all been in your shoes at one point), I'm going to assume from looking at your code that the goal of your game is to have a "magic number" that is set ahead of time, and you want the user to try and guess it. In general, good programs are self-documenting, meaning the code is written in a way that clearly describes what it does. Comments are also helpful. Take a note of the changes I made to your program and how they help you understand what's going on:
"""
* This comment is known as a module docstring
and describes the module, the file in this case
* guessing_game.py is a command-line game
where users try to guess a random number
while getting hints about their guess.
"""
magic_number = 42 # set this before running the program
while (guess := int(input('enter a guess: '))) != magic_number:
# * use a while loop to loop until the correct answer is entered.
# NOTE: the "walrus operator `:=` is used for consiceness.
# the walrus operator requires python >= 3.8
if guess > magic_number:
print('Too high!')
else:
print('Too low!')
print('You win!')
Now, kuwl, I challenge you to try the following on your own:
generate magic_number automatically when the program starts.
hint: https://docs.python.org/3/library/random.html
Set a special number, called a "sentinel value" in computer science, that will terminate the loop if the user wants to quit before guessing the correct number.
Set a limit on the number of attempts the player can make before he/she "loses". This can be done in several ways, try and think of a few!
Allow users to quit the game with ctrl-c, which is a common way to exit command-line programs like yours. Try catching the exception that gets "thrown" when a users hits ctrl-c gracefully and print a message like "thanks for playing, come again!"
Those changes will introduce you to a lot of key concepts in programming like importing packages, handling exceptions, and writing comments and self-documenting code. If you get stuck, try googling your question. There's a good chance many others have asked the same before. It's a valuable skill in programming to be able to write good questions, both to a search engine and to another human. If you're still stuck, ask a comment on this post and I'll do my best to answer it.
Happy hacking!
You will never get a ValueError in this program from this line input("Type in a number:")
Corrected code:
x = 10
try:
x = input("Type in a number:")
print('Correct!')
except ValueError:
if x > 10:
print('X is bigger than the number given')
if x < 10:
print('X is smaller than the number given')
You can simply do:
x = 10
x = input("Type in a number:")
if x.isnumeric() : # checks if x is numeric or not
print('Correct!')
if x > 10:
print('X is bigger than the number given')
if x < 10:
print('X is smaller than the number given')

Trying to end a script based on users answer (at a particular point) within a multiple choice scenario

I've created a basic, multiple choice, interactive calculator in Python. I want the user to be able to have the option to stop the programme running by answering "No" when asked whether they want to test out my calculator.
I want to be able to print("Ok, no problem") which you can see is already there but I need something extra to stop the programme running if this is the answer that the user picks.
Code is below. See lines 12-13.
name = input("Hi There. What is your name? ")
print("Well Hi " + name + ", it sure is nice to meet you")
age = input("So how old are you anyway? ")
print("Wow, you're " + age + " huh? ")
print(name + " I would like you to try out the companies new calculator. Would you be
happy to do that? ")
answer = input("Please answer Yes or No ")
if answer == "Yes":
print("Thank you, I appreciated that. Let's begin")
elif answer == "No":
print("Ok, no problem")
else:
print("Sorry I didn't quite get that. Please answer yes or no")
import math
number_1 = int(input("Please pick a number "))
order = (input("Ok, now please pick either: +, -, / or * "))
number_2 = int(input("Great, now please pick a second number "))
if order == "+":
print(number_1 + number_2)
elif order == "-":
print(number_1 - number_2)
elif order == "/":
print(number_1 / number_2)
elif order == "*":
print(number_1 * number_2)
else:
print("Sorry that is not +, -, / or *. Please enter a relevant order")
Any help that you can give me would be much appreciated.
You can use sys.exit to terminate the program:
import sys
#...
elif answer == "No":
print("Ok, no problem")
sys.exit()
Here is an answer for you which helped me out:
Let me give some information on them:
quit() raises the SystemExit exception behind the scenes.
Furthermore, if you print it, it will give a message:
>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>
This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.
Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.
exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.
Furthermore, it too gives a message when printed:
>>> print (exit)
Use exit() or Ctrl-Z plus Return to exit
>>>
However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.
sys.exit() raises the SystemExit exception in the background. This means that it is the same as quit and exit in that respect.
Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.
os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.
Note that, of the four methods given, only this one is unique in what it does.
Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.
Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:
raise SystemExit
This way, you do not need to import sys first.
However, this choice is simply one on style and is purely up to you.

The efficiency of a specific while loop

I'm making a program for a school project and within the program, the user makes a decision. to make sure the user inputs a valid input. i want to know if using a while loop like this is efficient. it is be contained within a function that would be used multiple times. i did this as this function will be called and the returned value will be stored in a variable. this is for a command line programme:
def user_choice():
while True:
choice = input("choose \'a\' or '\b\':")
if choice == "a" or choice == "b":
return choice
else:
print("not a valid input")
In terms of raw machine efficiency, your algorithm is perfectly acceptable. The bottleneck is the user's input. It only goes through the loop once per input, so the actual execution of that code is basically instantaneous. Some programs will use a loop to continuously check some condition as fast as the computer can manage, and that is indeed suboptimal (eats up a CPU core).
In terms of good coding style, your algorithm is perfectly acceptable as well. Using a while True (or while 1) with a return on a valid input is very common and easily understood to any reader.
I would suggest some slight modifications like if choice.lower().strip() in ('a', 'b'): instead of if choice == "a" or choice == "b": as noted in a comment, but that's just to make it a bit more robust in the face of messy user input. Also, you don't need to escape quotes unless they're of the type that encloses the string, so you can do input("choose 'a' or 'b':") instead of input("choose \'a\' or '\b\':").

except ValueError not tripping Python 3.4

Alright so I'm trying to basically prevent someone from typing a string value into the field:
#User selection
print("Which program would you like to run?")
print("(Type '9' if you wish to exit the menu)")
selection = int(input())
print()
#Security statement followed by case statement
while selection <= 0 or selection >= 10:
try:
print("That is an invalid selection, please input a proper selection.")
print("Which program would you like to run?")
selection = int(input())
print()
except ValueError:
print("Cmon man")
Plain and simple, it's not running. I've tried reorganizing everything and I haven't found a proper solution. Been looking around for almost an hour now. No help to the issue. Any kind souls?
Ignore the case statement portion btw, that's not even written yet.
P.S. Just keep getting usual "String isn't a number durr" response
("ValueError: invalid literal for int() with base 10: 'why'")
P.P.S. Issue is already pointed out. I'm apparently stupidly oblivious lol... Thanks for the help.
Your try...except doesn't cover the initial user input and so the ValueError isn't actually caught.
If you enter an int outside the bounds defined (0 >= x >= 10) as the first input then you can see the try...except blocks working.
You'll need to refactor your code so that the first input request is inside your try block and the loop or wrap the existing input request in another try...except.
Also, as a side note, input() can take a string argument that will be displayed as a prompt to the user.
selection = int(input("Which program would you like to run? "))

Input strings and integers

Just a quick question because I really can't find a simple solution to my problem.
Is there a way to get a user input that is meant to be a integer, but when a string is entered
the program will not break and instead displays "Error"
I've been trying to work around it by converting strings to integers and vice-versa, but I constantly get "invalid literal for int() with base 10" error, or when it displays "Error" it does so in an infinite loop.
Here's my code just to help clear the question
choice = input("Enter your choice: ")
while choice != 3:
if choice == 1:
get_songs()
print
main()
elif choice == 2:
read_songs()
print
main()
else:
print "Invalid choice"
So essentially I want the else operation to work for strings as well as for an integer that is greater than 3 or less than 1.
but I constantly get "invalid literal for int() with base 10" error
You get an exception, specifically a ValueError. You can catch the exception using an except block. For more info, refer to whatever language tutorial you've been using thus far, or try Google for except block Python.
when it displays "Error" it does so in an infinite loop.
When you detect that the input isn't correct, you need to get new input before you try the loop again. Put the input-getting stuff inside your loop. Do not use recursion (calling main() from within main) in addition to the loop; you're only going to confuse yourself this way. Because you don't get a value for choice until you're inside the loop, it's easier to explicitly break out of the loop when you find the appropriate choice value, instead of trying to control the loop with it (i.e. testing for it in the while condition).
We can also use continue to simplify the loop structure: instead of doing all the work in the try block, we limit that to the part where we extract a number. We use continue in the except block to skip the rest of the loop when we don't have an actual number, and only do the rest of the loop when we do. (After all, maybe the code we call for choice == 1 or choice == 2 could raise ValueError for some totally different reason, and we'd want to do something different about that.)
while True:
try:
choice = int(raw_input("Give me a number"))
except ValueError:
print "Could you at least give me an actual number?"
continue
if choice == 1:
do_something()
elif choice == 2:
do_something_else()
elif choice == 3:
break
else:
print "Try a different number"
Since that choice always != 3, you will get an infinite loop.
You should get input again if it jumps into the "else" condition.
In your code, the while loop should encapsulate the input() line. The following is a clearer alternative, however:
Create a function which gets user input:
def getInteger(prompt):
while True:
userIn = input(prompt)
try:
return int(userIn)
except ValueError:
print "Error"
Here's something: I dislike making the user enter "" around the strings.
ch = raw_input("Enter choice: ")
#ch *is* a string at this point
if ch.isdigit():
choice = int(ch)
else:
print "Invalid choice"
Edit (from comments):
isdigit may not handle locale encoding correctly. In Python 3, you can use isdecimal instead.
— J.F. Sebastian

Categories