I'm taking a python intro course so this stuff is still fairly basic, but any help would be greatly appreciated.
I've tried multiple things, I know that the comma in a print statement automatically adds a space, but I can't add a plus and the period without getting an error
here is my code:
bonus = survey_completers / class_size
avg = my_current_average + bonus
rounded_bonus = round(bonus, 1)
rounded_avg = round(avg, 1)
textOne = str("After the")
textTwo = str("point bonus, my average is")
textThree = str(".")
print(textOne, rounded_bonus, textTwo, rounded_avg, textThree)
giving the output:
After the 0.5 point bonus, my average is 87.6 .
When expected output is that sentence with the period right behind the 87.6
I've tried things such as:
bonus = survey_completers / class_size
avg = my_current_average + bonus
rounded_bonus = round(bonus, 1)
rounded_avg = round(avg, 1)
textOne = str("After the")
textTwo = str("point bonus, my average is")
print(textOne, rounded_bonus, textTwo, rounded_avg + ".")
which gives me this error:
Traceback (most recent call last):
File "CIOSBonus.py", line 40, in <module>
print(textOne, rounded_bonus, textTwo, rounded_avg + ".")
TypeError: unsupported operand type(s) for +: 'float' and 'str'
Command exited with non-zero status 1
Using f-strings:
bonus = survey_completers / class_size
avg = my_current_average + bonus
rounded_bonus = round(bonus, 1)
rounded_avg = round(avg, 1)
result = f"After the {rounded_bonus} point bonus, my average is {rounded_avg}."
print(result)
You can convert the float to a string:
print(textOne, rounded_bonus, textTwo, str(rounded_avg) + ".")
You can also set sep="", default is sep=" "
print(textOne, " ", rounded_bonus, " ", textTwo, " ", rounded_avg, ".", sep="")
Another option is to use f-strings:
print(f"{textOne} {rounded_bonus} {textTwo} {rounded_avg}.")
You can also use string formatting:
print("%s %f %s %f." %(textOne, rounded_bonus, textTwo, rounded_avg))
%s is string
%i is int
%f is float
I think that using f-strings is the best and cleanest way.
Also, when creating a string you don't have to have str("").
For example:
x = "Test String"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With