Python Data Types and Operators Examples

Learn how to use data types and apply operators in Python. This page provides beginner-friendly examples with code you can try.


1. Declare a variable and print it.
python
# Example 1: Declare a variable
name = "Alice"
print(name)

2. Change the value of a variable.
python
# Example 2: Reassign a variable
age = 20
age = 21
print("Updated age:", age)

3. Assign multiple variables in one line.
python
# Example 3: Multiple assignment
x, y, z = 1, 2, 3
print(x, y, z)

4. Swap values of two variables.
python
# Example 4: Swap variables
a = "apple"
b = "banana"
a, b = b, a
print("a:", a)
print("b:", b)

5. Combine variables in a sentence.
python
# Example 5: Combine variables
first_name = "John"
last_name = "Doe"
print("Full name:", first_name + " " + last_name)

6. Create different data types.
python
# Example 6: Data types in Python

# Integer (int)
my_int = 10
print("Integer:", my_int)

# Float (float)
my_float = 3.14
print("Float:", my_float)

# String (str)
my_str = "Hello, Python!"
print("String:", my_str)

# Complex number (complex)
my_complex = 2 + 3j
print("Complex Number:", my_complex)

# Boolean (bool)
my_bool = True
print("Boolean:", my_bool)

# NoneType (None)
my_none = None
print("NoneType:", my_none)

7. Check the type of a variable
python
# Example 7: Check the type of a variable
value = 42
print(type(value))  # <class 'int'>

8. Implicit type casting in Python.
python
# Example 8: Implicit type casting

# Example: Implicit casting during arithmetic (int + float)
my_int = 5          # int
my_float = 4.5      # float
result = my_int + my_float  # int is implicitly cast to float
print("Result (int + float):", result)
print("Type of result:", type(result))

# int to complex
my_int = 10
my_complex = my_int + 3j
print("Implicit casting (int to complex):", my_complex)

# float to complex
my_float = 4.5
my_complex = my_float + 1j
print("Implicit casting (float to complex):", my_complex)

9. Write a program that demonstrates explicit type conversion.
python
# Example 9: Explicit type conversion

# Convert float to int
pi = 3.14159
pi_as_int = int(pi)
print("Float to int:", pi_as_int)  # Output: 3

# Convert int to string
num = 100
num_str = str(num)
print("Int to string:", num_str)

# Convert string to int
str_number = "42"
converted_number = int(str_number)
print("String to int:", converted_number)

# Convert string to float
str_float = "3.14"
converted_float = float(str_float)
print("String to float:", converted_float)

# Convert int to float
num = 7
converted_float = float(num)
print("Int to float:", converted_float)

10. Add two numbers together.
python
# Example 10: Addition of two numbers

num1 = 5
num2 = 7
result = num1 + num2
print("The sum is:", result)

11. Subtract one number from another.
python
# Example 11: Subtraction of two numbers

num1 = 15
num2 = 8
result = num1 - num2
print("The difference is:", result)

12. Multiply two numbers together.
python
# Example 12: Multiplication of two numbers

num1 = 4
num2 = 3
result = num1 * num2
print("The product is:", result)

13. Divide one number by another.
python
# Example 13: Division of two numbers

num1 = 20
num2 = 4
result = num1 / num2
print("The quotient is:", result)

14. Find the remainder when dividing two numbers.
python
# Example 14: Modulus (remainder)

num1 = 17
num2 = 5
result = num1 % num2
print("The remainder is:", result)

15. Raise a number to the power of another number.
python
# Example 15: Exponentiation

base = 3
exponent = 4
result = base ** exponent
print("The result is:", result)

16. Use the AND operator to check if a person is eligible for a discount.
python
# Example 16: AND operator to check discount eligibility

age = 30
is_member = True

# Check if the person is eligible for a discount (must be an adult and a member)
if age >= 18 and is_member:
    print("You are eligible for the discount!")
else:
    print("Sorry, you are not eligible for the discount.")

17. Use the OR operator to check if a student is eligible for a free pass.
python
# Example 17: OR operator to check free pass eligibility

is_student = True
has_coupon = False

# Check if the student is eligible for a free pass (either a student or has a coupon)
if is_student or has_coupon:
    print("You are eligible for the free pass!")
else:
    print("Sorry, you are not eligible for the free pass.")

18. Use the NOT operator to check if a person is not banned.
python
# Example 18: NOT operator to check banned status

is_banned = False

# Check if the person is not banned
if not is_banned:
    print("You can access the service!")
else:
    print("Your account is banned.")

19. Use AND operator to check if a number is both even and divisible by 3.
python
# Example 19: AND operator for number validation

number = 12

# Check if the number is both even and divisible by 3
if number % 2 == 0 and number % 3 == 0:
    print("The number is both even and divisible by 3.")
else:
    print("The number does not meet the criteria.")

20. Use OR operator to check if a person is either a senior or a child for a discounted ticket.
python
# Example 20: OR operator for ticket discount eligibility

age = 65
is_child = False

# Check if the person is eligible for a discount (either a senior or a child)
if age >= 65 or is_child:
    print("You are eligible for a discounted ticket!")
else:
    print("You are not eligible for a discount.")

21. Use NOT operator to ensure the entered password is not the default password.
python
# Example 21: NOT operator to check password security

default_password = "12345"
entered_password = "password123"

# Check if the entered password is NOT the default
if entered_password != default_password:
    print("Password accepted!")
else:
    print("Please change your default password.")

22. Use logical operators to determine if a user can access a premium section of a website.
python
# Example 22: Logical operators for premium access

age = 30
is_premium_member = True

# Check if the user is eligible for premium access.
# The user should be both an adult (18 or older) and a premium member

if age >= 18 and is_premium_member:
    print("You have access to the premium section!")
else:
    print("You do not have access to the premium section.")

23. Assign a value to a variable.
python
# Example 23: Basic assignment

x = 10  # Assign the value 10 to variable x
print("The value of x is:", x)

24. Add a value to an existing variable using the += operator.
python
# Example 24: Add value using +=

x = 5
x += 3  # Adds 3 to x (x = x + 3)
print("The updated value of x is:", x)

25. Subtract a value from an existing variable using the -= operator.
python
# Example 25: Subtract value using -=

x = 10
x -= 4  # Subtracts 4 from x (x = x - 4)
print("The updated value of x is:", x)

26. Multiply a variable by a value using the *= operator.
python
# Example 26: Multiply value using *=

x = 3
x *= 2  # Multiplies x by 2 (x = x * 2)
print("The updated value of x is:", x)

27. Divide a variable by a value using the /= operator.
python
# Example 27: Divide value using /=

x = 10
x /= 2  # Divides x by 2 (x = x / 2)
print("The updated value of x is:", x)

28. Use the %= operator to find the remainder of a division.
python
# Example 28: Modulus assignment using %=

x = 10
x %= 3  # Finds remainder when x is divided by 3 (x = x % 3)
print("The remainder is:", x)

29. Use the **= operator to raise a variable to a power.
python
# Example 29: Exponentiation assignment using **=

x = 2
x **= 3  # Raises x to the power of 3 (x = x ** 3)
print("The updated value of x is:", x)

30. Use the //= operator for integer division.
python
# Example 30: Integer division assignment using //=

x = 10
x //= 3  # Integer division of x by 3 (x = x // 3)
print("The updated value of x is:", x)

31. Use the `is` operator to check if two variables refer to the same object.
python
# Example 31: Check identity using 'is'

x = [1, 2, 3]
y = x  # y refers to the same object as x
z = [1, 2, 3]  # z is a new object with the same values

print(x is y)  # True, since x and y refer to the same object
print(x is z)  # False, since x and z are two different objects even though their contents are the same

32. Use the `is not` operator to check if two variables do not refer to the same object.
python
# Example 32: Check identity using 'is not'

x = [1, 2, 3]
y = x  # y refers to the same object as x
z = [1, 2, 3]  # z is a new object with the same values

print(x is not y)  # False, because x and y refer to the same object
print(x is not z)  # True, because x and z refer to different objects

33. Check if two variables refer to the same object when dealing with immutable data types.
python
# Example 33: Immutable types comparison using 'is'

x = 10
y = 10  # x and y refer to the same object because of Python's optimization for small integers

print(x is y)  # True, because small integers are cached and refer to the same object

34. Compare variables with `is` when using mutable types.
python
# Example 34: Mutable types comparison using 'is'

x = [1, 2, 3]
y = [1, 2, 3]  # x and y are two different lists with the same values

print(x is y)  # False, since they are two different list objects even though they have the same contents

35. Use the `is` operator with None to check if a variable is None.
python
# Example 35: Check for None using 'is'

x = None
y = 10

print(x is None)  # True, x is None
print(y is None)  # False, y is not None

36. Use the `&` (AND) operator to perform bitwise AND operation.
python
# Example 36: Bitwise AND using '&'

x = 5  # In binary: 0101
y = 3  # In binary: 0011

result = x & y  # 0101 & 0011 = 0001 (binary)
print(f"Result of 5 & 3: {result}")  # Output: 1

37. Use the `|` (OR) operator to perform bitwise OR operation.
python
# Example 37: Bitwise OR using '|'

x = 5  # In binary: 0101
y = 3  # In binary: 0011

result = x | y  # 0101 | 0011 = 0111 (binary)
print(f"Result of 5 | 3: {result}")  # Output: 7

38. Use the `^` (XOR) operator to perform bitwise XOR operation.
python
# Example 38: Bitwise XOR using '^'

x = 5  # In binary: 0101
y = 3  # In binary: 0011

result = x ^ y  # 0101 ^ 0011 = 0110 (binary)
print(f"Result of 5 ^ 3: {result}")  # Output: 6

39. Use the `~` (NOT) operator to perform bitwise NOT operation.
python
# Example 39: Bitwise NOT using '~'

x = 5  # In binary: 0101

result = ~x  # ~0101 = -0110 (binary)
print(f"Result of ~5: {result}")  # Output: -6 (Two's complement of 5)

40. Use the `<<` (left shift) operator to shift bits to the left.
python
# Example 40: Left shift using '<<'

x = 5  # In binary: 0101

result = x << 1  # Shift bits left by 1 (multiply by 2)
print(f"Result of 5 << 1: {result}")  # Output: 10 (1010 in binary)

41. Use the `>>` (right shift) operator to shift bits to the right.
python
# Example 41: Right shift using '>>'

x = 5  # In binary: 0101

result = x >> 1  # Shift bits right by 1 (divide by 2)
print(f"Result of 5 >> 1: {result}")  # Output: 2 (0010 in binary)

42. Use the `in` operator to check if a value exists in a list.
python
# Example 42: Membership check using 'in'

fruits = ['apple', 'banana', 'cherry']
result = 'apple' in fruits  # Check if 'apple' is in the fruits list
print(f"Is 'apple' in the list? {result}")  # Output: True

43. Use the `in` operator to check if a value exists in a string.
python
# Example 43: Membership check using 'in' with strings

message = "Hello, World!"
result = 'World' in message  # Check if 'World' is in the message string
print(f"Is 'World' in the message? {result}")  # Output: True

44. Use the `in` operator to check if a key exists in a dictionary.
python
# Example 44: Membership check using 'in' with dictionaries

person = {"name": "Alice", "age": 25}
result = 'name' in person  # Check if the key 'name' exists in the dictionary
print(f"Is 'name' a key in the dictionary? {result}")  # Output: True

45. Use the `not in` operator to check if a value is not in a list.
python
# Example 45: Membership check using 'not in'

fruits = ['apple', 'banana', 'cherry']
result = 'orange' not in fruits  # Check if 'orange' is not in the fruits list
print(f"Is 'orange' not in the list? {result}")  # Output: True

46. Use the `not in` operator to check if a substring is not in a string.
python
# Example 46: Membership check using 'not in' with strings

message = "Hello, World!"
result = 'Python' not in message  # Check if 'Python' is not in the message string
print(f"Is 'Python' not in the message? {result}")  # Output: True

47. Use the `in` operator to check if a value exists in a set.
python
# Example 47: Membership check using 'in' with sets

colors = {"red", "green", "blue"}
result = 'green' in colors  # Check if 'green' is in the set
print(f"Is 'green' in the set? {result}")  # Output: True

48. Use the `not in` operator to check if a value does not exist in a set.
python
# Example 48: Membership check using 'not in' with sets

colors = {"red", "green", "blue"}
result = 'yellow' not in colors  # Check if 'yellow' is not in the set
print(f"Is 'yellow' not in the set? {result}")  # Output: True


What's Next?

Now that you've practiced variables, data types, and operators, you're ready to use them together in more complex programs. Next up: control flow with if, elif, and else statements.