Comprehensive Guide To Python Commands
Comprehensive Guide To Python Commands
1. Introduction to Python
Python is a high-level, interpreted programming language known for its readability and ease of use.
2. Basic Syntax
# Variable assignment
x=5
y = "Hello"
z = 3.14
# Data types
a = 10 # int
b = 10.5 # float
c = "Python" # str
d = [1, 2, 3] # list
e = (1, 2, 3) # tuple
f = {1, 2, 3} # set
4. Operators
Comprehensive Guide to Python Commands
# Arithmetic operators
x=5
y=2
print(x + y) # 7
print(x - y) # 3
print(x * y) # 10
print(x / y) # 2.5
print(x % y) # 1
# Comparison operators
print(x == y) # False
print(x != y) # True
# Logical operators
5. Control Flow
# if statement
x = 10
if x > 5:
# for loop
for i in range(5):
print(i)
# while loop
i=0
while i < 5:
print(i)
i += 1
6. Functions
def greet(name):
# Importing a module
import math
print(math.sqrt(16)) # 4.0
print(sqrt(25)) # 5.0
Comprehensive Guide to Python Commands
8. File Handling
# Writing to a file
file.write("Hello, World!")
content = file.read()
9. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
class Dog:
self.name = name
def bark(self):
dog = Dog("Rex")
# datetime module
import datetime
now = datetime.datetime.now()
print(now)
# os module
import os
import numpy as np
print(arr * 2) # Outputs: [2 4 6]
import pandas as pd
print(df)
# List comprehensions
# Lambda functions
add = lambda x, y: x + y
# Decorators
def decorator_func(func):
def wrapper():
func()
return wrapper
@decorator_func
def hello():
print("Hello, World!")
hello()
# Generators
def my_generator():
yield 1
Comprehensive Guide to Python Commands
yield 2
yield 3
gen = my_generator()
print(value) # Outputs: 1 2 3
# Context managers
file.write("Hello, World!")