Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

Menu iconMenu iconPython Programming Unlocked for Beginners
Python Programming Unlocked for Beginners

Chapter 2: Python Basics

2.4 Type Conversion

In this section, we will discuss type conversion in Python. Type conversion, also known as type casting, is the process of converting a value from one data type to another. In Python, you can use built-in functions to perform explicit type conversions. It is important to understand how to convert between different data types because certain operations may only work with specific types, or you may need to ensure that your data is in a suitable format for a particular function. 

2.4.1 Basic Type Conversion Functions

Here are some of the most commonly used type conversion functions in Python:

  • int(): Converts a value to an integer. This function can be used to convert floats to integers or numeric strings to integers.
  • float(): Converts a value to a floating-point number. This function can be used to convert integers to floats or numeric strings to floats.
  • str(): Converts a value to a string. This function can be used to convert integers, floats, or other types to strings.
  • bool(): Converts a value to a boolean. This function can be used to convert integers, floats, strings, or other types to boolean values.

Examples of type conversion: 

x = 5.5
y = int(x)  # Convert float to int, y becomes 5

a = 3
b = float(a)  # Convert int to float, b becomes 3.0

c = 42
d = str(c)  # Convert int to str, d becomes "42"

e = "123"
f = int(e)  # Convert str to int, f becomes 123

g = "True"
h = bool(g)  # Convert str to bool, h becomes True

2.4.2 Type Conversion Limitations

Not all type conversions are valid or possible. For example, if you try to convert a non-numeric string to an integer or a float, a ValueError will be raised: 

s = "hello"
i = int(s)  # Raises a ValueError: invalid literal for int() with base 10: 'hello'

It's important to be aware of the limitations and constraints of type conversions to prevent errors in your code. Always ensure that the value you're trying to convert is compatible with the target data type.

2.4.3 Implicit Type Conversion

Python also performs implicit type conversions, also known as "type coercion," in certain situations. Implicit type conversion occurs when the interpreter automatically converts one data type to another without the programmer explicitly requesting the conversion.

For example, when you perform arithmetic operations between integers and floats, Python automatically converts the integer to a float before performing the operation:

x = 5    # int
y = 2.0  # float

result = x + y  # Python implicitly converts x to a float: 5.0 + 2.0
print(result)  # Output: 7.0

In some cases, implicit type conversion can lead to unexpected results or loss of precision, so it's essential to understand how Python handles different data types in various contexts.

Understanding type conversion in Python is crucial for working with different data types and ensuring your data is in the appropriate format. As you progress through this book, you will encounter various situations where type conversion is necessary or useful for solving programming challenges and working with complex data structures.

Exercise 2.4.1: Shopping List Price Calculator

In this exercise, you will write a Python program that calculates the total price of items on a shopping list. You will practice using type conversion, arithmetic operations, and the print() function.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Declare three variables, item1item2, and item3, representing the prices of three items on the shopping list (e.g., 4.99, 2.75, and 1.25). Use float values for the prices.
  3. Calculate the total price by adding the prices of the three items, and assign the result to a variable named total_price.
  4. Convert the total_price to a string, and round the result to two decimal places using the round() function. Assign the result to a variable named formatted_total.
  5. Use the print() function to display the total price of the shopping list.

Your final code should look something like this:

item1 = 4.99
item2 = 2.75
item3 = 1.25

total_price = item1 + item2 + item3
formatted_total = round(total_price, 2)

print(f"The total price of the shopping list is ${formatted_total}")

When you run your program, you should see output similar to the following:

The total price of the shopping list is $9.0

Feel free to modify the item prices to test your program with different shopping list items. This exercise helps you become familiar with type conversion, arithmetic operations, and the print() function in Python.

Exercise 2.4.2: Calculate the Average of Three Numbers

In this exercise, you will write a Python program that calculates the average of three numbers entered by the user. You will practice using input, output, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter three numbers, and assign the results to variables num1num2, and num3. Remember to convert the input to the appropriate data type (e.g., float or int).
  3. Calculate the average of the three numbers using the formula average = (num1 + num2 + num3) / 3, and assign the result to a variable named average.
  4. Use the print() function to display the calculated average.

Your final code should look something like this:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

average = (num1 + num2 + num3) / 3

print(f"The average of {num1}, {num2}, and {num3} is {average:.2f}")

When you run your program, you should see output similar to the following (depending on user input):

Enter the first number: 4
Enter the second number: 6
Enter the third number: 8
The average of 4.0, 6.0, and 8.0 is 6.00

Exercise 2.4.3: Convert Seconds to Hours, Minutes, and Seconds

In this exercise, you will write a Python program that converts a given number of seconds into hours, minutes, and seconds. You will practice using variables, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter a number of seconds, and assign the result to a variable named total_seconds. Remember to convert the input to the appropriate data type (e.g., int).
  3. Calculate the number of hours, minutes, and remaining seconds using the following formulas:
    • hours = total_seconds // 3600
    • minutes = (total_seconds % 3600) // 60
    • seconds = total_seconds % 60
  4. Use the print() function to display the result in hours, minutes, and seconds.

Your final code should look something like this:

total_seconds = int(input("Enter the number of seconds: "))

hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60

print(f"{total_seconds} seconds is equal to {hours} hours, {minutes} minutes, and {seconds} seconds.")

When you run your program, you should see output similar to the following (depending on user input):

Enter the number of seconds: 3666
3666 seconds is equal to 1 hours, 1 minutes, and 6 seconds.

These exercises help you become familiar with type conversion in Python.

2.4 Type Conversion

In this section, we will discuss type conversion in Python. Type conversion, also known as type casting, is the process of converting a value from one data type to another. In Python, you can use built-in functions to perform explicit type conversions. It is important to understand how to convert between different data types because certain operations may only work with specific types, or you may need to ensure that your data is in a suitable format for a particular function. 

2.4.1 Basic Type Conversion Functions

Here are some of the most commonly used type conversion functions in Python:

  • int(): Converts a value to an integer. This function can be used to convert floats to integers or numeric strings to integers.
  • float(): Converts a value to a floating-point number. This function can be used to convert integers to floats or numeric strings to floats.
  • str(): Converts a value to a string. This function can be used to convert integers, floats, or other types to strings.
  • bool(): Converts a value to a boolean. This function can be used to convert integers, floats, strings, or other types to boolean values.

Examples of type conversion: 

x = 5.5
y = int(x)  # Convert float to int, y becomes 5

a = 3
b = float(a)  # Convert int to float, b becomes 3.0

c = 42
d = str(c)  # Convert int to str, d becomes "42"

e = "123"
f = int(e)  # Convert str to int, f becomes 123

g = "True"
h = bool(g)  # Convert str to bool, h becomes True

2.4.2 Type Conversion Limitations

Not all type conversions are valid or possible. For example, if you try to convert a non-numeric string to an integer or a float, a ValueError will be raised: 

s = "hello"
i = int(s)  # Raises a ValueError: invalid literal for int() with base 10: 'hello'

It's important to be aware of the limitations and constraints of type conversions to prevent errors in your code. Always ensure that the value you're trying to convert is compatible with the target data type.

2.4.3 Implicit Type Conversion

Python also performs implicit type conversions, also known as "type coercion," in certain situations. Implicit type conversion occurs when the interpreter automatically converts one data type to another without the programmer explicitly requesting the conversion.

For example, when you perform arithmetic operations between integers and floats, Python automatically converts the integer to a float before performing the operation:

x = 5    # int
y = 2.0  # float

result = x + y  # Python implicitly converts x to a float: 5.0 + 2.0
print(result)  # Output: 7.0

In some cases, implicit type conversion can lead to unexpected results or loss of precision, so it's essential to understand how Python handles different data types in various contexts.

Understanding type conversion in Python is crucial for working with different data types and ensuring your data is in the appropriate format. As you progress through this book, you will encounter various situations where type conversion is necessary or useful for solving programming challenges and working with complex data structures.

Exercise 2.4.1: Shopping List Price Calculator

In this exercise, you will write a Python program that calculates the total price of items on a shopping list. You will practice using type conversion, arithmetic operations, and the print() function.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Declare three variables, item1item2, and item3, representing the prices of three items on the shopping list (e.g., 4.99, 2.75, and 1.25). Use float values for the prices.
  3. Calculate the total price by adding the prices of the three items, and assign the result to a variable named total_price.
  4. Convert the total_price to a string, and round the result to two decimal places using the round() function. Assign the result to a variable named formatted_total.
  5. Use the print() function to display the total price of the shopping list.

Your final code should look something like this:

item1 = 4.99
item2 = 2.75
item3 = 1.25

total_price = item1 + item2 + item3
formatted_total = round(total_price, 2)

print(f"The total price of the shopping list is ${formatted_total}")

When you run your program, you should see output similar to the following:

The total price of the shopping list is $9.0

Feel free to modify the item prices to test your program with different shopping list items. This exercise helps you become familiar with type conversion, arithmetic operations, and the print() function in Python.

Exercise 2.4.2: Calculate the Average of Three Numbers

In this exercise, you will write a Python program that calculates the average of three numbers entered by the user. You will practice using input, output, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter three numbers, and assign the results to variables num1num2, and num3. Remember to convert the input to the appropriate data type (e.g., float or int).
  3. Calculate the average of the three numbers using the formula average = (num1 + num2 + num3) / 3, and assign the result to a variable named average.
  4. Use the print() function to display the calculated average.

Your final code should look something like this:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

average = (num1 + num2 + num3) / 3

print(f"The average of {num1}, {num2}, and {num3} is {average:.2f}")

When you run your program, you should see output similar to the following (depending on user input):

Enter the first number: 4
Enter the second number: 6
Enter the third number: 8
The average of 4.0, 6.0, and 8.0 is 6.00

Exercise 2.4.3: Convert Seconds to Hours, Minutes, and Seconds

In this exercise, you will write a Python program that converts a given number of seconds into hours, minutes, and seconds. You will practice using variables, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter a number of seconds, and assign the result to a variable named total_seconds. Remember to convert the input to the appropriate data type (e.g., int).
  3. Calculate the number of hours, minutes, and remaining seconds using the following formulas:
    • hours = total_seconds // 3600
    • minutes = (total_seconds % 3600) // 60
    • seconds = total_seconds % 60
  4. Use the print() function to display the result in hours, minutes, and seconds.

Your final code should look something like this:

total_seconds = int(input("Enter the number of seconds: "))

hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60

print(f"{total_seconds} seconds is equal to {hours} hours, {minutes} minutes, and {seconds} seconds.")

When you run your program, you should see output similar to the following (depending on user input):

Enter the number of seconds: 3666
3666 seconds is equal to 1 hours, 1 minutes, and 6 seconds.

These exercises help you become familiar with type conversion in Python.

2.4 Type Conversion

In this section, we will discuss type conversion in Python. Type conversion, also known as type casting, is the process of converting a value from one data type to another. In Python, you can use built-in functions to perform explicit type conversions. It is important to understand how to convert between different data types because certain operations may only work with specific types, or you may need to ensure that your data is in a suitable format for a particular function. 

2.4.1 Basic Type Conversion Functions

Here are some of the most commonly used type conversion functions in Python:

  • int(): Converts a value to an integer. This function can be used to convert floats to integers or numeric strings to integers.
  • float(): Converts a value to a floating-point number. This function can be used to convert integers to floats or numeric strings to floats.
  • str(): Converts a value to a string. This function can be used to convert integers, floats, or other types to strings.
  • bool(): Converts a value to a boolean. This function can be used to convert integers, floats, strings, or other types to boolean values.

Examples of type conversion: 

x = 5.5
y = int(x)  # Convert float to int, y becomes 5

a = 3
b = float(a)  # Convert int to float, b becomes 3.0

c = 42
d = str(c)  # Convert int to str, d becomes "42"

e = "123"
f = int(e)  # Convert str to int, f becomes 123

g = "True"
h = bool(g)  # Convert str to bool, h becomes True

2.4.2 Type Conversion Limitations

Not all type conversions are valid or possible. For example, if you try to convert a non-numeric string to an integer or a float, a ValueError will be raised: 

s = "hello"
i = int(s)  # Raises a ValueError: invalid literal for int() with base 10: 'hello'

It's important to be aware of the limitations and constraints of type conversions to prevent errors in your code. Always ensure that the value you're trying to convert is compatible with the target data type.

2.4.3 Implicit Type Conversion

Python also performs implicit type conversions, also known as "type coercion," in certain situations. Implicit type conversion occurs when the interpreter automatically converts one data type to another without the programmer explicitly requesting the conversion.

For example, when you perform arithmetic operations between integers and floats, Python automatically converts the integer to a float before performing the operation:

x = 5    # int
y = 2.0  # float

result = x + y  # Python implicitly converts x to a float: 5.0 + 2.0
print(result)  # Output: 7.0

In some cases, implicit type conversion can lead to unexpected results or loss of precision, so it's essential to understand how Python handles different data types in various contexts.

Understanding type conversion in Python is crucial for working with different data types and ensuring your data is in the appropriate format. As you progress through this book, you will encounter various situations where type conversion is necessary or useful for solving programming challenges and working with complex data structures.

Exercise 2.4.1: Shopping List Price Calculator

In this exercise, you will write a Python program that calculates the total price of items on a shopping list. You will practice using type conversion, arithmetic operations, and the print() function.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Declare three variables, item1item2, and item3, representing the prices of three items on the shopping list (e.g., 4.99, 2.75, and 1.25). Use float values for the prices.
  3. Calculate the total price by adding the prices of the three items, and assign the result to a variable named total_price.
  4. Convert the total_price to a string, and round the result to two decimal places using the round() function. Assign the result to a variable named formatted_total.
  5. Use the print() function to display the total price of the shopping list.

Your final code should look something like this:

item1 = 4.99
item2 = 2.75
item3 = 1.25

total_price = item1 + item2 + item3
formatted_total = round(total_price, 2)

print(f"The total price of the shopping list is ${formatted_total}")

When you run your program, you should see output similar to the following:

The total price of the shopping list is $9.0

Feel free to modify the item prices to test your program with different shopping list items. This exercise helps you become familiar with type conversion, arithmetic operations, and the print() function in Python.

Exercise 2.4.2: Calculate the Average of Three Numbers

In this exercise, you will write a Python program that calculates the average of three numbers entered by the user. You will practice using input, output, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter three numbers, and assign the results to variables num1num2, and num3. Remember to convert the input to the appropriate data type (e.g., float or int).
  3. Calculate the average of the three numbers using the formula average = (num1 + num2 + num3) / 3, and assign the result to a variable named average.
  4. Use the print() function to display the calculated average.

Your final code should look something like this:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

average = (num1 + num2 + num3) / 3

print(f"The average of {num1}, {num2}, and {num3} is {average:.2f}")

When you run your program, you should see output similar to the following (depending on user input):

Enter the first number: 4
Enter the second number: 6
Enter the third number: 8
The average of 4.0, 6.0, and 8.0 is 6.00

Exercise 2.4.3: Convert Seconds to Hours, Minutes, and Seconds

In this exercise, you will write a Python program that converts a given number of seconds into hours, minutes, and seconds. You will practice using variables, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter a number of seconds, and assign the result to a variable named total_seconds. Remember to convert the input to the appropriate data type (e.g., int).
  3. Calculate the number of hours, minutes, and remaining seconds using the following formulas:
    • hours = total_seconds // 3600
    • minutes = (total_seconds % 3600) // 60
    • seconds = total_seconds % 60
  4. Use the print() function to display the result in hours, minutes, and seconds.

Your final code should look something like this:

total_seconds = int(input("Enter the number of seconds: "))

hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60

print(f"{total_seconds} seconds is equal to {hours} hours, {minutes} minutes, and {seconds} seconds.")

When you run your program, you should see output similar to the following (depending on user input):

Enter the number of seconds: 3666
3666 seconds is equal to 1 hours, 1 minutes, and 6 seconds.

These exercises help you become familiar with type conversion in Python.

2.4 Type Conversion

In this section, we will discuss type conversion in Python. Type conversion, also known as type casting, is the process of converting a value from one data type to another. In Python, you can use built-in functions to perform explicit type conversions. It is important to understand how to convert between different data types because certain operations may only work with specific types, or you may need to ensure that your data is in a suitable format for a particular function. 

2.4.1 Basic Type Conversion Functions

Here are some of the most commonly used type conversion functions in Python:

  • int(): Converts a value to an integer. This function can be used to convert floats to integers or numeric strings to integers.
  • float(): Converts a value to a floating-point number. This function can be used to convert integers to floats or numeric strings to floats.
  • str(): Converts a value to a string. This function can be used to convert integers, floats, or other types to strings.
  • bool(): Converts a value to a boolean. This function can be used to convert integers, floats, strings, or other types to boolean values.

Examples of type conversion: 

x = 5.5
y = int(x)  # Convert float to int, y becomes 5

a = 3
b = float(a)  # Convert int to float, b becomes 3.0

c = 42
d = str(c)  # Convert int to str, d becomes "42"

e = "123"
f = int(e)  # Convert str to int, f becomes 123

g = "True"
h = bool(g)  # Convert str to bool, h becomes True

2.4.2 Type Conversion Limitations

Not all type conversions are valid or possible. For example, if you try to convert a non-numeric string to an integer or a float, a ValueError will be raised: 

s = "hello"
i = int(s)  # Raises a ValueError: invalid literal for int() with base 10: 'hello'

It's important to be aware of the limitations and constraints of type conversions to prevent errors in your code. Always ensure that the value you're trying to convert is compatible with the target data type.

2.4.3 Implicit Type Conversion

Python also performs implicit type conversions, also known as "type coercion," in certain situations. Implicit type conversion occurs when the interpreter automatically converts one data type to another without the programmer explicitly requesting the conversion.

For example, when you perform arithmetic operations between integers and floats, Python automatically converts the integer to a float before performing the operation:

x = 5    # int
y = 2.0  # float

result = x + y  # Python implicitly converts x to a float: 5.0 + 2.0
print(result)  # Output: 7.0

In some cases, implicit type conversion can lead to unexpected results or loss of precision, so it's essential to understand how Python handles different data types in various contexts.

Understanding type conversion in Python is crucial for working with different data types and ensuring your data is in the appropriate format. As you progress through this book, you will encounter various situations where type conversion is necessary or useful for solving programming challenges and working with complex data structures.

Exercise 2.4.1: Shopping List Price Calculator

In this exercise, you will write a Python program that calculates the total price of items on a shopping list. You will practice using type conversion, arithmetic operations, and the print() function.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Declare three variables, item1item2, and item3, representing the prices of three items on the shopping list (e.g., 4.99, 2.75, and 1.25). Use float values for the prices.
  3. Calculate the total price by adding the prices of the three items, and assign the result to a variable named total_price.
  4. Convert the total_price to a string, and round the result to two decimal places using the round() function. Assign the result to a variable named formatted_total.
  5. Use the print() function to display the total price of the shopping list.

Your final code should look something like this:

item1 = 4.99
item2 = 2.75
item3 = 1.25

total_price = item1 + item2 + item3
formatted_total = round(total_price, 2)

print(f"The total price of the shopping list is ${formatted_total}")

When you run your program, you should see output similar to the following:

The total price of the shopping list is $9.0

Feel free to modify the item prices to test your program with different shopping list items. This exercise helps you become familiar with type conversion, arithmetic operations, and the print() function in Python.

Exercise 2.4.2: Calculate the Average of Three Numbers

In this exercise, you will write a Python program that calculates the average of three numbers entered by the user. You will practice using input, output, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter three numbers, and assign the results to variables num1num2, and num3. Remember to convert the input to the appropriate data type (e.g., float or int).
  3. Calculate the average of the three numbers using the formula average = (num1 + num2 + num3) / 3, and assign the result to a variable named average.
  4. Use the print() function to display the calculated average.

Your final code should look something like this:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

average = (num1 + num2 + num3) / 3

print(f"The average of {num1}, {num2}, and {num3} is {average:.2f}")

When you run your program, you should see output similar to the following (depending on user input):

Enter the first number: 4
Enter the second number: 6
Enter the third number: 8
The average of 4.0, 6.0, and 8.0 is 6.00

Exercise 2.4.3: Convert Seconds to Hours, Minutes, and Seconds

In this exercise, you will write a Python program that converts a given number of seconds into hours, minutes, and seconds. You will practice using variables, type conversion, and arithmetic operators.

Instructions:

  1. Create a new Python file or open a Python interpreter.
  2. Use the input() function to prompt the user to enter a number of seconds, and assign the result to a variable named total_seconds. Remember to convert the input to the appropriate data type (e.g., int).
  3. Calculate the number of hours, minutes, and remaining seconds using the following formulas:
    • hours = total_seconds // 3600
    • minutes = (total_seconds % 3600) // 60
    • seconds = total_seconds % 60
  4. Use the print() function to display the result in hours, minutes, and seconds.

Your final code should look something like this:

total_seconds = int(input("Enter the number of seconds: "))

hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60

print(f"{total_seconds} seconds is equal to {hours} hours, {minutes} minutes, and {seconds} seconds.")

When you run your program, you should see output similar to the following (depending on user input):

Enter the number of seconds: 3666
3666 seconds is equal to 1 hours, 1 minutes, and 6 seconds.

These exercises help you become familiar with type conversion in Python.