Variables and Data Types in Python

Introduction to Variables and Data Types

What are Variables?

  • Variables are containers for storing data values.
  • In Python, variables are created when you assign a value to them:
x = 10
name = "Alice"
  • Variables do not need explicit declaration and can change type.

Data Types in Python

  • Data types classify data. In Python, everything is an object, and every object has a type.
  • Common data types include:
    • Integers: int
    • Floating-point numbers: float
    • Strings: str
    • Booleans: bool

Variable Declaration and Assignment

Declaration and Assignment

  • Variables are assigned using the = operator.
  • Python infers the data type based on the value assigned.
age = 25  # Integer
pi = 3.14  # Float
name = "John"  # String
is_student = True  # Boolean

Checking Variable Types

  • You can check the type of a variable using the type() function.
print(type(age))  # Output: <class 'int'>
print(type(name))  # Output: <class 'str'>
<class 'int'>
<class 'str'>
  • Python is dynamically typed, meaning you don’t have to declare the type.

Working with Numbers

Integer Operations

  • Integers (int) are whole numbers. You can perform arithmetic operations on them.
x = 10
y = 5
sum = x + y  # Addition
product = x * y  # Multiplication
  • Common operators: +, -, *, /, % (modulo)

Float (Decimal Numbers)

  • Floats represent numbers with decimal points.
price = 19.99
discount = 0.10
total = price * (1 - discount)
  • Operations on floats behave similarly to integers.

Strings in Python

String Basics

  • A string is a sequence of characters enclosed in quotes.
message = "Hello, world!"
name = 'Alice'
  • Strings can be single or double-quoted.

String Operations

  • Concatenation (+):
greeting = "Hello, " + name
  • Repetition (*):
laugh = "ha" * 3  # Output: "hahaha"
  • Accessing characters by index:
first_letter = name[0]  # Output: 'A'

Boolean and None Types

Boolean Type

  • Booleans represent True or False.
is_adult = True
has_permission = False
  • Boolean values are often used in conditional statements.

The None Type

  • None represents the absence of a value.
result = None
  • Often used to indicate that a variable holds no value or is a placeholder for future data.

Type Conversion

Converting Between Types

  • You can convert between different types using built-in functions.
x = 10  # int
y = float(x)  # Converts to float: 10.0
z = str(x)  # Converts to string: '10'

Why Type Conversion Matters

  • Type conversion is important when combining different types in operations.
age = 30
message = "I am " + str(age) + " years old."
print(message)  # Output: I am 30 years old.
I am 30 years old.