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))
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
in my program I have to organize stings to be of a certain length, in this case I set the max length to a. when I set it up the way I written below, I get an error in the python visualizer that I am using a unsupported format character. I can't use format or ljust to format my answer.
a =9
string = '%(a)s' % 'k'
print (string + 'KITE')
the problem is I know this will work if the variable a was a number, so what is going on?
edit- the desired out put would be ' kKITE'
EDIT:
If rjust is not allowed either:
>>> s = '%s' % (' '*8 + 'k')
>>> s + 'KITE'
' kKITE'
I believe you are looking for rjust:
>>> 'kKITE'.rjust(9)
' kKITE'
Or for your example:
>>> s = ('%s' % 'k').rjust(8)
>>> s + 'KITE'
' kKITE'
a = 9
string = "%s" %('k' * a)
print (string + 'KITE')
>> 'kkkkkkkkkKITE'
a = 9
string = "%s%s" %(' ' * a, 'k')
print (string + 'KITE')
>> ' kKITE'
I'm trying to make an algorithm in Python 2.7.10 that takes user input, splits it and puts words into a list, then takes all words from that list and prints them in a specific manner.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
print "You think that the painting is:"
print "%s" + ", %s" * len(input) + "." % ( > ? < )
The %s formatters work as placeholders. The problem is that the number of placeholders that will be printed as a part of the string isn't fix, it's equal to len(input). Therefore I don't know how to assign values to these formatters. (That's the " > ? < " part inside of the brackets.)
Note: as this is for test purposes only, let's assume the user will only be inputting strings, not integers, etc. so that there is no need for the %r formatter.
The desired output should look somewhat like this:
> nice pretty funny
You think that the painting is:
nice, pretty, funny.
I know this can be achieved using the str.join(str) method but is there a way of doing it as I explained above? Thanks.
Use print ("%s" + ", %s" * (len(input) - 1) + ".") % tuple(input)
However, IMO ', '.join(input) + '.' is better :)
You can do what you want by doing this:
print ",".join(["%s"] * len(input)) % tuple(input)
Basically, construct your string of "%s, "... and pass the input as a list to the string formatters. You can do it exactly like you've written it too, just pass in your list.
print "%s" + ", %s" * len(input)) + "." % tuple(input)
You should use a tuple after "%". Note that you have already considered the first word in the print, so len(input) -1 words are left to be written.
usr_input = raw_input(' > ')
input = usr_input.split(' ')
output = "%s" + ", %s" * (len(input) - 1) + "."
print "You think that the painting is:"
print output % tuple(input)
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) + ': ')