Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Python Variables and Data Types
Python is one of the most popular programming languages, known for its simplicity and readability. If you’re new to Python, understanding variables and data types is essential. This guide will explain what variables and data types are, how to use them, and why they are important in Python programming.
What Are Variables?
In Python, a variable is like a container that stores data. Think of it as a labeled box where you can put something inside and retrieve it later. Variables allow you to store and manipulate data in your programs.
How to Declare a Variable
Declaring a variable in Python is straightforward. You simply assign a value to a name using the =
operator. For example:
name = "Alice"age = 25
Here, name
is a variable that stores the value "Alice"
, and age
is a variable that stores the value 25
.
Rules for Naming Variables
- Variable names can contain letters, numbers, and underscores (
_
). - They cannot start with a number.
- Variable names are case-sensitive (e.g.,
name
andName
are different). - Avoid using Python keywords (e.g.,
if
,else
,for
) as variable names.
What Are Data Types?
Data types define the kind of data a variable can hold. Python supports several built-in data types, which can be grouped into the following categories:
- Numeric Types: For numbers.
- Text Type: For strings (text).
- Sequence Types: For ordered collections of items.
- Mapping Type: For key-value pairs.
- Set Types: For unordered collections of unique items.
- Boolean Type: For true/false values.
Let’s explore each of these in detail.
1. Numeric Types
Python supports three numeric types:
a. Integers (int
)
Integers are whole numbers, positive or negative, without decimals. For example:
x = 10y = -5
b. Floating-Point Numbers (float
)
Floats are numbers with decimal points. For example:
pi = 3.14temperature = -10.5
c. Complex Numbers (complex
)
Complex numbers have a real and an imaginary part. For example:
z = 2 + 3j
2. Text Type
Strings (str
)
Strings are sequences of characters enclosed in single ('
) or double ("
) quotes. For example:
greeting = "Hello, World!"name = 'Alice'
You can also use triple quotes ('''
or """
) for multi-line strings:
message = """This is amulti-line string."""
3. Sequence Types
Sequence types are used to store collections of items. Python supports three sequence types:
a. Lists (list
)
Lists are ordered collections of items that can be changed (mutable). Items are enclosed in square brackets []
. For example:
fruits = ["apple", "banana", "cherry"]numbers = [1, 2, 3, 4, 5]
b. Tuples (tuple
)
Tuples are similar to lists but cannot be changed (immutable). Items are enclosed in parentheses ()
. For example:
coordinates = (10, 20)colors = ("red", "green", "blue")
c. Range (range
)
The range
type represents a sequence of numbers. It is commonly used in loops. For example:
numbers = range(1, 6) # Represents numbers from 1 to 5
4. Mapping Type
Dictionaries (dict
)
Dictionaries store data as key-value pairs. Keys must be unique and immutable (e.g., strings or numbers). Items are enclosed in curly braces {}
. For example:
person = { "name": "Alice", "age": 25, "city": "New York"}
5. Set Types
Sets are unordered collections of unique items. They are enclosed in curly braces {}
. For example:
unique_numbers = {1, 2, 3, 4, 5}
6. Boolean Type
Booleans (bool
)
Booleans represent true or false values. They are often used in conditional statements. For example:
is_raining = Trueis_sunny = False
Why Are Variables and Data Types Important?
- Data Storage: Variables allow you to store and reuse data in your programs.
- Data Manipulation: Different data types enable you to perform specific operations (e.g., adding numbers, concatenating strings).
- Code Readability: Using meaningful variable names and appropriate data types makes your code easier to understand.
- Error Prevention: Understanding data types helps you avoid errors (e.g., adding a string to a number).
Examples of Using Variables and Data Types
Example 1: Working with Numbers
# Declare variablesx = 10y = 3.14
# Perform arithmetic operationssum = x + yprint("Sum:", sum) # Output: Sum: 13.14
Example 2: Working with Strings
# Declare variablesfirst_name = "Alice"last_name = "Smith"
# Concatenate stringsfull_name = first_name + " " + last_nameprint("Full Name:", full_name) # Output: Full Name: Alice Smith
Example 3: Working with Lists
# Declare a listfruits = ["apple", "banana", "cherry"]
# Access list itemsprint("First Fruit:", fruits[0]) # Output: First Fruit: apple
# Add an item to the listfruits.append("orange")print("Updated List:", fruits) # Output: Updated List: ['apple', 'banana', 'cherry', 'orange']
Example 4: Working with Dictionaries
# Declare a dictionaryperson = { "name": "Alice", "age": 25, "city": "New York"}
# Access dictionary valuesprint("Name:", person["name"]) # Output: Name: Alice
# Update a valueperson["age"] = 26print("Updated Age:", person["age"]) # Output: Updated Age: 26
Tips for Beginners
- Use Descriptive Variable Names: Choose names that describe the data (e.g.,
user_age
instead ofx
). - Understand Data Types: Know which data type to use for different kinds of data.
- Practice: Write small programs to experiment with variables and data types.
- Debugging: If you encounter errors, check if you’re using the correct data type.