Trying to get my code to exit on the press of the enter button and I'm running into a ValueError: invalid literal for int() with base 10: '', but it's telling me that my error is on the line simulations_num = int(simulations). Anybody have an idea?
simulations = input("How many times would you like to run the simulation? ")
# Invalid answer, system exit
if (not simulations) or int(simulations) <=0:
print("That is not a valid number of simulations.")
print("Shutting down.")
SystemExit
simulations_num = int(simulations)
#the rest of my code comes here
I've also attempted if simulations == '' to no avail.
I have noticed that if simulations_num = int(simulations) isn't involved, the code works fine, but that part of the code (or something similar) is necessary for the rest of the code
You need to raise SystemExit(), or just use sys.exit() (which does the same thing).
you need to raise an error, or at least use sys.exit(0).
The working principle is this:
import sys
if not input(': ').lower() in ['yes','y','1']:
sys.exit(0)
applied to your example would be this
simulations = input("How many times would you like to run the simulation? ")
import sys
# Invalid answer, system exit
if (not simulations) or int(simulations) <=0:
print("That is not a valid number of simulations.")
print("Shutting down.")
sys.exit(0)
simulations_num = int(simulations)
#the rest of my code comes here
raise RuntimeError() would also be good
To address your code:
First of all, you need to add the "raise" keyword infront of SystemExit for it to work properly.
Second, to build a situation, in which you have to press Enter for the program to exit, you can use input().
Corrected Version:
simulations = input("How many times would you like to run the simulation? ")
# Invalid answer, system exit
if (not simulations) or int(simulations) <= 0:
print("That is not a valid number of simulations.")
print("Shutting down.")
input("Press Enter to exit...")
raise SystemExit("Exiting... Reason: invalid input!")
simulations_num = int(simulations)
# the rest of my code comes here
Related
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')
so I've been trying to make a little number-guessing game where the user guesses a number and the computer basically says whether that's higher/lower than the correct number or if it's correct.Basically, everything works correctly up until the user enters an invalid input(anything that isn't an integer). Then it still works correctly but when you eventually guess the right number it tells you that you won and the number of tries that you took būt it also returns a Typerror which says that strings and ints cannot be compared. This is weird because it doesn't do it as soon as you enter the invalid input but rather at the end when you get it correct. Additionally, it shouldn't even be doing that as there is no part in the else statement that tells it to go back into the function.
from random import randint
def game(rand_num = randint(1,10),trys=1): #generates random number and sets trys to 1
user_guess = input('enter your guess 1-10:') #user guess
try: # try except to check for validity of input,restarts functions with preserved random number and # of tries
user_guess = int(user_guess)
except:
print('please try again and enter a valid input')
game(rand_num=rand_num,trys=trys)
# if and elif to check if the number was higher or lower,if it was then it will restart the game function with preserved random number
# and trys increased by 1
if user_guess < rand_num:
print('your guess was lower than the magic number so try again')
game(rand_num=rand_num,trys=trys+1)
elif user_guess > rand_num:
print('your guess was higher than the magic number so try again')
game(rand_num=rand_num,trys=trys+1)
else: #if both don't work then you must have won and it tells you that as well as how many trys you took``
print('hurray you won!!!!!')
print(f'you took {trys} trys')
game()
Also when I tried to use a breakpoint to determine the issue, again everything seemed fine until
after it told the that they won,it mysteriously just went back into the function and started doing stuff with the previously invalid input set as the user_guess variable which is presumably why the Type error happened.
the first place where the function "goes" to after telling the user they won
the 2nd place where it "goes"
It does that for a few more times but yeah it just basically cycles through if elif and try except for some reason
however, I found out that you can use a quit() at the end of the else statement that tells the user they won to solve this but as far as I know that just suppresses the function from doing anything and exits it so it isn't really a solution.
I'm trying to write a basic tic-tac-toe in Python. One of my functions is meant to get the user's input as a number from 1 to 9. If the user enters a non-integer, or a number not between 1 and 9, it will return an error. It's nestled in a try-except to avoid worrying about type conversion.
def get_move():
print("Your move ...")
while True:
try:
move = input("Type a number from 1-9: ")
if move.isnumeric():
if (0 < int(move) < 10):
break
else:
print("The number is outside the range. Try again.")
else:
if (move.tolower == "quit") or (move.tolower == "exit"):
exit()
except:
print("Not a valid integer, try again.")
return move
This sort-of works when I run normally. But when I try to debug in VS Code, when the debugger reaches the line move = input("Type a number from 1-9: ") and I click "Step Into", it simply goes straight to the "except" clause. And the code proceeds in an infinite loop - it will never stop and wait for the user input, meaning that I have to manually stop the debugger.
Any idea why it might be doing this?
Edit:
Thanks for correcting my typo, but that hasn't solved the problem. I've changed the line from:
if (move.tolower == "quit") or (move.tolower == "exit"):
exit()
to:
if move.lower() == "quit" or move.lower() == "exit":
exit()
And also changed the except clause to except (ValueError, TypeError). Now I receive the following error:
Exception has occurred: EOFError
EOF when reading a line
File "[...]tictacpy.py", line 18, in get_move
move = input("Type a number from 1-9: ")
File "[...]tictacpy.py", line 46, in <module>
move = get_move()
Most likely this is happening because in the debugger you do not have a console for standard input, so calling input() will error (I don't know VS code specifically so I'm guessing here, but this is a reasonable cause).
In any case, I'd strongly suggest not using all-catching except clauses as this silences and wrongly handles errors that may happen that are not a part of your expected flow.
I'd start by changing your except to say except (ValueError, TypeError) so that it only catches errors resulting from bad input / type conversion issues. You'll then be able to see what the real error is.
Also, note that there is no such thing as move.tolower - you probably meant move.lower(). Maybe that's your bug?
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? "))
I've started Python today, on a raspberry pi, and I wanted to create password protected menu. It all works except the options keep appearing after I enter an option.
This is my code can anyone tell me what is wrong with it please, I have kept it all here so you guys could see what is wrong. Like I said I get the first one, shutdown or items but when I enter 1 or 2 it repeats it, ignoring the if statement.
ans = True
while ans:
print("""
1. Shutdown
2. Items
""")
ans=input("Please enter a number: ")
if ans == "1":
exit()
elif ans == "2":
pa=input("Please Enter Password: ")
if pa == "zombiekiller":
print("""
1. Pi password
2. Return To Menu
""")
else:
print("You Have Entered An Inccorect Password. Terminating Programm")
import time
time.sleep(1)
exit()
exit doesn't do anything. Just putting it, alone, on a line dereferences the name but doesn't invoke it. Perhaps you meant to call it?
exit()
To step out of a while loop you could also use break, which is a statement:
while True:
print('Ending this loop')
break
If you're using python 2.7, input will try and interpret your input as a python expression, returning the number 1, not the string "1". Always use raw_input to get a string from the user.
In python 3, the old input has been removed, and the old raw_input has been renamed to input.