I am testing that the user input is of length 10 and only contains numbers. At the moment, my code is:
while True:
number = input("Enter number: ")
try:
if len(number) != 10:
print ("Enter 10 digits\n")
continue
except ValueError:
print ("Enter only numbers\n")
continue
else:
break
The program will ask for user input, then test that it is of 10 length and only contains integers.
Currently, user input is read as a string so that if it began with a '0', then this would be included in len(), if you know what I mean? For example, if I inputted '0123456789', this would be seen to have a length of 10 and not 9 because it begins with '0'.
Also, I wanted to ensure that if the user entered 10 letters, this would be declined because only numbers are allowed.
Any help would be greatly appreciated.
Thank you.
At no point in your code do you actually check that the input is an integer..
You could do something like this:
while True:
number = input("Enter number: ")
if not number.isdigit(): # check if a string contains a number with .isdigit()
print ("Enter only numbers\n")
continue
elif len(number) != 10:
print ("Enter 10 digits\n")
continue
else:
break
Info on str.isdigit():
Type: method_descriptor
String Form:<method 'isdigit' of 'str' objects>
Namespace: Python builtin
Docstring:
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
while True:
number = input("Enter number: ")
try:
number = int(number)
except ValueError:
print ("Enter only numbers")
else:
if 10 > number//10**9 > 0 :
print ("Enter 10 digits")
continue
else:
break
You can checking for an error while casting to a number (integer)
try:
if len(number) != 10 and int(number):
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue
Note that the flaw in len(number) is that the nine firsts digit could be 0.
To ensure that is a valid number beetwen 1000000000 and 999999999 you can do the following:
import math
while True:
try:
if math.floor(math.log10(int(number)))+1 == 10:
print ("Your number is good!")
break
else :
print("Your number isn't good!")
continue
except ValueError:
print('only digit please')
continue
Related
Write a python program to ask a user to input a 6-digit integer and check if the input is a palindrome or not. If the user fails to enter an integer or if the integer is less than 6-digit, the user must be asked to input it again.
(NOTE: The code should be written without using TRY and EXCEPT and the user should not be allowed to take more than 3 attempts.)
My take on this is:
for n in range(3):
while True:
i = input("Please enter a six digit integer:")
if i.isnumeric():
if len(i)==6:
i_integer = int(i)
print("Your number is:",i_integer,"and the data type is:",type(i_integer))
break
else:
print("Enter value is not numeric")
With this code, if I enter a six-digit number, then I have to enter it for 3 times, instead of one time. Below is the output.
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Is there any better way to do this without using TRY and EXCEPT?
Instead of a "for" loop, you could just use a counter and "while" loop like the following code snippet.
tries = 0
while True:
i = input("Please enter a six digit integer:")
if i.isnumeric() and len(i) == 6:
i_integer = int(i)
print("Your number is:",i_integer,"and the data type is:",type(i_integer))
break
else:
tries += 1
if tries >= 3:
break
if tries >= 3:
print("Sorry - too many tries to enter a six digit integer")
quit()
# Palindrome testing would start here
print("Going to see if this is a palindrome")
Testing this out, the following output was displayed on my terminal.
#Una:~/Python_Programs/Palindrome$ python3 Numeric.py
Please enter a six digit integer:12345
Please enter a six digit integer:123456
Your number is: 123456 and the data type is: <class 'int'>
Going to see if this is a palindrome
I will leave it to you to build the test to see whether or not the entered number is a palindrome.
Give that a try.
tries = 0
while True:
i = input("Please enter a six digit integer:")
if i.isnumeric() and len(i) == 6:
i_integer = int(i)
print("Your number is:",i_integer,"and the data type is:",type(i_integer))
# Palindrome testing would start here
print("Going to see if this is a palindrome")
n=int(i)
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
break
else:
tries += 1
if tries >= 3:
break
if tries >= 3:
print("Sorry - too many tries to enter a six digit integer")
I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()
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)
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 answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.