DEV Community

Cover image for Python Day Six : Python Lesson
Amina
Amina

Posted on

Python Day Six : Python Lesson

Day Day Six Lesson : Python Casting

Casting is the process of converting a value from one data type to another.
Python provides built-in functions for casting:

int() → Converts a value to an integer (whole number)
float() → Converts a value to a float (decimal number)
str() → Converts a value to a string (text)

Integers,

Example:


x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • int(1) → The number 1 is already an integer, so it remains 1.
  • int(2.8) → Converts 2.8 to the integer 2 by removing the decimal part.
  • int("3") → Converts the text "3" into the integer 3.

Output:

1
2
3
Enter fullscreen mode Exit fullscreen mode

Float Casting

example:

x = float(1)      # x will be 1.0
y = float(2.8)    # y will be 2.8
z = float("3")    # z will be 3.0
w = float("4.2")  # w will be 4.2
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • float(1) → Converts 1 to 1.0
  • float(2.8) → Remains 2.8
  • float("3") → Converts the string "3" to 3.0
  • float("4.2") → Converts the string "4.2" to 4.2

Output:

1.0
2.8
3.0
4.2
Enter fullscreen mode Exit fullscreen mode

String Casting

x = str("s1")   # x will be 's1'
y = str(2)      # y will be '2'
z = str(3.0)    # z will be '3.0'
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • str("s1") → Remains "s1" because it is already a string.
  • str(2) → Converts the number 2 into the text "2".
  • str(3.0) → Converts the decimal number 3.0 into the text "3.0".

Output:

s1
2
3.0
Enter fullscreen mode Exit fullscreen mode

Casting is a basic but powerful Python skill. By learning how to convert data types, you can handle user input, perform calculations, and build better programs. Keep practicing—every lesson brings you closer to becoming a confident programmer! 💻🐍

Top comments (0)