Python: Typecasting

Post Reply
User avatar
Jason
Site Admin
Posts: 767
Joined: Sun Dec 21, 2025 8:56 pm

Stuff put into an input function is always considered a string datatype, so typecasting is sometimes needed.

Code: Select all

age = int(input("What is your age?"))

# The author wants the age as an integer value 'int'.

# For some reason, the code author changes his mind and wants the variable in decimal form, so a typecasting to float is needed.

age = float(age)

print(f"Your age is {age}")

# Displays the sentence: "Your age is (whatever you typed)."

# Let's say he/she wanted the code done correctly from the start.

age = float(input("What is your age?"))

print(f"Your age is {age}")

# Does the same thing.

 

POSTREACT(ions) SUMMARY

Post Reply