Basics of Python
Basics of Python
1. Variable
A variable is a name given to a piece of data. It can store values like numbers, text, or more
complex data. For example, `x = 10` stores the number 10 in the variable `x`.
2. Data Type
Data types specify the kind of value a variable holds. Common data types in Python include
integers (e.g., 5), floats (e.g., 3.14), strings (e.g., "hello"), and booleans (e.g., True or False).
3. String
A string is a sequence of characters enclosed in quotes. For example, `"Hello, world!"` is a
string.
4. Integer
An integer is a whole number, positive or negative, without any decimal point. For example,
`7` and `-3` are integers.
5. Float
A float is a number with a decimal point. For example, `3.14` and `-0.5` are floats.
6. List
A list is a collection of items enclosed in square brackets and separated by commas. For
example, `[1, 2, 3]` is a list of integers.
7. Tuple
A tuple is similar to a list but is immutable, meaning its contents cannot be changed after
creation. It is enclosed in parentheses. For example, `(1, 2, 3)` is a tuple.
8. Dictionary
A dictionary is a collection of key-value pairs enclosed in curly braces. Each key is unique,
and it maps to a value. For example, `{'name': 'Alice', 'age': 25}` is a dictionary.
9. Function
A function is a block of reusable code that performs a specific task. It is defined using the
`def` keyword. For example, `def greet():` defines a function named `greet`.
10. Loop
A loop allows you to execute a block of code repeatedly. The two main types of loops in
Python are `for` loops and `while` loops.
11. If Statement
An `if` statement lets you execute code only if a certain condition is true. For example, `if x >
10:` checks if `x` is greater than 10.
14. Class
A class is a blueprint for creating objects with specific attributes and methods. It is defined
using the `class` keyword. For example, `class Dog:` defines a class named `Dog`.
15. Object
An object is an instance of a class. It contains attributes and methods defined in the class.
For example, `my_dog = Dog()` creates an object of the `Dog` class.
16. Method
A method is a function defined within a class that operates on objects of that class. For
example, `def bark(self):` is a method that could be defined in a `Dog` class.
17. Import
The `import` keyword is used to include external code modules into your script. For example,
`import math` allows you to use functions from the `math` module.
18. Exception
An exception is an error that occurs during program execution. You handle exceptions using
`try` and `except` blocks. For example, `try:` followed by `except:` lets you manage errors.
19. File
A file is a document used to store data. In Python, you can open, read, write, and close files
using functions like `open()`, `read()`, and `write()`.
20. Module
A module is a file containing Python code that can be imported and used in other scripts. For
example, `math` is a module that provides mathematical functions.