Wednesday, August 21, 2024

Python basics

Python is a high-level, interpreted programming language known for its readability and simplicity. It was created by Guido van Rossum and first released in 1991.

Python is widely used in various fields, including web development, data science, automation, artificial intelligence, and scientific computing.

Here are some key features that make Python popular:

1.     Readability: Python's syntax is designed to be easy to read and write, which helps developers understand and maintain code more effectively.

2.     Extensive Libraries: Python has a rich set of libraries and frameworks, such as NumPy and Pandas for data analysis, Django and Flask for web development, and TensorFlow and PyTorch for machine learning.

3.     Interpreted: Python code is executed line by line, which can make debugging easier and allows for rapid development.

4.     Cross-Platform: Python is available on many operating systems, including Windows, macOS, and Linux, making it a cross-platform language.

5.     Community Support: Python has a large and active community, which means plenty of resources, tutorials, and third-party tools are available.

Setting Up Your Environment

Before you start coding, you need to set up Python on your computer.

  1. Install Python:
    • Download Python from the official website and follow the installation instructions.
    • Make sure to check the option to add Python to your PATH during installation.
  2. Install an IDE or Text Editor:

Your First Python Program

Open a text editor or IDE and create a new file named hello.py. Enter the following code:

print("Hello, World!")

Save the file and run it from your command line:

python hello.py

You should see the output:

 

Basic Syntax and Data Types

Variables and Data Types

# Variables
name = "Alice"  # String
age = 30        # Integer
height = 5.5    # Float
is_student = True  # Boolean
 print(name)
print(age)
print(height)
print(is_student)

Basic Data Types

  • String: Text data, enclosed in quotes ("Hello" or 'Hello').
  • Integer: Whole numbers (10, -5).
  • Float: Decimal numbers (3.14, -0.001).
  • Boolean: True or False.
Basic Operators
  • Arithmetic Operators: +, -, *, /, %, // (integer division), ** (exponentiation).
                sum = 5 + 3
                difference = 10 - 2
                product = 4 * 7
                quotient = 20 / 4
  • Comparison Operators: ==, !=, >, <, >=, <=.
                is_equal = (5 == 5# True
                is_greater = (10 > 5# True
  • Logical Operators: and, or, not.
            x = True
            y = False
            result = x and# False

Data Structures

  • Lists: Ordered, mutable collections of items. Defined with square brackets [].
            fruits = ["apple", "banana", "cherry"]
            print(fruits[0])  # Access first element
  • Tuples: Ordered, immutable collections of items. Defined with parentheses ().
            coordinates = (10.0, 20.0)
  • Dictionaries: Collections of key-value pairs. Defined with curly braces {}.
            person = {"name": "Alice", "age": 30}
            print(person["name"])  # Access value by key
  • Sets: Unordered collections of unique items. Defined with curly braces {}.
            numbers = {1, 2, 3}

Control Flow

Conditional Statements

# If statement
age = 18
 
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Loops

  • For Loop
# Iterate through a list
for name in names:
    print(name)
  • While Loop
# Print numbers 0 to 4
i = 0
while i < 5:
    print(i)
    i += 1

Functions - Functions help you organize and reuse code. Defined using the def keyword.

def greet(name):
    return f"Hello, {name}!"
 
print(greet("Alice"))
print(greet("Bob"))

Working with Files

Reading from a File

# Open and read a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

Writing to a File

# Write to a file
with open('example.txt', 'w') as file:
    file.write("Hello, file!")

Libraries and Modules

Python has a rich ecosystem of libraries. To use them, you first need to install them, often via pip, Python's package manager.

pip install requests

Then, you can use the library in your code:

import requests
 response = requests.get('https://api.github.com')
print(response.status_code)

Error Handling - Handle exceptions to prevent your program from crashing due to unexpected errors.

Use try and except blocks to handle exceptions.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
finally:
    print("Execution completed.")

Object-Oriented Programming

Python supports object-oriented programming (OOP).

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
     def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."
 p1 = Person("Alice", 30)
print(p1.greet())

Additional Concepts

List Comprehensions - A concise way to create lists.

squares = [x**2 for x in range(10)]
Lambda Functions - Anonymous functions defined with the lambda keyword.
add = lambda a, b: a + b
print(add(5, 3))  # Output: 8

 

 

 

No comments:

Post a Comment