How to properly validate the length of a number - python

I would like to be able to check weather the user has inputed a 8-digit number, not for example, a 7 digit number, and tell them that the number they inputted is too long or not long enough.
For reference here is the input:
cardNumber = input("What is your 8 digit card number: ")

I guess you can use len() function.
Something like if len(cardnumber) != 8: print("Please, input 8 digit number.").

You can use the usual len:
Python 3:
cardNumber = input("What is your 8 digit card number?")
s = len(cardNumber)
if s < 8: print("Too short")
elif s > 8: print("Too long")
else: print("Right Length")
Python 2:
cardNumber = raw_input("What is your 8 digit card number?")
s = len(cardNumber)
if s < 8: print("Too short")
elif s > 8: print("Too long")
else: print("Right Length")
Generally, you can get the number of digits of an integer by using len(str(number))

In case you want to loop until the user has entered the correct number:
try:
input = raw_input # make this Python 2.6+ and 3.5+ compatible
except NameError:
pass
while True:
cardNumber = input("What is your 8 digit card number: ")
if len(cardNumber) == 8:
break
if len(cardNumber) < 8:
print("Your number is not long enough, please try again...")
elif len(cardNumber) > 8:
print("Your number is too long, please try again...")
print("Thank you, your number is: {}".format(cardNumber)

If your are using Python 2, use raw_input instead of input, which will always return a string:
>>> cardNumber = raw_input("What is your 8 digit card number: ")
What is your 8 digit card number: 00000001
>>> len(cardNumber)
8
In Python 2, raw_input will return the entered value as string, while input will evaluate the entered value as code, et is equivalent to eval(raw_input(prompt)).
You can check that with the following code:
>>> cardNumber = input("What is your 8 digit card number: ")
What is your 8 digit card number: 2 + 4
>>> cardNumber
6
With Python 3, however, the old raw_input was renamed to input, and the old input does not exists, although you can still achieve the same with eval(input()).
Once you have the string representation of the card number, you can use len to get the number of characters.
However, I would rather use Regex to validate the input instead of just checking the length, as you may have letters or other symbols as well. You can wrap the whole thing in a loop to keep asking until a valid value is entered. Assuming you are using Python 3, it will look like this:
import re
from termcolor import colored
while True:
cardNumber = input("What is your 8 digit card number: ")
if not re.match('[0-9]{8}', cardNumber):
print(colored("\nThe entered value is not valid. Please, try again.\n", "red"))
else:
break

Related

How to write a code to get a user input for a 6 digit integer number and check if the number is palindrome?

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")

How do i convert the input into an int?

I tried using int() to convert the input into int, but I just get a TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'. How do i solve this?
import random
number = random.randint(1, 50)
lives = 10
guess = int(print("Enter a number between 1 and 50: "))
while guess != number and lives != 0:
if guess > number:
guess = int(print("Your guess is higher than the secret number. Enter another guess: "))
lives -= 1
else:
guess = int(print("Your guess is lower than the secret number. Enter another guess: "))
lives -= 1
if guess == number:
print("You win!")
else:
print("You lose!")
Doesn't print() just show some text?
Try using:
guess = int(input("Enter a number between 1 and 50: "))
https://www.geeksforgeeks.org/taking-input-in-python/
guess = int(input("Enter a number between 1 and 50: "))
By default input takes everything as a string. And we convert the type afterwards.
guess = int(print("Enter a number between 1 and 50: ")) is wrong.
it should be
guess = int(input('enter a number between 1 and 50: '))
You are attempting to cast the output of print() to int when, as the error message suggests, print() outputs None.
If you replace the line 6 "print" with "input" your code will work (as seems expected) with python 3.

"if" statement not working on input variable [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
Well, I am a beginner and my variable (guess) input doesn't work with the if statement:
When I put on the input numbers from 0 to 9, I want it prints out Right number!, else it print out the other message:
guess = input("Choose a number between 0-9: ")
if guess <=9 and guess >=0:
print("Right number!")
else:
print("The number you entered is out of range try again!")
The input() function returns a string, not a number (e. g. "127", not 127). You have to convert it to a number, e. g. with the help of int() function.
So instead of
guess = input("Choose a number between 0-9: ")
use
guess = int(input("Choose a number between 0-9: "))
to obtain an integer in guest variable, not a string.
Alternatively you may reach it in 2 statements - the first may be your original one, and the second will be a converting one:
guess = input("Choose a number between 0-9: ")
guess = int(guess)
Note:
Instead of
if guess <=9 and guess >=0:
you may write
if 0 <= guess <= 9: # don't try it in other programming languages
or
if guess in range(10): # 0 inclusive to 10 exclusive

Checking user input to see if it satisfies two conditions

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)

Checking input is a number in python

I need help, my program is simulating the actions of a dice. I want to an error check to occur checking if the input string is a number and if it isn't I want to ask the question again again until he enters an integer
# This progam will simulate a dice with 4, 6 or 12 sides.
import random
def RollTheDice():
print("Roll The Dice")
print()
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
Repeat = True
while Repeat == True:
if not NumberOfSides.isdigit() or NumberOfSides not in ValidNumbers:
print("You have entered an incorrect value")
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides")
print()
UserScore = random.randint(1,NumberOfSides)
print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore))
RollAgain = input("Do you want to roll the dice again? ")
if RollAgain == "No" or RollAgain == "no":
print("Have a nice day")
Repeat = False
else:
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
As a commenter disliked my first answer with try: except ValueError and the OP asked about how to use isdigit, that's how you can do it:
valid_numbers = [4, 6, 12]
while repeat:
number_of_sides = 0
while number_of_sides not in valid_numbers:
number_of_sides_string = input("Please select a dice with 4, 6 or 12 sides: ")
if (not number_of_sides_string.strip().isdigit()
or int(number_of_sides_string) not in valid_numbers):
print ("please enter one of", valid_numbers)
else:
number_of_sides = int(number_of_sides_string)
# do things with number_of_sides
the interesting line is not number_of_sides_string.strip().isdigit(). Whitespace at both ends of the input string is removed by strip, as a convenience. Then, isdigit() checks if the full string consists of numbers.
In your case, you could simply check
if not number_of_sides_string not in ['4', '6', '12']:
print('wrong')
but the other solution is more general if you want to accept any number.
As an aside, the Python coding style guidelines recommend lowercase underscore-separated variable names.
Capture the string in a variable, say text. Then do if text.isdigit().
Make a function out of:
while NumberOfSides != 4 and NumberOfSides != 6 and NumberOfSides != 12:
print("You have selected the wrong sided dice")
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
And call it when you want to get input. You should also give an option to quit e.g. by pressing 0. Also you should try catch for invalid number. There is an exact example in Python doc. Note that input always try to parse as a number and will rise an exception of it's own.
You can use type method.
my_number = 4
if type(my_number) == int:
# do something, my_number is int
else:
# my_number isn't a int. may be str or dict or something else, but not int
Or more «pythonic» isinstance method:
my_number = 'Four'
if isinstance(my_number, int):
# do something
raise Exception("Please, enter valid number: %d" % my_number)

Categories