+91 81900 98289

Python Casting

This Python Casting lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

Casting converts a value from one type to another. int() cuts a float toward zero and also reads a whole number from text.

str() turns a number into text so you can join it to a sentence. float() reads a decimal from text.

Example 1: Start here

int(\"3.5\") fails. Convert to float first, or store the text as a float.

print(int("42")) # int() reads a whole number from the text print(float("3.5")) # float() keeps a decimal print(str(2026)) # str() turns the value into text

Example 2: Text to a number

int and float read a number that was stored as text.

print(int("24")) # int() reads a whole number from the text print(float("3.5")) # float() keeps a decimal

Example 3: Number to text

A plus sign joins text only. str turns the number into text first.

score = 82 # a whole number print("Score: " + str(score)) # plus joins text; use str() for a number

Example 4: Truth from a number

Zero is False. Any other number is True.

print(bool(0)) # 0 is False; any other number is True print(bool(5)) # 0 is False; any other number is True
int(\"3.5\") fails. Convert to float first, or store the text as a float.
Call Now 81900 98289