Checking If Input Is In A List Of Numbers In Python
numbers = [1,2,3,4,5,6,7] x = input() if x in numbers: print("Hey you did it") else: print("Nope")
I'm not sure what I'm doing wrong here, but it always tells me that my number is not in the list.. even though it is. Works fine with strings, though.
Help would be appreciated. Thanks!
Input is a string, so you are comparing strings to integers. First convert to an int then do the membership test:
numbers = [1,2,3,4,5,6,7] x = input() if int(x) in numbers: print("Hey you did it") else: print("Nope")
To make this slightly more robust, you should handle the
ValueError that will occur if the user does not input an integer (there's always one user who will enter 'cheeseburger' instead of a number):
numbers = [1,2,3,4,5,6,7] x = input() try: i = int(x) if i in numbers: print("Hey you did it") else: print("Nope") except ValueError: print("You did not enter a number")
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module