I have been trying to improve my guessing game in Python by limiting the guess input between 2 numbers(1 and 100) and asking if the guess input is a number or not. I have been trying to do this both at the same time. Is there anyway I can do this by minimum coding?
Limiting an input between Two Numbers and checking if the input is a number or not at the same time
9.1k Views Asked by Boran At
2
There are 2 best solutions below
2
bipin_s
On
while True:
try:
number = raw_input("Enter a number between 1 and 100: ")
if number.isdigit():
number=int(number)
else:
raise ValueError()
if 1 <= number <= 100:
break
raise ValueError()
except ValueError:
print("Input must be an integer between 1 and 100.")
it is a small improvement over the answer by @blhsing , so that the program does not crash on string input
Related Questions in PYTHON
- new thread blocks main thread
- Extracting viewCount & SubscriberCount from YouTube API V3 for a given channel, where channelID does not equal userID
- Display images on Django Template Site
- Difference between list() and dict() with generators
- How can I serialize a numpy array while preserving matrix dimensions?
- Protractor did not run properly when using browser.wait, msg: "Wait timed out after XXXms"
- Why is my program adding int as string (4+7 = 47)?
- store numpy array in mysql
- how to omit the less frequent words from a dictionary in python?
- Update a text file with ( new words+ \n ) after the words is appended into a list
- python how to write list of lists to file
- Removing URL features from tokens in NLTK
- Optimizing for Social Leaderboards
- Python : Get size of string in bytes
- What is the code of the sorted function?
Related Questions in EXCEPTION
- Python twisted not catching exception
- Proper use of custom exceptions
- C++ Mongodb driver, not working
- C# console application - Unhandled exception while finding the Available and free Ram space.Getting exact answer in windows forms application
- Hashing String (SHA-256) in an ActionListener class
- Do we have to mention exception type in java?
- How can I make Eclipse (or javac) warn about over-inclusive throws clauses
- Why can an Exception not be rethrown in the BackgroundWorker RunWorkerCompleted event
- How can I set the the expected Exception type for a catch statement with a parameter I've passed into a method?
- Why do I get an IndexOutOfBoundsException when my else should prevent it?
- crypto.BadPaddingException: data hash wrong (EKYC-Response)
- How to print the first line from a traceback stack
- java.lang.ArrayIndexOutOfBoundsException object array
- Passing keyword arguments to custom exceptions - anomaly
- Unauthorised access to folders when creating xml file
Related Questions in ERROR-HANDLING
- Application is missing a default group leaderboard (ItunesConnect error)
- jQuery Ajax Uncaught TypeError: Cannot use 'in' operator to search
- Error return from the pooledBin function (R package binGroup) depending on the method of confidence interval calculation
- How to determine data point that gives error?
- Facelets error page works during ajax request with FullAjaxExceptionHandler, but does not evaluate EL during synchronous request
- why ajax error is different in IE and Chrome?
- Unexceptional exceptions
- What is the difference between Swift 2.0 do-try-catch and regular Java/C#/C++ exceptions
- how to fix error when url is directly entered with no search keywords?
- Errors Handling in WCF - how to pass the error to client as well as remain the channel in the "Open" state
- Ignoring User Exists Error in Oracle
- error for displayed even it has not been submitted yet
- Error handling using poller
- register_shutdown_function with error 500
- Eclipse error parser ignores template "call stack"
Related Questions in LIMITING
- limiting characters after dot - java
- Limiting the use of RAM. (C# .NET)
- How to limit usage of virtual memory by node.js?
- Sum credit and debit transactions where credits have expiries
- Is there a javascript loader which can limit the number of sockets to 1 or 2
- Limiting an input between Two Numbers and checking if the input is a number or not at the same time
- Trying to implement Rate Limiting Policy on API Management in Azure
- Limiting lines per page in BI Publisher
- how to limit the number of entries that print in the array
- Throwing Error/Exception when an unnecessary Argument is sent in PHP
- Limiting RAM usage for program executed through shell script
- Rails: I want to limit the selections available in form.html.erb based on logic
- How to limit speed of outgoing response from php script?
- How can I limit connections to my web application per minute?
- filtering input to only numbers. C
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
You can use a
whileloop to keep asking the user for a valid input until the user enters one: