Check for blank entry - python

I am trying to get an input from a user and if it is blank entry I should see message with("please enter numbers")
I have tried using if statement and setting it equal to None.
def get_player_numbers():
number_csv = input("Enter your 6 numbers, separated by commas: ")
if number_csv == None:
print("Enter something")
get_player_numbers()
else:
number_list = number_csv.split(",")
integer_set = {int(number) for number in number_list}
return integer_set
I should be able to see
("Please enter digits , input can't be blank")

input() always returns a string. Blank input return an empty string:
if number_csv == '':
print("Please enter digits , input can't be blank")
Due to the implicit falsehood of empty strings, this can be simplified to:
if not number_csv:
print("Please enter digits , input can't be blank")

I don't think this would compile because you are going to get an End Of File error. You should use raw_input() instead of input(). The difference is input() returns an object of type python expression, while raw_input returns a string. You are going to want to compare strings in this case. Your new code would be...
def get_player_numbers():
number_csv = raw_input("Enter your 6 numbers, separated by commas: ")
if number_csv == "":
print("Enter something")
return get_player_numbers()
else:
number_list = number_csv.split(",")
integer_set = {int(number) for number in number_list}
return integer_set
Note: now your if statement compares the input value to "" instead of None.
Edit: Thanks for the comment! I fixed the recursive call by adding a return statement if the user enters a blank. This needs to happen or when the user finally enters something the output will be None.

I'd recommend you to use regular expression (test) to test input:
import re
def get_player_numbers():
integer_set = None
while not integer_set:
number_csv = input("Enter your 6 numbers, separated by commas: ")
if not re.match("([0-9]+,){5}[0-9]+", number_csv):
print("Invalid input.")
else:
number_list = number_csv.split(",")
integer_set = {int(number) for number in number_list}
return integer_set
res = get_player_numbers()
print(res)
Output:
Enter your 6 numbers, separated by commas:
Invalid input.
Enter your 6 numbers, separated by commas: 1,2
Invalid input.
Enter your 6 numbers, separated by commas: some-word
Invalid input.
Enter your 6 numbers, separated by commas: 1,2,3,4,5,6

Related

How do i get rid of the term none here and what is it?

I've created a basic addition statement, i am aware that input is being read as a string but my code prints out "none" before taking an input (see below). How do i take integer as an input??
# code example
print("This is a calculator")
a = input(print("Enter the first number"))
b = input(print("Enter the second number"))
print("sum =", a + b)
This outputs:
This is a calculator
Enter the first number
None5
Enter the second number
None6
sum = 56
remove print() in the first two lines:
a = input("Enter the first number")
b = input("Enter the second number")
instead of:
a = input(print("Enter the first number"))
b = input(print("Enter the second number"))
None is the return of the print() function so since input() prints what you input to it you are printing the returned None value. Then the print statement will still print the prompt. However you want to let input() print the prompt as described above.
input() prints the prompt for you. You just have to enter a = input("Enter the first number")

How can I manage to make this input only integers answer and rejected string. This include .split()

Good day everyone, I would like to ask about this problem which I need to make the outcome only Integers and not string
If I put string in the Input.. it will make error and If i place number it will print the number
example:
num = int(input("Enter number only: ")).split(",")
print(num)
Assuming the user gives a comma-delimited input 7,42,foo,16, you can use a try block to only add numbers, and pass over strings:
nums = []
user_input = input("Enter a series of numbers separated by commas: ")
input_fields = user_input.split(",")
for field in input_fields:
try:
num.append(int(field))
except ValueError:
pass
for num in nums:
print(str(num))
I would do this:
user_input = input("Enter a series of numbers separated by commas: ")
input_fields = user_input.split(",")
int_list = []
for i in input_fields:
int_list.append(int(i)) # you may want to check if int() works.

Length Validation

So were given a task that enters 6 digits, I want to put a length validation in my list because i had already done my number validation. for some reason even though i entered six numbers it prints ("6 digits only! Please try again"). anyways this is my code (pardon for the code construction since I just started learning python)
while True:
numbers = input("Enter 6 digits: ")
if numbers.isalpha():
print("Invalid Input!", numbers ," is not a number!")
else:
NumberList = numbers.split()
if len(NumberList) == 6:
print("user list is ", NumberList)
break
else:
print ("6 digits only! Please try again")
The split function, called without arguments, splits on whitespaces.
So, your string is not splitted to a list (you obtain only a list with one element, your string).
print("123456".split())
['123456']
To split the string, in this case, you have to use: NumberList = list(numbers).
list("123456")
['1', '2', '3', '4', '5', '6']
The input would surely give you a string and so you can use the split function, but it expects spaces by default.
So splitting this string would result in ['splitting,'this','string'], but something like 123456, results in ['123456'] and so the length is always one.
The way to solve this, is to convert the string to a list:
Replace
NumberList = numbers.split()
with
NumberList = list(numbers)
This should result in ['1','2','3','4','5','6'] and so should give you a proper length.
The string.split() method with no argument specified, will create a list of substrings, by splitting the original string at any white spaces. If your input is, say 123456, then numbers.split() will produce ["123456"] since the input string doesn't have any white spaces. In that case, len(NumberList) is 1 and that's why it fails your validation.
You could instead just check for len(numbers) == 6.
If you want to turn "123456" into ["1", "2", "3", "4", "5", "6"] (since it seems that's what you want to print), you can use list(numbers)
while True:
numbers = input("Enter 6 digits: ")
if numbers.isalpha():
print("Invalid Input!", numbers ," is not a number!")
else:
NumberList = len(numbers)
if NumberList == 6:
print("user list is", NumberList)
break
else:
print ("6 digits only! Please try again")
I assume your input is something like "123456", first of all, your check str.isalpha() will return true only if all the element of the string are letters, meaning that "123asd" would be considered False, and therefore valid for your program, which is a mistake, secondly str.split() will only separate the string according to a separator char, the default one is the blank space, if your line is "123456", the result of split, will just be a list of one element with the full string, because there is no space in that line.
while True:
numbers = input("Enter 6 digits: ")
if sum([n.isalpha() for n in numbers]):
print("Invalid Input!", numbers ," is not a number!")
else:
NumberList = list(numbers)
if len(NumberList) == 6:
print("user list is ", NumberList)
break
else:
print("6 digits only! Please try again")
Also, there is no need to split the string to a list, if the only operation you need to do is check its lenght, you can just use len(numbers)
while True:
num = input("Enter a Number: ")
try:
numbers = [int(i) for i in num]
if len(numbers) == 6:
print('valid')
numbers = numbers[:5]
print(numbers)
else:
print('invalid')
except ValueError:
print('only numbers')
The number validation is incorrect if you only want numbers. I tried entering numbers first then letters and I got through it.

"Try and Except" to differentiate between strings and integers? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number)
def validation(i):
try:
result = int(i)
return(result)
except ValueError:
print("Please enter a number")
def start():
x = input("Enter Number: ")
z = validation(x)
if z != None:
#Rest of function code
print("Success")
else:
start()
start()
When the above code is executed, and an integer number is entered, you get this:
Enter Number: 1
Success
If and invalid value however, such as a letter or floating point number is entered, you get this:
Enter Number: Hello
Please enter a number
Enter Number: 4.6
Please enter a number
Enter Number:
As you can see it will keep looping until a valid NUMBER value is entered. So is it possible to use the "try and except" function to keep looping until a letter is entered? To make it clearer, I'll explain in vague structured English, not pseudo code, but just to help make it clearer:
print ("Hello this will calculate your lucky number")
# Note this isn't the whole program, its just the validation section.
input (lucky number)
# English on what I want the code to do:
x = input (luckynumber)
So what I want is that if the variable "x" IS NOT a letter, or multiple letters, it should repeat this input (x) until the user enters a valid letter or multiple letters. In other words, if a letter(s) isn't entered, the program will not continue until the input is a letter(s). I hope this makes it clearer.
You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit:
def validate_integer():
x = input('Please enter a number: ')
try:
int(x)
except ValueError:
print('Sorry, {} is not a valid number'.format(x))
return validate_integer()
return x
def start():
x = validate_integer()
if x:
print('Success!')
Don't use recursion in Python when simple iteration will do.
def validate(i):
try:
result = int(i)
return result
except ValueError:
pass
def start():
z = None
while z is None:
x = input("Please enter a number: ")
z = validate(x)
print("Success")
start()

How to allow strings in a float input?

So I'm asking my user to input a number(float)
num=float(input("Please enter a number"))
but I'm also asking the user to enter the value "q" to quit
and since this variable can only take in floats, the program is not letting the user enter the string ("q"), is it possible to do this?
Expect a string and parse it has as a float only if it is not equal to q.
temp = input("Please enter a number")
if not temp == "q":
num = float(temp)
You're trying to automatically cast your input to a float. If you don't want to do this in all cases you should add some if/else logic in here:
input_string = input("Please enter a number")
if not input_string == 'q':
num = float(intput_string)
Or, to be a bit more pythonic you should do a try/except strategy:
input_string = input("Please enter a number")
try:
num = float(input_string)
except ValueError:
if input_string == 'q':
# However you exit
The second is technically more pythonic according to the EAFP principle (https://docs.python.org/2/glossary.html)

Categories