Python Casting 🎯

beginner
10 min

Python Casting 🎯

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! 🐠

Why Python Casting Matters 💡

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.

Understanding Data Types in Python 📝

Before we dive into casting, let's understand the basic data types in Python:

  1. int (integer) - whole numbers, e.g., 3, 10, -5
  2. float (floating-point) - decimal numbers, e.g., 3.14, 0.001
  3. str (string) - text, e.g., "Hello, World!"
  4. bool (boolean) - True or False

Python Casting Functions ✅

Python provides built-in functions to convert data between types:

  1. int() - converts a number or a string to an integer
  2. float() - converts a number or a string to a floating-point number
  3. str() - converts any data type to a string
  4. bool() - converts a number or a string to a boolean

Practical Examples 🐘

Let's see these functions in action with some examples!

Example 1: Converting a String to an Integer

python
number_string = "5" number_int = int(number_string) print(number_int) # Output: 5

Example 2: Converting a String to a Float

python
number_string = "3.14" number_float = float(number_string) print(number_float) # Output: 3.14

Example 3: Converting an Integer to a String

python
number_int = 10 number_string = str(number_int) print(number_string) # Output: 10

Example 4: Converting a Boolean from a Number

python
number_int = 0 boolean = bool(number_int) print(boolean) # Output: False number_int = 1 boolean = bool(number_int) print(boolean) # Output: True

Example 5: Converting a Boolean from a String

python
boolean_string = "True" boolean = bool(boolean_string) print(boolean) # Output: True boolean_string = "False" boolean = bool(boolean_string) print(boolean) # Output: False

Quiz Time 🧮

Quick Quiz
Question 1 of 1

What 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! 🎓