'How to return a position of elements in a list using only positive number?
I created a list for the user to enter a number, which is the position of the elements in the list, but it still work for negative number. Are there anyway to stop the program taking in negative numbers and accept only positive ones?
Preferably not using conditional statements.
Here is my code:
userInput = int(input("Please enter a number from 0-4: "))
lNation = ["Canada", "Australia", "Japan", "Korea", "USA"]
print ("With",userInput,"you have chosen",lNation[userInput])
Solution 1:[1]
def positive_number_between_0_and_4():
while True:
try:
val = int(input("Enter a number(0-4)"))
except ValueError:
print("hmm thats not an integer...")
else:
if 0 <= val <= 4:
return val
print("That number is not between 0 and 4")
choice = positive_number_between_0_and_4()
print(f"You choose: {choice}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joran Beasley |