How to narrow input of a integer to a certain length like "7" (per example) from a user raw_input:
def number():
number=int(input("Number:"))
print(number)
number=1234567
It has to have an while condition where it says if len(number) < 7 or len(number) > 7:
print("Error")
phone=int(input("Number:"))`
Thank you & Merry Xmas
check the length before you try casting to int:
def number():
while True:
i = input("Number:")
if len(i) > 7:
print("Number can only contain at most 7 digits!")
continue
try:
return int(i)
except ValueError:
print("Invalid input")
If you want exactly 7 use if len(i) != 7 and adjust the error message accordingly. I also used a try/except as because the length is seven does not mean it is a valid string of digits. If you want to allow the minus son you could if len(i.lstrip("-")) > 7:
Related
I started learning Python, and I was working on a simple draft number manual, and I had a problem of only 10 digits and no letters or symbols.
this is my code
number = 10
def num():
number = input("Enter the number")
if number == "1111111111":
print("Amal")
elif number == "2222222222":
print("Mohammed")
elif number == "3333333333":
print("Khadijah")
elif number == "4444444444":
print("Abdullah")
elif number == "5555555555":
print("Rawan")
elif number == "6666666666":
print("Faisal")
elif number == "7777777777":
print("Layla")
else:
print("Sorry, the number is not found ")
num()
So, if you want to differentiate the error message for a non-found number and an invalid entry, you would need the following:
1- To check if the input is numeric or if it contains any other symbols, you can use the following:
if number.isdigit():
print("Is a number!")
else:
print("Not a number!")
2- To check for the length, you can simply use:
if len(number) == 10:
print("is 10 digits!")
else:
print("Not 10 digits")
question:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)
This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Check if numbers are in a certain range in python (with a loop)? [duplicate]
(3 answers)
Closed 4 years ago.
Let's say I want the user to input a number between 1 and 50, so I do:
num = input("Choose a number between 1 and 50: ")
But if the user inputs a number that does not fall between 1 and 50, i want it to print:
Choose a number between 1 and 50: invalid number
How can I do that?
num = input("Choose a number between 1 and 50: ")
try:
num = int(num) #Check if user input can be translated to integer. Otherwise this line will raise ValueError
if not 1 <= num <= 50:
print('Choose a number between 1 and 50: invalid number')
except ValueError:
print('Choose a number between 1 and 50: invalid number')
You need the input to be set to an integer since otherwise it would be a string:
num = int(input("Choose a number between 1 and 50: "))
Check what num has been set to:
if 1 < num < 50:
print(1)
else:
print("invalid number")
This is what I might do:
validResponse = False
while(not validResponse):
try:
num = int(input("Choose a number between 1 and 50: "))
if(1 <= num <= 50):
validResponse = True
else:
print("Invalid number.")
except ValueError:
print("Invalid number.")
This is, if you want to prompt them until a correct number has been entered. Otherwise, you can ditch the while loop and validResponse variable.
The try will run the statement until it runs into an error. if the error is specifically that the number couldn't be interpereted as an integer, then it raises a ValueError exception and the except statement tells the program what to do in that case. Any other form of error, in this case, still ends the program, as you'd want, since the only type of acceptable error here is the ValueError. However, you can have multiple except statements after the try statement to handle different errors.
In addition to the above answers, you can also use an assertion. You're likely going to use these more so when you're debugging and testing. If it fails, it's going to throw an AssertionError.
num = input('Choose a number between 1 and 50') # try entering something that isn't an int
assert type(num) == int
assert num >= 1
assert num <= 50
print(num)
You can use an if statement, but you need to assign the input to a variable first then include that variable in the conditional. Otherwise, you don't have anything to evaluate.
num = input('Choose a number between 1 and 50')
if type(num) == int: # if the input isn't an int, it won't print
if num >= 1 and num <= 50:
print(num)
By default, the input provided is going to be a string. You can call the built-in function int() on the input and cast it to type int. It will throw a ValueError if the user enters something that isn't type int.
num = int(input('Choose a number between 1 and 50'))
You could also implement error handling (as seen in Moonsik Park's and Ethan Thomas' answers).
As part of a larger menu-driven program, I'd like to test user input to see if that input:
is an integer AND
if it is an integer, if it is within the range 1 to 12, inclusive.
number = 0
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invlaid input, please try again >>> ")
continue
else:
if not (1<= number <=12):
print("Need a whole number in range 1-12 >>> ")
continue
else:
print("You selected:",number)
break
I'm using Python 3.4.3, and wanted to know if there's a more succinct (fewer lines, better performance, more "Pythonic", e.g.) way to achieve this? Thanks in advance.
You don't need anything bar one if in the try:
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
if 1 <= number <= 12:
print("You selected:", number)
break
print("Need a whole number in range 1-12 >>> ")
except ValueError:
print("Invlaid input, please try again >>> ")
Bad input will mean you go straight to the except, if the input is good and is in your accepted range, the print("You selected:", number) and will be executed then we break or else print("Need a whole number in range 1-12 >>> ") will be executed if is outside the range.
Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary continues):
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invalid input, please try again >>> ")
else:
if 1 <= number <= 12:
print("You selected: {}".format(number))
break
else:
print("Need a whole number in range 1-12 >>> ")
Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one if and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits.
while True:
num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
if num_str.isdigit() and int(num_str) in range(1,13):
print("You selected:",int(num_str))
break
else:
print("Need a whole number in range 1-12 >>> ")
I don't think you need a whole try/except block. Everything can be fit into a single condition:
number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)
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!")