Length Validation - python

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.

Related

Cannot get output for more than one user defined digit

def main():
Need the code to ask the user a number and print out number in words digit by digit.
Ex. Input: 473
Output: four seven three
numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
n = eval(input('Please input a number: '))
print('You typed a number: ',n)
print('The number in words: ', numbers[n])
Cannot get code here to print out more than one digit. I have tried a few for loops and always get the error message with my index
main()
Because your list has 10 items and it can not find index for example 324
so you should split your number into digits and try it for each digit.
numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
n = int(input('Please input a number: '))
print('You typed a number: ',n)
print('The number in words: ', end="")
for char in str(n):
print(numbers[int(char)], end=" ")
print()
You are basically trying to access an eleent in an array(your array only have 10 elements, so works fine for n<=10) that doesn't exist. You need to extract the digits, and try for every digit.
you can put numbers in a dictionary
numbers = {'0': 'zero', '1': 'one', '2': 'two', etc...}
then loop throw the user's string:
for number in n:
print(numbers[number] + " ", end='')
here is version that uses a list comprehension:
numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
inp = input()
print(" ".join([numbers[int(dig)] for dig in inp]))

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.

Check for blank entry

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

Python one line for loop input

I don't know how to get input depending on user choice. I.e. 'How many numbers you want to enter?' if answers 5, then my array has 5 spaces for 5 integers in one line separated by space.
num = []
x = int(input())
for i in range(1, x+1):
num.append(input())
Upper code works, however inputs are split by enter (next line). I.e.:
2
145
1278
I want to get:
2
145 1278
I would be grateful for some help.
EDIT:
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
This seems to work. But why I'm getting "Memory limit exceeded" error?
EDIT:
Whichever method I use, I get the same problem.
x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)
or
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
array = list(map(int, num))
print(max(array)-min(array)-x+1)
or
z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)
Assuming you want to input the numbers in one line, here is a possible solution. The user has to split the numbers just like you did in your example. If the input format is wrong (e.g. "21 asd 1234") or the number does not match the given length, the user has to enter the values again, until a valid input is made.
x = int(input("How many numbers you want to enter?"))
while True:
attempt = input("Input the numbers seperated with one space")
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)==x:
print(num)
break
else:
print("You have to enter exactly %s numbers! Try again"%x)
except:
print("The given input does not match the format! Try again")
The easiest way to do this would be something like this:
input_list = []
x = int(input("How many numbers do you want to store? "))
for inputs in range(x):
input_number = inputs + 1
input_list.append(int(input(f"Please enter number {input_number}: ")))
print(f"Your numbers are {input_list}")
Is there a reason you want the input to be on one line only? Because you can only limit how many numbers you store (or print) that way, not how many the user inputs. The user can just keep typing.
You can use this without needing x:
num = [int(x) for x in input().split()]
If you want the numbers to be entered on one line, with just spaces, you can do the following:
x = int(input("How many numbers do you want to store? "))
y = input(f"Please enter numbers seperated by a space: ")
numbers_list = y.split(" ")[:x]
print(f"We have a list of {len(numbers_list)} numbers: {numbers_list}")
Even if someone enters more than the amount of promised numbers, it returns the promised amount.
Output:
How many numbers do you want to store? 4
Please enter numbers seperated by a space: 1 4 6 7
We have a list of 4 numbers: ['1', '4', '6', '7']
Try this.
x = int(input())
num = [] # List declared here
while True:
try:
# attempt moved inside while
# in case input is in next line, the next line
# will be read in next iteration of loop.
attempt = input()
# get values in current line
temp = [int(val) for val in attempt.split(" ")]
num = num + temp
if len(num) == x:
break
except:
print('Error2')
Maybe the bot was passing integers with newline instead of spaces, in which case the while loop will never terminate (assuming your bot continuously sends data) because every time, it will just re-write num.
Note - this code will work for both space as well as newline separated inputs

Python ISBN program

I'm trying to calculate the check digit for an ISBN input on python. so far I have...
def ISBN():
numlist = []
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
**numlist == request
print numlist**
if len(request) != 10:
print "Invalid Input"
ISBN()
ISBN()
The bold bit is where im having trouble, I cant seem to split the 10 digit input into individual numbers in the list (numlist) and then multiply the seperated individual numbers by 11 then the next by 10 then the next by 9 etc...
For the next part of the program, I will need to add these new multiplied numbers in the list together, then i will use the mod(%) function to get the remainder then subtract the number from 11, any assistance with any of my coding or incorrect statements on how to calculate the ISBN would be greatly appreciated.
Thank you.
This code should get you on your way:
listofnums = [int(digit) for digit in '1234567890']
multipliers = reversed(range(2,12))
multipliednums = [a*b for a,b in zip(listofnums, multipliers)]
Strings are iterable, so if you iterate them, each element is returned as a single-character string.
int builds an int from a (valid) string.
The notation [a*b for a,b in zip(listofnums, multipliers)] is a list comprehension, a convenient syntax for mapping sequences to new lists.
As to the rest, explore them in your repl. Note that reversed returns a generator: if you want to see what is "in" it, you will need to use tuple or list to force its evaluation. This can be dangerous for infinite generators, for obvious reasons.
I believe list() is what you are looking for.
numlist=list(request)
Here is how I would write the code. I hope I'm interpreting the code correctly.
def ISBN():
request = raw_input("Please enter the 10 digit number: ")
if len(request) == 10:
numlist = list(request)
print numlist
else:
print "Invalid Input"
ISBN()
import itertools
if sum(x * int(d) for x, d in zip(nums, itertools.count(10, -1))) % 11 != 0:
print "no good"

Categories