Type conversion: str()
You already know how to use the int() and float() functions to convert a string into a number.
This type of conversion is not a one-way street. You can also convert a number into a string, which is way easier and safer - this kind of operation is always possible.
A function capable of doing that is called str():
str(number)
To be honest, it can do much more than just transform numbers into strings, but that can wait for later.
The "right-angle triangle" again
Here is our "right-angle triangle" program again:
leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))
We've modified it a bit to show you how the str() function works. Thanks to this, we can pass the whole result to the print() function as one string, forgetting about the commas.
You've made some serious strides on your way to Python programming.
You already know the basic data types, and a set of fundamental operators. You know how to organize the output and how to get data from the user. These are very strong foundations for Module 3. But before we move on the next module, let's do a few labs, and recap all that you've learned in this section.
Objectives
Scenario
Your task is to complete the code in order to evaluate the results of four basic arithmetic operations.
The results have to be printed to the console.
You may not be able to protect the code from a user who wants to divide by zero. That's okay, don't worry about it for now.
Test your code - does it produce the results you expect ?
We won't show you any test data - that would be too simple.
What I wrote:
vara = float(input("Input variable a number here: " ))# input a float value for variable a here
varb = float(input("Input variable b number here: "))# input a float value for variable b here
print("Variable a plus Variable b is", vara + varb)# output the result of addition here
print("Variable a minus Variable b is", vara - varb)# output the result of subtraction here
print("Variable a multiplied by Variable b is", vara * varb)# output the result of multiplication here
print("Variable a divided by Variable b is", vara / varb)# output the result of division here
print("\nThat's all, folks!")