Welcome to the world of Python Casting! In this lesson, we'll explore how to convert data between different types in Python. This skill is essential for building robust and flexible programs. Let's dive in! 🐠
In Python, variables have specific types, such as int, float, str, and bool. However, sometimes we need to work with different types of data in the same program. That's where casting comes in handy.
Before we dive into casting, let's understand the basic data types in Python:
int (integer) - whole numbers, e.g., 3, 10, -5float (floating-point) - decimal numbers, e.g., 3.14, 0.001str (string) - text, e.g., "Hello, World!"bool (boolean) - True or FalsePython provides built-in functions to convert data between types:
int() - converts a number or a string to an integerfloat() - converts a number or a string to a floating-point numberstr() - converts any data type to a stringbool() - converts a number or a string to a booleanLet's see these functions in action with some examples!
number_string = "5"
number_int = int(number_string)
print(number_int) # Output: 5number_string = "3.14"
number_float = float(number_string)
print(number_float) # Output: 3.14number_int = 10
number_string = str(number_int)
print(number_string) # Output: 10number_int = 0
boolean = bool(number_int)
print(boolean) # Output: False
number_int = 1
boolean = bool(number_int)
print(boolean) # Output: Trueboolean_string = "True"
boolean = bool(boolean_string)
print(boolean) # Output: True
boolean_string = "False"
boolean = bool(boolean_string)
print(boolean) # Output: FalseWhat will be the output of the following code?
That's all for now! Keep practicing and exploring casting in Python. Happy coding! 🎉
Remember to always use casting when needed to ensure your code works smoothly. If you have any questions, feel free to ask! 💬
Stay tuned for more lessons on CodeYourCraft! 🎓