How to limit input integer in single digit? [python] [duplicate] - python

This question already has answers here:
Python excepting input only if in range
(3 answers)
Closed 2 years ago.
what's the easiest way to limit this code integer input to a single digit?
num = ["First","Second","Third"]
num_list = []
for a in num:
x = int(input(f"Enter Your {a} number: "))
num_list.append(x)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(num_list[i],num_list[j],num_list[k])

just a quick fix
def get_single_digit_input():
while True:
a = input('please enter number')
if not a.isnumeric():
print('please enter single digit Numeric only')
continue
a = int(a)
# your logic is here
if a<=9 and a>=0:
return a
else:
print('please enter single digit Numeric only')
a = get_single_digit_input()

You can check using a while statement. If the input is not a single digit, force it back to the input statement. Also you want to check if the input is a digit and not an alphabet or special character.
Here's a way to do it: I am using the walrus operator in python 3.9
while len(x:=input('Enter a single digit :')) > 1 or (not x.isnumeric()):
print ('Enter only a single digit')
print (x)
If you are using python < 3.9, then use this.
x = ''
while True:
x = input ('Enter a single digit :')
if (len(x) == 1) and (x.isnumeric()): break
print ('Enter only a single digit')
print (x)

Related

Python: Create an infinite list that takes user input in [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Hey I'm trying to create an infinite list in python that takes user input in till 0 is entered, I don't really know if this is the right way to do so, here's what I did:
`n = input("Enter a list element separated by space ")
while n == 0:
break
else:
list = n.split()
print(list)`
Thank you!
This code will do what you originally described:
Numbers = []
while True:
number = int(input("Please enter a number:"))
if number == 0:
break
Numbers.append(number)
print(Numbers)
try this
l = []
while 1:
n = input("Enter a list element seperated by a space")
for x in n.split():
if x == 0:
break
l.append(int(x))

how to display matching digits in a string from another number [duplicate]

This question already has answers here:
How to compare string and integer in python? [duplicate]
(2 answers)
Closed 2 years ago.
I'm newbie to python. I'm trying to find matching digits in a string from a given number. I have tried the following code:
st=input("Enter a string")
no=int(input("Enter a number"))
for i in range(len(st)):
while no>0:
rem=no%10
if rem == st[i]:
print(rem)
Here's a code snippet for you:
# Number input
mynumber = input("Enter a number: ")
# Check if input is an integer
try:
int(mynumber)
except ValueError:
print("Sorry, not a number")
# String input
mystring = input("Enter a string: ")
# Look for matching numbers in the string and display them
match = ''
for n in mynumber:
for s in mystring:
if n == s and not n in match:
match += n
print('Matching:', match if match else 'None')

input is taking integer as string object [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
am trying to take input from user forcefully and execute it in Fibonacci elements program, having problem near input i want to make sure that he doesn't enter character nor -ve number, when i take my input as int(input()) my while loop wont execute i want it to keep executing until user provides input.
in below program when i entered 5 as input it taking it as string object
n=input("enter no of fibonnaci elements: ")
while not n:
n=input("enter no of fibonnac elements: ")
print(type(n))
if(n!=int()):
print("enter integer only")
else:
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
You can use isinstance(n,int)to check if it is an int. But if you use int(input("enter no of fibonnaci elements:"))then it will throw a ValueError before it.
n=int(input("enter no of fibonnaci elements: ")) #convert to int here
while not n: #will not enter this loop - why is it even here?
n=input("enter no of fibonnac elements: ")
if(not isinstance(n,int)): #Note: won't Reach this line - Will throw an error before this
print("enter integer only")
else:
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
A better way to do this
while True:
try:
n=int(input("enter no of fibonnaci elements: "))#convert to int here
break
except ValueError:
print("enter integer only")
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
print(t1,end=" ")
t1,t2=t2,(t1+t2)
print()
Output
enter no of fibonnaci elements: str
enter integer only
enter no of fibonnaci elements: 6
series is: 0 1 1 2 3 5

How do I let users input any number of input values in Python? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 years ago.
For example, if you wanted to accept say 2 input values it would be something like,
x = 0
y = 0
line = input()
x, y = line.split(" ")
x = int(x)
y = int(y)
print(x+y)
Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space.
How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.
You can set a parameter how many values there will be and loop the input and put them into a map - or you make it simple 2 liner:
numbers = input("Input values (space separator): ")
xValueMap = list(map(int, numbers.split()))
this will create a map of INT values - separated by space.
You may want to use a for loop to repeatedly get input from the user like so:
num_times = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(num_times):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)
Then, later on, you can use an if/elif/else chain to do different actions to the numbers based on the length of the list (found using the len() function).
For example:
if len(numbers) == 0:
print("Try again") #Or whatever you want
elif len(numbers) == 1:
print(numbers[0])
else:
print(sum(numbers))
Try something like this. You will provide how many numbers you want to ask the user to input those many numbers.
def get_input_count():
count_of_inputs = input("What is the number you want to count? ")
if int(count_of_inputs.strip()) == 0:
print('You cannot have 0 as input. Please provide a non zero input.')
get_input_count()
else:
get_input_and_count(int(count_of_inputs.strip()))
def get_input_and_count(count):
total_sum = 0
for i in range(1,count+1):
input_number = input("Enter number - %s :"%i)
total_sum += int(input_number.strip())
print('Final Sum is : %s'%total_sum)
get_input_count()

How to validate an input with a 4-digit number? [duplicate]

This question already has an answer here:
Python Checking 4 digits
(1 answer)
Closed 1 year ago.
I want to write a program that only accepts a 4-digit input from the user.
The problem is that I want the program to accept a number like 0007 but not a number like 7 (because it´s not a 4 digit number).
How can I solve this? This is the code that I´ve wrote so far:
while True:
try:
number = int(input("type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
print("Good! The number you wrote was", number)
But if I input 7 to it it will just say Good! The number you wrote was 7
Before casting the user's input into an integer, you can check to see if their input has 4 digits in it by using the len function:
len("1234") # returns 4
However, when using the int function, Python turns "0007" into simple 7. To fix this, you could store their number in a list where each list element is a digit.
If it's just a matter of formatting for print purposes, modify your print statement:
print("Good! The number you wrote was {:04d}", number)
If you actually want to store the leading zeros, treat the number like a string. This is probably not the most elegant solution but it should point you in the right direction:
while True:
try:
number = int(input("Type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
# determine number of leading zeros
length = len(str(number))
zeros = 0
if length == 1:
zeros = 3
elif length == 2:
zeros = 2
elif length == 3:
zeros = 1
# add leading zeros to final number
final_number = ""
for i in range(zeros):
final_number += '0'
# add user-provided number to end of string
final_number += str(number)
print("Good! The number you wrote was", final_number)
pin = input("Please enter a 4 digit code!")
if pin.isdigit() and len(pin) == 4:
print("You successfully logged in!")
else:
print("Access denied! Please enter a 4 digit number!")

Categories