Line 8: ValueError: invalid literal for int() with base 10: ' ' - python

I'm a beginner programmer. I want to write a program that gives me the maximum product of all the products of 4-adjacent digits in an input number.
So, if the input is "12345678"
Possible selections are 1234, 2345,3456,4567,5678 and the largest product is 5*6*7*8.
My code:
number = str(input("Enter a number:"))
i = 0
L = []
while (i!=len(number)-3):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
print(L)
print(number)
print(max(L))
I need to apply this to a 1000-digited number. My code works for 8-digited input number and gave an answer for a 500-digited number.
But I tried it with a 600-digited number and it throws this error.
I understand ValueError is an error that appears when the argument given to a function call has correct type, but inappropriate value. There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
the error is for '' an empty string that cannot be converted to an integer. But I cannot understand where/why the empty string was formed.
I have read a few other answers of this Error type, but all involve code that use features of Python I am NOT familiar with and hence cannot understand. I'm just a beginner! So, please help!
And apologies for breaking any rules laid out with regards to question formation!

You've got a space there, not an empty string. Most likely, you just hit the space bar at the end of your input, and Python can't convert that to an integer. You can either just ensure that you don't leave a space at the end, or do some checking of your input (e.g., add a line number = number.strip() to remove any trailing whitespace).

Validate your input as numeric, and strip any whitespace:
number ='123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
def foo(number):
number = number.strip()
if number.isdigit():
i = 0
L = []
while (i in range(len(number)-3)):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
return max(L)
This functions should return a None if user has provided invalid input (e.g., "Alexander"), this should avoid the error you describe:
There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
You can also simplify this using a generator statement for a set of only the unique results:
def foo2(number):
number = number.strip()
if number.isdigit():
return max({int(number[i]) * int(number[i+1]) * int(number[i+2]) * int(number[i+3]) for i in range(len(number)-3)})

Related

I write the code in python to count digits of a number but It doesn't work for some numbers

In order to count digits of a number I write this code in python:
a=int(input('number: '))
count=0
while a!=0:
a=a//10
count=count+1
print('number has ',count,'digits')
It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...
It say:
ValueError: invalid literal for int() with base 10: '3**21'
3**21 is integer input So why it gives this erroer,and How Should I fix this?
The int() constructor accepts string representation of ints, which 2**5 is not, this is an math operation, you may use eval to compute that. I've add an additionnal variable value to keep track of the initial value and print it at then end
value = eval(input('number: '))
a = value
count = 0
while a!=0:
a = a//10
count += 1
print(value, 'has', count, 'digits')
⚠️ CAREFULL eval is dangerous
You can try
a=input('number: ') # entered 3**21
if a.isalnum():
a = int(a)
else:
exec("a = {}".format(a))
count=0
while a!=0:
a=a//10
count=count+1
print('number has ',count,'digits')
Output
number has 11 digits
This code will cast a to int only if a contained only digits else it will execute python command to store the expiration that entered to expiration and not int.
Neither '3^21' nor '3**21' are integers. They are strings with Python expressions that would evaluate to integers if the Python interpreter evaluated them.
>>> 3^21
22
>>> 3**21
10460353203
The int builtin only accepts strings such as '100', '22' or '10460353203'.
(int also has a base argument that defaults to 2 and allows you to issue commands like int('AA', 16), but it still does not allow you do pass the kind of string-expressions you are trying to pass.)
You must eval() the expression first if you want an integer
eval('3**21')
# 10460353203
and to simply count digits (like digits number is string length) :
num_digits = len(str(eval('3**21')))
print(num_digits)
# 11
So your code could be :
a=input('number: ')
num_digits = len(str(eval(a)))
print('number has ',num_digits,'digits')

Integer to letters with a loop

I'm trying to create a program on python that will take 3 integers and convert them into letter's using their ASCII but I'm not sure what is wrong with this program. Can you help me?
num = []
letter = []
x = 0
numx = 0
for x in range(0,3):
numx = int(input('Enter an integer'))
num.append(numx)
letter.append(str(chr(num[x]))
print(letter)
I think your issue is just that you only have two closing parens for three open parens in the third line of the loop. Making the change, your code seems to work for me.
Also, since you're doing the append inside the loop, there's no reason to use num[x] instead of numx directly. Unless you're using it for something else, you can get rid of num entirely. And your call to str is unnecessary.
To convert ASCII numbers into a string, you could do the following:
letters = []
for x in range(0,3):
numx = int(input('Enter an integer: '))
letters.append(str(chr(numx)))
print(''.join(letters))
For example:
Enter an integer: 65
Enter an integer: 66
Enter an integer: 67
ABC
letters is a list of the numbers converted to letters, and the join() is used to concatenate them all together (without adding anything between them).

Why does using regular expression to check the input from user give me error message in Python?

I am a new Python learner. I wrote the code below which is for a program that reads a number (eg. 1234), adds up all the digits (the result would be 10), and displays the result.
It works if I remove the regular expression part. However, I would like to know why the code does not work with it?
import re
numbers= int(input("Enter a number e.g. 1234 :"))
n=re.match('(\d+)', number)
if n:
total = 0
for number in numbers:
total += number
print ("The total sum is:",total)
else:
print ("invalid input!")
Thank you all!
re.match returns a match instance:
>>> import re
>>> number='123' # just an example
>>> re.match('(\d+)', number)
<_sre.SRE_Match object; span=(0, 3), match='123'>
What you need is what was matched:
>>> re.match('(\d+)', number).group()
'123'
An example of why the regex might be useful is the case of removing unwanted strings. For example:
>>> number='123 kg'
>>> re.match('(\d+)', number).group()
'123'
To sum over digits:
>>> number='123 kg'
>>> digits = re.match('(\d+)', number).group()
>>> sum(int(c) for c in digits)
6
Regex is for matching and comparing against strings. When you convert the input to int regex will fail because it is no longer comparing to a string.
Also, you cannot iterate over an integer. I think what you want to do is to check if the string input is all digits, then iterate over the digits in the string, convert them to ints, and sum as you go.
try this:
import re
number= input("Enter a number of variable length e.g. 73618 :")
n=re.match('(\d+)', number)
if n:
total = 0
for digit in number:
total += int(digit)
print ("The total sum of digits is:",total)
else:
print ("Error! Make sure you only use numbers")
As per python docs :
re.match(pattern, string, flags=0)
If zero or more characters at the beginning of string match the
regular expression pattern, return a corresponding MatchObject
instance. Return None if the string does not match the pattern
So what you need to do here is check if the returned value from regex is not None.
ie, if n is not None:
The other answers got pieces right, but it really is much simpler than what you're making it anyway.
You're getting the error because re.match works with strings, not integers, so you need:
number = input("Enter a number of variable length e.g. 73618 :")
Also, if re does not match, it will return None. None is not the same as False:
if n is not None: ...
It also doesn't work if you mix numbers and letters (e.g. 9f). The solution is very simple though. You don't need to use re at all:
number = input("Enter a number of variable length e.g. 73618 :")
if number.isdigit():
total = 0
for digit in number:
total += digit
print ("The total sum of digits is:",total)
else:
print("Error! Make sure you only use numbers")
If you are only trying to enter a single number, a regular expression might be a bit overkill here. When you use Python's int() function to convert a string into a number, it will give you an error if the string contains letters. You can catch this using exception handling as follows:
try:
number_string = input("Enter a number of variable length e.g. 73618 : ")
number = int(number_string) # try and convert the string into a number
total = 0
for digit in number_string:
total += int(digit)
print ("The total sum of digits is:", total)
except ValueError as e:
print ("Error! Make sure you only use numbers")
You could also make use of Python's sum() function to help with the totalling:
try:
number_string = input("Enter a number of variable length e.g. 73618 : ")
number = int(number_string) # try and convert the string into a number
total = sum(int(digit) for digit in number_string)
print ("The total sum of digits is:", total)
except ValueError as e:
print ("Error! Make sure you only use numbers")

How can we take raw input in a single line with a whitespace between them, then convert them into integers and add them to a list?

My code:
number = raw_input().split()
# I can't get a line here to do the trick
a = list()
a.append(number)
All I need to do is enter 2 integers in a single line separated by a whitespace. Then enter them as integers in a Python list and then add the elements back into the result variable.
This splits everything you enter at whitespace and tries to convert each entry into an integer:
numbers = [int(x) for x in raw_input().split()]
This is a list comprehension. It does the same as this code:
numbers = []
for x in raw_input().split():
numbers.append(int(x))
The list comprehension is shorter. If you need to handle potential exceptions and your code gets more complicated, the loop might be more suitable.
Further improvement - Error Handling
There is always the possibility that the user enters erroneous data.
def get_numbers(count=2):
"""Get `count` integers from one line of user input.
"""
numbers = []
msg = 'Please enter {} integers separated by space: '.format(count)
for entry in raw_input(msg).split():
try:
numbers.append(int(entry))
except ValueError:
print('Found bad value: {}.'.format(entry))
return get_numbers()
if len(numbers) != count:
print('Need to enter exactly {} numbers. '
'Found: {}.'.format(count, len(numbers)))
return get_numbers()
return numbers
my_two_numbers = get_numbers()
You can map to int but any bad input will raise a valueError:
numbers = map(int,raw_input().split())
A safer approach would be a try/except to catch when the user enters bad input:
while True:
number = raw_input().split()
try:
# try casting to int
numbers = map(int, number)
break
except ValueError:
# user entered bad input so print message and ask again
print("Invalid input")
print(numbers) # list of ints
That will also allow one number or more than two numbers so if you want exactly two you need to check the length after splitting. You also have a list after splitting so a is not needed.
In order to avoid, bad input and forbidden characters I would use regex to search and then cast:
valid_integers = map(int, re.findall(r'-?\d+', user_input)) # cast found strs to ints

number/numbers to list by using input() [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit() part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.

Categories