Hi friends, welcome to DailyCodeHub. Today we are going to learn how to declare an integer variable in Python and print its value and type. This is one of the most basic programs every Python beginner should know.
Question : Write a Python program to declare an integer variable and print its value and type.
Method 1: Basic Declaration
code :
# Assign integer value to variable
x = 10
# Print value of x
print("Value:", x)
# Print data type of x
print("Type:", type(x))
Output :
Value: 10
Type: <class 'int'>
Method 2 : Multiple variables
Code :
# Assign values to variables
a = 10
b = 20
c = 30
# Print values
print("a =", a)
print("b =", b)
print("c =", c)
# Print data types
print("Type of a:", type(a))
print("Type of b:", type(b))
print("Type of c:", type(c))
Output:
a = 10
b = 20
c = 30
Type of a: <class 'int'>
Type of b: <class 'int'>
Type of c: <class 'int'>
Method 3: Using id ( ) and bit_length( )
Code :
# Assign integer value to variable
x = 10
# Print value of x
print("Value:", x)
# Print data type of x
print("Type:", type(x))
# Print memory address of x
print("Memory Address:", id(x))
# Print number of bits required to represent x
print("Bits needed:", x.bit_length())
Output:
Value: 10
Type: <class 'int'>
Memory Address: 140234567890
Bits needed: 4
Explanation :
Step 1: We write x = 10, which means we are creating a variable called x and storing the value 10 in it.
Step 2: print("Value:", x) Prints the value stored in the variable x which is 10.
Step 3: type(x) is a built-in function in python . It returns the data type of any variable. Since x is 10 which is a whole number it returns int.
Step 4: id(x) returns the memory address where the variable is stored in your computer memory.
Step 5: bit_length( ) is an int method that returns how many bits are needed to represent the number. 10 in binary is 1010 which needs 4 bits.
Key points :
- Integer is a whole number without any decimal point.
- In Python we use "=" to assign a value to a variable
- type( ) function returns the data type of a variable
- int returns as class int in python
- Python integers have no size limit unlike other languages
- id( ) returns the memory address of a variable.
I hope this program was helpful. If you have any doubts please leave a comment below. Keep practicing and happy coding.
Happy coding ❤️
No comments:
Post a Comment