[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.

  1. 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.
  2. What built-in function do you use to convert a string into an integer?
  3. What happens when you try to convert a string into an integer but the string is not a number?

Solution:

  1. To convert a string into a floating-point number, you use the float() function:
x = float('85')
print(x)  # Output: 85.0
  1. 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)
  1. 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'
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *