DEV Community

SAINAPEI LENAPUNYA
SAINAPEI LENAPUNYA

Posted on

Day 4:Type Casting in Python

On Day 4 of my Python challenge,I learned about type casting.

Type casting means converting one data type into another for example, changing a number into text, or text into a number (if possible).This is super useful when working with user input or combining different kinds of values.

Here’s the code I wrote today:

# Integer to float num_int = 10 num_float = float(num_int) # Float to integer decimal_num = 5.9 whole_num = int(decimal_num) # Number to string age = 22 age_str = str(age) # String to integer num_str = "100" num_from_str = int(num_str) print("Integer to float:", num_float) print("Float to integer:", whole_num) print("Number to string:", age_str) print("String to integer:", num_from_str) 
Enter fullscreen mode Exit fullscreen mode

What happened when I ran it?

Notice how the data type changes when we cast it:

int → float adds a decimal (10 → 10.0)

float → int drops the decimal part (5.9 → 5)

int → str turns numbers into text (22 → "22")

str → int only works if the string is a number ("100" → 100)

GitHub update:
I saved my file as day4(type_casting).py, then pushed it with:

git add 'day4(type_casting).py' git commit -m "type casting..." git push 
Enter fullscreen mode Exit fullscreen mode

Challenge for you:

Try converting "3.14" into a float.

Then convert it into an integer.What result do you get?

Your turn:
Have you ever had a situation where you needed to convert data types (maybe while coding, or even thinking about real life like changing “22” to 22 😉)?Share your examples in the comments!

Top comments (0)