What is a Type Conversion Function?
- A type conversion function is a function with the same name as the data type to which it converts.
- Because the input() function returns a string as its value, you must use the function int to convert the string to a number before performing arithmetic.
- Example
| Conversion Function | Example Use | Value Returned |
|---|---|---|
| int() | int(4.88) | 4 |
How Does the Input Function Work?
- The input() function pauses your program and waits for the user to enter some text. Once Python receives the user’s input, it stores it in a variable.
- The function takes one argument, the prompt, or the instructions, that we want to display to the user so they know what to do.
Putting It All Together with Integers:
- As an example, let’s compute an object’s momentum, given an object’s mass and velocity. Momentum = Mass * Velocity
python
1# Get Values for variables
2mass = int(input("Enter the object's mass: "))
3velocity = int(input("Enter the object's velocity: "))
4
5# Do Calculations
6momentum = mass * velocity
7
8# Display Results
9print("The object's momentum is " + str(momentum))Output:
1Enter the object's mass: 2
2Enter the object's velocity: 3
3The object's momentum is 6