-
Hajipur, Bihar, 844101
Casting in Python refers to converting one data type to another manually using built-in functions.
Although Python is dynamically typed (automatically detects data types), sometimes you need to explicitly convert values from one type to another.
Python provides the following built-in functions for casting:
Function | Purpose |
---|---|
int() |
Converts to integer |
float() |
Converts to float |
str() |
Converts to string |
bool() |
Converts to boolean |
int()
Used to convert a number or a numeric string to an integer.
x = int(5.6) # Result: 5
y = int("10") # Result: 10
❗ Cannot convert non-numeric strings:
int("abc") # Error
float()
Converts integer or numeric string to float.
a = float(7) # Result: 7.0
b = float("3.14") # Result: 3.14
str()
Converts numbers or other data types to string.
x = str(100) # Result: "100"
y = str(3.14) # Result: "3.14"
bool()
bool(0)
, bool("")
, bool(None)
return False
All other values return True
bool(1) # True
bool(0) # False
bool("Hi") # True
To perform operations between different types
To store data in a specific format
To avoid type errors in calculations or concatenation
From | To | Method | Example Result |
---|---|---|---|
float |
int |
int(5.6) |
5 |
int |
float |
float(2) |
2.0 |
number |
string |
str(100) |
"100" |
string |
int |
int("25") |
25 |
any |
boolean |
bool(value) |
True / False |
Q1. Write a Python program to convert the float 3.7
to an integer using int()
.
Q2. Write a Python program to convert the string "25"
to an integer using int()
.
Q3. Write a Python program to convert the number 100
to a string and print its type.
Q4. Write a Python program to convert the integer 50
to a float using float()
.
Q5. Write a Python program to try converting the string "abc"
to an integer and observe the error.
Q6. Write a Python program to convert an empty string ""
to boolean and display the result.
Q7. Write a Python program to use str()
to convert a boolean value to a string and print it.
Q8. Write a Python program to convert the string "7.5"
to a float using float()
.
Q9. Write a Python program to convert a non-zero number like 10
to boolean and print the result.
Q10. Write a Python program to convert a float value 5.99
to a string using str()
and check its type.
Q1: What is type casting in Python?
Q2: Which function converts a float to an integer?
Q3: What does str() do in Python?
Q4: What is the output of bool(0)?
Q5: What will happen if you use int("abc")?
Q6: Which of the following will return True?
Q7: How do you convert 100 into a string?
Q8: Which data type conversion is invalid?
Q9: What function should be used to convert a number to float?
Q10: Which of the following returns False?