0% found this document useful (0 votes)
2 views

Python Basics

Uploaded by

KunalKaushik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Basics

Uploaded by

KunalKaushik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

elif x == 0:

Python Basics print("x is zero")


else:
Python is a versatile and widely-used programming print("x is negative")
language known for its simplicity and readability.
Here's a quick overview of some basics to get you Loops are used to repeat a block of code multiple
started: times.

1. Variables and Data Types python


Copy code
# For loop
Variables store information that can be used and for i in range(5):
manipulated in a program. print(i)

python # While loop


Copy code count = 0
# Integer while count < 5:
x = 5 print(count)
count += 1
# Float
y = 3.14 4. Functions
# String
name = "Alice" Functions allow you to encapsulate code into
reusable blocks.
# Boolean
is_valid = True python
Copy code
2. Basic Operations def greet(name):
return f"Hello, {name}!"

Python supports basic arithmetic operations. print(greet("Alice"))

python
Copy code
5. Lists
# Addition
sum = x + y Lists are ordered collections of items.
# Subtraction python
difference = x - y Copy code
fruits = ["apple", "banana", "cherry"]
# Multiplication
product = x * y # Accessing elements
print(fruits[0]) # apple
# Division
quotient = x / y # Adding elements
fruits.append("date")
# Exponentiation
power = x ** 2 # Removing elements
fruits.remove("banana")
# Modulus (remainder)
remainder = x % 2 # Slicing
print(fruits[1:3]) # ['cherry', 'date']
3. Control Structures
6. Dictionaries
Conditional Statements allow you to execute
certain code based on conditions. Dictionaries are collections of key-value pairs.

python python
Copy code Copy code
if x > 0: person = {"name": "Alice", "age": 25,
print("x is positive") "city": "New York"}
1|Page
Variables are used to store information that can be
# Accessing values
referenced and manipulated in a program.
print(person["name"]) # Alice

# Adding key-value pairs python


person["email"] = "[email protected]" Copy code
# Integer
# Removing key-value pairs x = 5
del person["age"]
# Float
y = 3.14
7. Importing Modules
# String
You can import and use external libraries and name = "Alice"
modules in Python. # Boolean
is_valid = True
python
Copy code
import math Data Types

print(math.sqrt(16)) # 4.0 Python supports various data types:

8. File I/O  Integers: Whole numbers, e.g., 1, 2, -5


 Floats: Decimal numbers, e.g., 3.14, 2.0
Reading from and writing to files.  Strings: Text, e.g., "Hello", 'Python'
 Booleans: True or False
python
Copy code
# Writing to a file 2. Basic Operations
with open("example.txt", "w") as file:
file.write("Hello, world!") Python supports basic arithmetic operations:
# Reading from a file python
with open("example.txt", "r") as file: Copy code
content = file.read() # Addition
print(content) sum = x + y

These basics should give you a good starting point. # Subtraction


Python's syntax is designed to be easy to read and difference = x - y
write, making it an excellent language for beginners. # Multiplication
If you have any specific questions or need further product = x * y
examples, feel free to ask!
# Division
quotient = x / y
Python Notes
# Exponentiation
Here are some comprehensive notes on Python, power = x ** 2
covering various aspects of the language: # Modulus (remainder)
remainder = x % 2

3. Control Structures
Python Basics
Conditional Statements
1. Variables and Data Types
Control the flow of execution based on conditions.
Variables
python
Copy code
if x > 0:

2|Page
print("x is positive") Dictionaries are collections of key-value pairs.
elif x == 0:
print("x is zero")
python
else:
Copy code
print("x is negative")
person = {"name": "Alice", "age": 25,
"city": "New York"}
Loops
# Accessing values
print(person["name"]) # Alice
Repeat a block of code multiple times.
# Adding key-value pairs
For Loop person["email"] = "[email protected]"

python # Removing key-value pairs


Copy code del person["age"]
for i in range(5):
print(i)
7. Importing Modules
While Loop Import and use external libraries and modules.
python
python
Copy code
Copy code
count = 0
import math
while count < 5:
print(count)
print(math.sqrt(16)) # 4.0
count += 1

4. Functions 8. File I/O

Reading from and writing to files.


Functions allow you to encapsulate code into
reusable blocks. python
Copy code
python # Writing to a file
Copy code with open("example.txt", "w") as file:
def greet(name): file.write("Hello, world!")
return f"Hello, {name}!"
# Reading from a file
print(greet("Alice")) with open("example.txt", "r") as file:
content = file.read()
5. Lists print(content)

Lists are ordered collections of items. Advanced Topics


python
Copy code 1. List Comprehensions
fruits = ["apple", "banana", "cherry"]
A concise way to create lists.
# Accessing elements
print(fruits[0]) # apple python
Copy code
# Adding elements squares = [x**2 for x in range(10)]
fruits.append("date")

# Removing elements 2. Lambda Functions


fruits.remove("banana")
Anonymous functions defined with the lambda
# Slicing
print(fruits[1:3]) # ['cherry', 'date'] keyword.

python
6. Dictionaries Copy code

3|Page
add = lambda a, b: a + b Creating a package:
print(add(2, 3)) # 5
markdown
3. Error Handling Copy code
mypackage/
__init__.py
Handle exceptions to make your program more module1.py
robust. module2.py

python Using a package:


Copy code
try:
result = 10 / 0 python
except ZeroDivisionError: Copy code
print("Cannot divide by zero") from mypackage import module1
finally:
print("This will execute no matter print(module1.some_function())
what")
6. Virtual Environments
4. Classes and Objects
Isolate dependencies for different projects.
Object-oriented programming allows you to define
custom data types. bash
Copy code
# Create a virtual environment
python python -m venv myenv
Copy code
class Person: # Activate the virtual environment
def __init__(self, name, age): # On Windows
self.name = name myenv\Scripts\activate
self.age = age
# On macOS/Linux
def greet(self): source myenv/bin/activate
return f"Hello, my name is
{self.name} and I am {self.age} years # Install packages
old." pip install requests
person = Person("Alice", 25) # Deactivate the virtual environment
print(person.greet()) deactivate

5. Modules and Packages 7. Working with APIs


Organize your code into modules and packages for Use the requests library to interact with APIs.
better maintainability.
python
Creating a module: Copy code
import requests
python
Copy code response =
# mymodule.py requests.get("https://api.github.com")
def greet(name): data = response.json()
return f"Hello, {name}!" print(data)

Using a module: 8. Working with Databases


python Use libraries like sqlite3 to interact with databases.
Copy code
import mymodule python
Copy code
print(mymodule.greet("Alice")) import sqlite3

4|Page
# Connect to a database (or create one if
it doesn't exist) # Pandas DataFrame
conn = sqlite3.connect('example.db') data = {'Name': ['Alice', 'Bob'], 'Age':
[25, 30]}
# Create a cursor object df = pd.DataFrame(data)
cur = conn.cursor()
# Plotting with Matplotlib
# Create a table plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
cur.execute('''CREATE TABLE IF NOT EXISTS plt.xlabel('X axis')
users (id INTEGER PRIMARY KEY, name TEXT, plt.ylabel('Y axis')
age INTEGER)''') plt.title('Simple Plot')
plt.show()
# Insert a row of data
cur.execute("INSERT INTO users (name, age)
VALUES ('Alice', 25)")
These notes cover the basics and some advanced
# Commit the changes topics in Python. Let me know if you need more
conn.commit() details on any specific area!
# Query the database
cur.execute("SELECT * FROM users")
rows = cur.fetchall()
for row in rows:
print(row)

# Close the connection


conn.close()

9. Web Development

Use frameworks like Flask or Django for web


development.

Flask Example:

python
Copy code
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
return "Hello, Flask!"

if __name__ == '__main__':
app.run(debug=True)

10. Data Science

Use libraries like NumPy, Pandas, and Matplotlib for


data science tasks.

python
Copy code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# NumPy array
arr = np.array([1, 2, 3, 4, 5])

5|Page

You might also like