+ 1

Is there a more Pythonic way to approve inputted digits?

I'm writing a program that only allows the user to enter digits from 1-6. Any other characters should be rejected. I've found a method that works, but it just seems... off somehow. Any improvement suggestions? allowed = ["1", "2", "3", "4", "5", "6"] while True: nums = input("Enter a four-digit number: ") if not (nums[0] and nums[1] and nums[2] and nums[3]) in allowed: print("All digits entered must be an integer from 1-6") continue

9th Dec 2022, 3:22 AM
Savager
7 ответов
+ 8
Savager , an other solution could be using the filter() function with a short lamba: while True: inp = input('enter a 4-digit number 1-6: ') if len(list(filter(lambda x: x in '123456', inp))) == 4: break print(inp)
10th Dec 2022, 9:36 AM
Lothar
Lothar - avatar
+ 6
Herre an example using function all ....or as an alternative: regex each one of them does the job. https://code.sololearn.com/cW53MrBPpsug/?ref=app
9th Dec 2022, 7:35 AM
Oma Falk
Oma Falk - avatar
+ 6
here is a strange syntax expanding on Oma Falk's regex solution. A while-else loop with an ellipsis pass.😁 (you can use '...' or 'pass') no 'break' or 'continue', too. import regex as re while not re.match("^[1-6]{4}
quot;, n:=input("input a 4-digit number using digits 1 to 6\n")): ... else: print(n, "valid input")
9th Dec 2022, 9:35 AM
Bob_Li
Bob_Li - avatar
+ 4
There are many different ways you could accomplish this. Here's an example converting the entered value to a list of integers and checking them to make sure each is in the range of 1-6. Also, I added a check to make sure that exactly 4 values are entered. Note that if a value other than an int is entered, there will be an error that will need to be handled. while True: nums = list(map(int, input("Enter a four-digit number: "))) if len(nums) == 4: break for num in nums: if not 1 <= num <= 6: print("\nAll digits entered must be an integer from 1-6") break else: print(f"\nSuccess, you entered: {''.join(map(str, nums))}")
9th Dec 2022, 5:50 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
Steve nice!
12th Dec 2022, 11:06 AM
Oma Falk
Oma Falk - avatar
+ 3
Bob_Li cool stuff🤓😎
9th Dec 2022, 5:12 PM
Oma Falk
Oma Falk - avatar
+ 3
A method using sets: allowed = frozenset('123456') while ...: n = input("Enter a four-digit number: ") if len(n) == 4 and \ set(n) - allowed == set(): break print("All 4 digits entered must be an integer from 1-6")
11th Dec 2022, 11:33 AM
Steve
Steve - avatar