Introduction to Python Programming

Introduction to Python Programming

Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python is widely used in various fields such as web development, data science, artificial intelligence, automation, and more.

Features of Python

  1. Simple and Easy to Learn: Python's syntax is straightforward, making it an excellent choice for beginners.
  2. Open Source: Python is free to use, distribute, and modify.
  3. Interpreted Language: Python code is executed line by line, which helps in debugging.
  4. Platform Independent: Python programs can run on different operating systems like Windows, macOS, and Linux.
  5. Extensive Libraries: Python has a rich set of libraries such as NumPy, Pandas, and Matplotlib, which simplify complex tasks.
  6. Object-Oriented: Python supports object-oriented programming concepts like classes and objects.

Applications of Python

  1. Web Development: Frameworks like Django and Flask are used for building websites.
  2. Data Science: Libraries like Pandas, NumPy, and Matplotlib are used for data analysis and visualization.
  3. Machine Learning and AI: Libraries like TensorFlow and PyTorch are popular in AI development.
  4. Automation: Python can automate repetitive tasks using libraries like Selenium and PyAutoGUI.
  5. Game Development: Libraries like Pygame are used for creating simple games.
  6. Desktop Applications: Python can create GUI applications using Tkinter or PyQt.

Python Syntax Basics

Python uses simple syntax that resembles English, making it beginner-friendly.

Example 1: Printing a Message

print("Hello, World!")

Output:

Hello, World!

Example 2: Variables in Python

x = 5
name = "India"
print(x)
print(name)

Output:

5
India

Python Variables and Data Types

  • Variables: Containers for storing data values.
  • Data Types: Define the type of value a variable can hold.

Common Data Types in Python:

  1. int: Integer (e.g., 10, -5)
  2. float: Decimal number (e.g., 3.14, -0.99)
  3. str: String (e.g., 'Python', 'India')
  4. bool: Boolean (e.g., True, False)
  5. list: Collection of items (e.g., [1, 2, 3])
  6. tuple: Immutable collection (e.g., (4, 5, 6))
  7. dict: Key-value pairs (e.g., {'name': 'John', 'age': 25})
  8. set: Unordered collection of unique items (e.g., {1, 2, 3})

Example: Data Types

x = 10         # int
y = 3.14       # float
name = "Python"  # str
is_active = True  # bool

Python Control Flow Statements

Control flow statements are used to control the execution of code based on conditions.

1. if Statement

x = 10
if x > 5:
    print("x is greater than 5")

Output:

x is greater than 5

2. if-else Statement

x = 4
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

Output:

x is not greater than 5

3. for Loop

for i in range(5):
    print(i)

Output:

0
1
2
3
4

4. while Loop

x = 1
while x <= 5:
    print(x)
    x += 1

Output:

1
2
3
4
5

Functions in Python

Functions are blocks of reusable code that perform a specific task.

Example: Defining and Calling a Function

def greet():
    print("Hello, Welcome to Python!")

greet()

Output:

Hello, Welcome to Python!

Example: Function with Parameters

def add(a, b):
    return a + b

result = add(5, 3)
print(result)

Output:

8

Python Modules and Packages

What is a Module?

A module is a file containing Python code that can define functions, classes, and variables. It helps in organizing code into manageable parts.

Example: Using a Built-in Module

import math
print(math.sqrt(16))

Output:

4.0

Creating Your Own Module

Save the following code in a file named my_module.py:

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

Now, use the module in another Python script:

import my_module
print(my_module.greet("Student"))

Output:

Hello, Student!

What is a Package?

A package is a collection of modules organized in directories. Each directory must contain a special __init__.py file to be recognized as a package.

File Handling in Python

Python provides built-in functions to work with files, such as reading, writing, and appending data.

Example: Writing to a File

with open("example.txt", "w") as file:
    file.write("Hello, Python!")

Example: Reading from a File

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

Output:

Hello, Python!

Example: Appending to a File

with open("example.txt", "a") as file:
    file.write("\nWelcome to File Handling.")

Python Object-Oriented Programming (OOP)

Python supports OOP, which helps in organizing code using objects.

Key Concepts of OOP:

  1. Class: Blueprint for creating objects.
  2. Object: Instance of a class.
  3. Inheritance: Mechanism for a class to derive properties and methods from another class.
  4. Encapsulation: Restricting access to certain details of an object.
  5. Polymorphism: Ability to use a method in different ways.

Example: Defining a Class and Creating an Object

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")

student1 = Student("John", 20)
student1.display()

Output:

Name: John, Age: 20


Comments

Popular posts from this blog

Programming Notes by Atul Kalukhe