concatenation of strings and variables - python

What I need is for it to print "the sum of 1 and 2 is 3". I'm not sure how to add a and b because I either get an error or it says "the sum of a and b is sum".
def sumDescription (a,b):
sum = a + b
return "the sum of" + a " and" + b + "is" sum

You cannot concat ints to a string, use str.format and just pass in the parameters a,b and use a+b to get the sum:
def sumDescription (a,b):
return "the sum of {} and {} is {}".format(a,b, a+b)
sum is also a builtin function so best to avoid using it as a variable name.
If you were going to concatenate, you would need to cast to str:
def sumDescription (a,b):
sm = a + b
return "the sum of " + str(a) + " and " + str(b) + " is " + str(sm)

Use string interpolation, like this. Python will internally convert the numbers to strings.
def sumDescription(a,b):
s = a + b
d = "the sum of %s and %s is %s" % (a,b,s)

You are trying to concatenate string and int.
You must turn that int to string before hand.
def sumDescription (a,b):
sum = a + b
return "the sum of " + str(a) + " and " + str(b) + " is " + str(sum)

Related

How to remove the error of 'can only concatenate str (not "float") to str' in Python while returning a string?

I am trying to calculate a percentage of landmass occupied by a country from the total landmass.I am taking two arguments as string and float in a function and returning String along with the calculated percentage in it. For example the Input =area_of_country("Russia", 17098242) and Output = "Russia is 11.48% of the total world's landmass". Below is my code
class Solution(object):
def landmass(self, st, num):
percentage = 148940000 / num * 100
return st + "is" + percentage + "of total world mass!"
if __name__ == "__main__":
s = "Russia"
n = 17098242
print(Solution().landmass(s, n))
Error :-
return st + "is" + percentage + "of total world mass!"
TypeError: can only concatenate str (not "float") to str
You need to cast the percentage (since it's a float) into a string when concatenating using the + operator. So your return statement would look like:
return str(st) + "is" + str(percentage) + "of total world mass!"
instead of this:
return st + "is" + percentage + "of total world mass!"
Try this:
return str(st) + "is" + str(percentage) + "of total world mass!"

putting str and int together 4 times not working [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 4 years ago.
I have this python program that adds strings to integers:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b
a = int(a)
b = int(b)
c = a + b
str(c)
print "a + b as integers: " + c
I get this error:
TypeError: cannot concatenate 'str' and 'int' objects
How can I add strings to integers?
There are two ways to fix the problem which is caused by the last print statement.
You can assign the result of the str(c) call to c as correctly shown by #jamylak and then concatenate all of the strings, or you can replace the last print simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
str(c) returns a new string representation of c, and does not mutate c itself.
c = str(c)
is probably what you are looking for
If you want to concatenate int or floats to a string you must use this:
i = 123
a = "foobar"
s = a + str(i)
c = a + b
str(c)
Actually, in this last line you are not changing the type of the variable c. If you do
c_str=str(c)
print "a + b as integers: " + c_str
it should work.
Apart from other answers, one could also use format()
print("a + b as integers: {}".format(c))
For example -
hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
will result in output - Time elapsed - 13 hours and 32 minutes
Check out docs for more information.
You can convert int into str using string function:
user = "mohan"
line = str(50)
print(user + "typed" + line + "lines")
The easiest and least confusing solution:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c
I found this on http://freecodeszone.blogspot.com/
I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():
rolling = True; import random
while rolling:
roll = input("ENTER = roll; Q = quit ")
if roll.lower() != 'q':
num = (random.randint(1,6))
print("----------------------"); print("you rolled " + str(num))
else:
rolling = False
main()
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.
This is what i have done to get rid of this error separating variable with "," helped me.
# Applying BODMAS
arg3 = int((2 + 3) * 45 / - 2)
arg4 = "Value "
print arg4, "is", arg3
Here is the output
Value is -113
(program exited with code: 0)

Python - simple interest

I am trying to write a code for myself that will give me an answer for simple interest, I will use same concept and later make compound interest. I am having trouble with my rate. when I do it as a percentage like
r = int(input("rate %: ")
and I type 5.4 it does not work so I tried it in a decimal form like this
r = int(input("Rate 0."))
i get the same answer at end if i do 0.045 and 0.45
so how do i fix this problem
here is my entire code
while True:
while True:
print('Working out for SIMPLE INTEREST')
p = int(input("Principl:"))
r = int(input("Rate 0."))
t = int(input("Time yrs:"))
i = p*r
i = i*t
a = p + i
print("Interest = " + str(i))
print("Accumalated = " + str(a))
print(str(p) + ' x ' + str(r) + ' x ' + str(t) + ' = ' + str(i) + ' | ' + str(p) + ' + ' + str(i) + ' = ' + str(a))
int converts the input string to an integer, which is a whole number like 4 or 5. For 5.4, you want a floating point number, which you can make using the float function:
r = float(input("rate %: "))
(For professional usage, you might even consider the arbitrary-precision decimal package, but it's probably overkill in your situation.)
It is because int does not support decimal numbers
So change int(input('something...')) to input('sonething...')

How to print numbers in steps using function python

Am trying to write a function to print numbers in steps.Here is my code
def steps(num):
v = num
for i in range(1, v+1):
print(" "*i + str(i)*3)
print(steps(3))
The result appears as
111
222
333
None
I am trying to get rid of the "none" word any help? Note please, i don't want to get rid of the print statement in "print(steps(3)), any other method or solution will be welcomed.
You need to output the spaces yourself like so:
for i in range(1, v + 1):
print(" " * i + str(i) * 3)
def steps(number):
mystr = ""
for i in range(1, number + 1):
mystr += 3*str(i) + '\n' + i*'\t'
return mystr

turning variables that use 'str()' into numbers

I'm trying to apply the math.floor function to a some variables that use the str() function... what is the proper way to do this?
Here's my code:
import math
x = str(10.3)
y = str(22)
z = str(2020)
print "x equals " + x
print "y equals " + y
print "z equals " + z
#playing around with the math module here. The confusion begins...
#how do I turn my str() functions back into integers and apply the floor function of the math module?
xfloor = math.floor(x)
zsqrt = math.sqrt(z)
print "When we print the variable \"xfloor\" it rounds " + x + "down into " + xfloor + "."
print "When we print the variable \"zsqrt\" it finds the sqareroot of " + z + "which is " + zsqrt + "."
raw_input("Press the enter key to continue.")
Any and all assistance is welcome.
Cast them back :
xfloor = math.floor(float(x))
zsqrt = math.sqrt(float(z))
But this is not a recommended practice as you are converting it to str unnecessarily. To print use str.format
print "x equals {}".format(x)
For this you do not need to cast to str.

Categories