I'm having this annoying problem in Python 2.7, it won't let me do this
numbers = raw_input(numbers + 1 + ': ')
I want it to print out 'numbers + 1' as a number in the console but..
It comes up with this error message:
Traceback (most recent call last):
File "F:/Python/Conversation", line 25, in <module>
numbers = raw_input(numbers + 1 + ': ')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Is there a solution or just another thing that I can use instead of this?
Thanks in advance!
As the error message points out, you cannot add a number and a string. You can add two strings, so try this:
raw_input( str(numbers+1) + ':' )
You need to put + and numbers inside a single/double quote; or else, it will be treated as a string concatenation. You got the error because you tried to concatenate/add numbers with 1.
So, you need to cast 1 to a string, using str( ). Then, concatenate it with 'numbers + ' and ':'. Like so:
>>> numbers = raw_input('numbers + ' + str(1) + ': ')
numbers + 1:
However, If you want to replace numbers with number:
>>> numbers = 3
>>> numbers = raw_input(str(numbers + 1) + ': ')
4:
It works because you add the numbers's value with 1 first. Then, cast the result to string later.
You need to turn the 1 int value into a string:
numbers = raw_input(numbers + str(1) + ': ')
Alternatively, use string formatting:
numbers = raw_input('{}{}: '.format(numbers, 1))
Or perhaps you wanted to turn numbers into an int first, then the result into a string:
sum = int(numbers) + 1
numbers = raw_input(str(sum) + ': ')
Related
I am trying to create a program that is sort of an "expander". If you were to give it a number like 1234, it should return "1000 + 200 + 30 + 4". However, I keep getting an int object is not subscript able error even thought I made proper conversions.
I have tried having new_str = num[int(i)] ... but that still doesn't work.
def expanded_form(num):
count = len(str(num))-1
new_str = ""
for i in range(0,len(str(num))):
new_str += num[i] * 10**count + " + "
count -= 1
return new_str
print(expanded_form(1234))
The problem is inside the for loop, you're writing num[i], that's what's giving you the error since num is an int and you can't really access an index of an int.
You're trying to get the number on that index and multiply it by 10 ** count. To do that should try this
new_str += str(int(str(num)[i]) * 10 ** count) + ' + '
You first have to turn num into a string to get the number on that position, but it returns it as a string, so you have to parse it back to int in order to multiply it with 10 ** count, and then you have to turn it into a string again in order to concatenate it with ' + '.
If you want to avoid parsing it so many times try doing this inside the for loop
new_str = str(num)[i] + '0' * count + ' + '
Instead of mutiplying it by a power of 10 you can use the fact that count is the number of zeros that should follow str(num)[i]
Your error is telling you that you cannot subscript an integer. Here: num[i]. num is an integer. You should cast it again to a string.
This said, to do what you want you need to recast the digit num[i] to an int in order to do the math.
def expanded_form(num):
count = len(str(num))-1
new_str = []
for i in range(0,len(str(num))):
new_str.append(int(str(num)[i]) * 10**count)
count -= 1
return ' + '.join(map(str, new_str))
print(expanded_form(1234))
Note that I made new_str a list and use join to build the string with the sum, to get rid of the extra '+' at the end. I also needed map to convert back all the integers to string otherwise join does not work.
I'm currently creating a program that sums the input from the user and returns it as a float.
When I try to run the code below with inputs such as "20.1", I receive ValueError: could not convert string to float: '.'
Shouldn't 20.1 be accepted as a float value?
abc = []
i = 0
while True:
i += 1
item = input("Transaction " + str(i) + ": ")
if item == '':
break
abc.extend(item)
abc = [float(k) for k in abc]
print(sum(abc[0:len(abc)]))
When you do abc.extend('20.1') you get ['2', '0', '.', '1'] and the issue is that you can't convert . to float, as the error message suggests. You want to use abc.append(item) instead.
This is because extending a list by an iterable object means appending each element of the iterable to the list. A string is iterable over its characters.
For what it's worth, you can also do sum(abc) straight up, you don't need to do do sum(abc[0:len(abc)]).
you should use append instead of extend.
abc = []
i = 0
while True:
i += 1
item = input("Transaction " + str(i) + ": ")
if item == '':
break
abc.append(item)
abc = [float(k) for k in abc]
print(sum(abc[0:len(abc)]))
There are specific inputs for specific things. You want to use the float input
float(input())
raw_input and input are for strings
int(input)
Are for integers
I am trying to make s programme that takes text and gives back to the user every 3rd letter including the first letter.This is what i wrote.
msg = input('Message? ')
for i in range(len(msg)):
(i) = (i*3)
print(msg[i], end=' ')
This gives back every thurd letter including the 1st letter but then also gives the error:
File "program.py", line 4, in
print(msg[i], end=' ')
IndexError: string index out of range
Also the software I am using says: Testing the first example but ignoring whitespace. Your submission raised an exception of type IndexError. This occurred on line 4 of your submission.
Whats the simplest way to fix this?
Let's say you have the string "Here we are". It has length 11. You are letting i go all the way to the end of the string, but once i reaches 4, that string at index i * 3 (12) is not defined. Instead, you shouldn't go farther than i divided by 3 (rounding down). This is how you would do that:
msg = input('Message? ')
for i in range((len(msg) // 3) + 1):
(i) = (i*3)
print(msg[i], end=' ')
what you want to do can easily be achieved by slicing the string
msg = input('Message? ')
print(msg[::3])
This should work:
msg = input("Message?: ")
count = 1
for i in msg:
if count % 3 == 0:
print("First char in string is " + msg[0] + ", the third is " + i)
count += 1
You can increment the range in steps of 3:
msg = input('Message? ')
for i in range(0, len(msg), 3):
print(msg[i], end=' ')
When I run this piece of code, the shell outputs the error 'Can't convert 'int' object to str implicitly'.
I have tried other fixes on StackOverflow, however I wasn't able to fix the issue in my code.
import math
while True:
try:
di = input('Input 7 digit number ')
total = (int(di[0])+int(di[2])+int(di[4])+int(di[6]))*3+(int(di[1])+int(di[3])+int(di[5]))
if len(str(di)) != 7:
print('Incorrect')
if len(str(di)) == 7:
print('Okay')
multiplier = [3,1]
times = ''
total = 0
for index, digit in enumerate(list(str(di))):
total = total + int(digit)*multiplier[index%2]
times = times+str(int(digit)*multiplier[index%2])+', '
mof10 = total + (10 - total%10)
checkdigit = mof10 - total
final = str(di) + str(checkdigit)
print(times[:-1])
print(total)
print(mof10)
print(checkdigit)
print(final)
final = (di[1]+di[3]+di[5])+((di[0]+di[2]+di[4]+di[6])*3)
final = (final+4)
Base10=(int(round(final, -1)))
Check = Base10-final
checkdigit = int(input('8th number in product code: '))
if (n8 == Check):
print('Valid product code')
except ValueError:
print('Invalid product code')
break
Error message:
Traceback (most recent call last):
File "C:\Documents and Settings\User\Desktop\GTIN-8 product code.py", line 55, in
final = (final+4)
TypeError: Can't convert 'int' object to str implicitly
You first get the value d1 as a str
di = input('Input 7 digit number ')
Then you get final by
final = (di[1]+di[3]+di[5])+((di[0]+di[2]+di[4]+di[6])*3)
Therefore final is a str too, so you can't do
final = (final+4)
because final is a str and 4 is an int
You can't add integers to strings in Python. You need to convert them both to integers or strings.
final = int(final) + 4 # convert final from string to integer and add 4
or
final = final + '4' # append the string '4' to the end of the string final.
Changing the above line will stop the error, but I think you have other parts of your code where you are using strings where you should be using integers.
For example, If di=1234567, then di[0], di[1], and so on are strings.
Therefore di[0]+di[2]+di[4]+d[6] is the string '1357', not 1+3+5+7=16. And when you do di[0]+di[2]+di[4]+d[6] * 3, the string is repeated three times '135713571357'.
You might find it easiest if you create a list of integers at the beginning of your code:
di = [int(x) for x in str(di)]
Then di[0], di[1] and so on will be integers.
integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + rslt)
double = input("Point Number: ")
print('2.5 + ' +double+' = ' +(float(double)+2.5))
Gives me
Traceback (most recent call last):
File "C:\...", line 13, in <module>
print('2 + ' + integer + ' = ' + rslt)
TypeError: Can't convert 'int' object to str implicitly
I'm fairly new to programming and my background is mostly just the basics of C# so far. I wanted to try to learn Python through doing all my C# school projects on Python. I'm used to the simple syntax of C# which would look something like this:
int integer = Convert.ToInt32(Console.ReadLine())
or
double double = Convert.ToDouble(Console.ReadLine())
Which takes a user input string and converts it to what I specified.
I think I read py2.x has a command called raw_input that works a bit better than the input command of py3.x in this regard.
I was trying to find myself a similar format as the one I'm used to in C# to use in Python, but it's proving surprisingly hard just to find a method to convert the user input string into an integer after all this googling and trying everything I could think of (and that I found on google) I decided it was time to ask. Can you help?
You have to convert the integer into a string:
print('2 + ' + str(integer) + ' = ' + str(rslt))
Or pass it as an argument to print and print will do it for you:
print('2 +', integer, '=', rslt)
I would do it using string formatting:
print('2 + {} = {}'.format(integer, rslt))
Your problem is not with converting the input to an integer. The problem is that when you write ' = ' + rslt you are trying to add an integer to a string, and you can't do that.
You have a few options. You can convert integer and rslt back into strings to add them to the rest of your string:
print('2 + ' + str(integer) + ' = ' + str(rslt))
Or you could just print multiple things:
print('2 + ', integer, ' = ', rslt)
Or use string formatting:
print('2 + {0} = {1}'.format(integer, rslt))
In Python 3.x - input is the equivalent of Python 2.x's raw_input...
You should be using string formatting for this - and perform some error checking:
try:
integer = int(input('something: '))
print('2 + {} = {}'.format(integer, integer + 2))
except ValueError as e:
print("ooops - you didn't enter something I could make an int of...")
Another option - that looks a bit convoluted is to allow the interpreter to take its best guess at the value, then raise something that isn't int or float:
from ast import literal_eval
try:
value = literal_eval(input('test: '))
if not isinstance(value, (int, float)):
raise ValueError
print value + 2
except ValueError as e:
print('oooops - not int or float')
This allows a bit more flexibility if you wanted complex numbers or lists or tuples as input for instance...
If you want to convert a value to an integer, use the int built in function, and to convert a value to a floating point number, use the float built in function. Then you can use the str built in function to convert those values back to strings. The built in function input returns strings, so you would use these functions in code like this:
integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + str(rslt))
double = input("Point Number: ")
print('2.5 + ' +str(double)+' = ' +str(float(double)+2.5)
integer = int(input("Number: "))
print('2 + %d = %d' % (integer, integer + 2))
double = float(input("Point Number: "))
print('2.5 + %.2f = %.2f' % (double, double + 2.5))