[PriP 1.1] Revision Tour-1 – Practical 1.1
Table of Contents
4. While taking input from input()
, you need to convert the input into float
and int
types, if you are reading numbers.
- What built-in function do you use to convert a string into a floating-point number? Demonstrate this function by converting string ’85’ into a floating-point number and assigning it to a variable x.
- What built-in function do you use to convert a string into an integer?
- What happens when you try to convert a string into an integer but the string is not a number?
Solution:
- To convert a string into a floating-point number, you use the
float()
function:
x = float('85')
print(x) # Output: 85.0
- To convert a string into an integer, you use the
int()
function. Example:
# Convert the string '85' into an integer
string_number = '85'
integer_number = int(string_number)
print(integer_number)
- If you try to convert a string into an integer but the string is not a number, you’ll get a
ValueError
.
# Attempt to convert the string 'hello' into an integer
string_non_number = 'hello'
# This will raise a ValueError
integer_non_number = int(string_non_number)
print(integer_non_number)
Output
ValueError: invalid literal for int() with base 10: 'hello'