Python Notes
$ python --version
Python 3.12.3
Python is platform independent
python virtual machine:
The Python Virtual Machine (PVM) is an abstract machine and a crucial component of the Python runtime environment. It
is responsible for executing Python bytecode, which is a low-level,
platform-independent representation of Python source code.
It supports Virtual Environment :
Create virtual environment :
$python3 -m venv myvenv #Will install on current folder
Activate virtual environment:
$ source myvenv/bin/activate
deactivate #To deactive
(myvenv) HostName@Current folder:
print('Welcome to python training')
PIP:
pip (also known by Python 3's alias pip3) is a package manager (package management system) written in Python and is used to install and manage software packages.
pip install fastapi[all]
pip freeze > requirements.txt
pip install requirements.txt
pip list
Variables:
username = "Praveen"
city = "Hyderabad"
state = 'TG'
age=40
print(f"Myname is {username} I am from {city} {state} and my age is {age}")
data1=int(input('Enter your value-1: '))
data2=int(input('Enter your value-1: '))
print(f"Total: {(data1) + (data2)}")
print(type(data1))
Conditions:
if age>30:
print('your allowed to enter')
else:
print('Not Allowed')
If Condition with iteration:
while True:
try:
age = int(input("Enter your age: "))
if 0 <= age <= 101:
break
else:
print("Please enter a valid age between 0 and 101.")
except ValueError:
print("Invalid input! Please enter a number.")
print(f"Your age is: {age}")
#################### Array ####################
# array declarations
usernames = ['Bramha','Vishnu','Mahesh']
print(usernames)
# ['Bramha', 'Vishnu', 'Mahesh']
for username in usernames:
print(f"User Details : {username}")
for userindex,username in enumerate(usernames):
print(f"Index : {userindex} --> {username.upper()}")
for userindex,username in enumerate(usernames,start=1):
print(f"Index : {userindex} --> {username.upper()}")
Problem - Created and fill array with user input:
# initiating empty array
user_data =[]
data = int(input("How many numbers to add: "))
for i in range(data):
num = int(input(f" Enter number : "))
user_data.append(num)
print(f"values is array: {user_data}")
# calculate even or odd
for num in user_data:
if(num%2==0):
print(f"{num} is even")
else:
print(f"{num} is odd")
# calculate the addition if all numbers
res = 0
for num in user_data:
res +=num
print(f"addition res = {res}")
# Get Positive input
def get_positive_input(prompt):
while True:
value = int(input(prompt))
if value > 0:
return value
else:
print("Enter a positive value greater than 0.")
data1 = get_positive_input("Enter your value-1: ")
data2 = get_positive_input("Enter your value-2: ")
# Addition
c = data1 + data2
print(f"Addition is: {c}")
#################### Functions ####################
# Declare function
def showwelcome():
print("Welcome to the function")
showwelcome()
def calculatedata(x,y):
return print(x+y)
calculatedata(3,2)
def multireturndata(x,y):
return x,y
a,b = multireturndata(2,5)
#################### Class ####################
class user:
def showwelcome(self):
print("Welcome to the class")
def calculatedata(self,x,y):
print(f"Addition is {x+y}")
# using class
uc = user()
uc.showwelcome()
uc.calculatedata(2,3)
#########
class user:
def __init__(self): # __int__ - Constructor. It is self called
print('Defult constructor called')
user = user()
#output - Defult constructor called
class user:
def __init__(self,uname,email,city):
self.uname = uname
self.email = email
self.city = city
user = user('Praveen','praveen@mail.com','Hyd')
print(user.uname,user.email,user.city)
#Output - Praveen praveen@mail.com Hyd
class user:
def showcity(self): # Defined the function, not self Constructor
city = input('Enter city : ')
print('city will be called ', city)
user = user() # Loading call
user.showcity() # Calling method
#Output - Enter city : Hyderabad / city will be called Hyderabad
class user:
def __init__(self,uname,email,city):
self.uname = uname
self.email = email
self.city = city
def __str__(self): # This function auto called when your printing object
return f"{self.uname} - {self.email} - {self.city}"
user = user('Praveen','praveen@mail.com','Hyd')
print(user)
#output - Praveen - praveen@mail.com - Hyd
#####
### ribclass.py ###
from abc import ABC,abstractmethod
class RBI(ABC):
@abstractmethod # abstractmethod means mandatory in chaild class
def withdraw(self):
pass
@abstractmethod
def deposit(self):
pass
@abstractmethod
def checkBalance(self):
pass
def openSalaryAccount(self): # No abstractmethod so this function not mandatory in clild
pass
### ribclass.py closed ###
### sbiclass.py ####
from rbiclass import RBI # Importing RBI class from rbiclass.py file
class SBI(RBI):
def withdraw(self):
print("withdraw from SBI")
def deposit(self):
print("deposit from SBI")
def checkBalance(self):
print("checkbalance from SBI")
def openFD(self):
print('FD account opened in SBI')
### sbiclass.py closed ###
### Bankingmail.py #####
from sbiclass import SBI # Importing SBI class from sbiclass.py file
bank1 = SBI()
bank1.checkBalance()
bank1.openSalaryAccount()
bank1.deposit()
### Bankingmail.py closed #####
# Output - checkbalance from SBI / deposit from SBI
############ FASTAPI ###########
from fastapi import FastAPI
app = FastAPI()
users = ['Admin','Manager','QA']
@app.get("/Welcome")
def Show_Welcome():
return{"Message":"Welcome to FASTAPI"}
# RUN - /Documents/python-ansible/python-training/day-2/fastapi$ uvicorn crudapp:app
@app.get("/loadusers")
def showusers():
return {"message":users}
# Troubleshoot - sudo lsof -i :8000; kill -9 <PID>
###########
# database.py - File
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQL_DB = "sqlite:///./mytest.db"
engine = create_engine(
SQL_DB, connect_args={"check_same_thread": False}
)
SessioLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_connection():
db = SessioLocal()
try:
yield db
finally:
db.close()
-----
# schema.py - file name
from pydantic import BaseModel
# the data you are expecting from the client
class Base(BaseModel):
name: str
sclass: str
section: str
---
# models.py - File name
# schema represenation
from sqlalchemy import Column,String
from .database import Base
class Student(Base):
__tablename__="STUDENT"
name= Column(String,primary_key=True)
sclass= Column(String)
section= Column(String)
class staff(Base):
__tablename__="STAFF"
name= Column(String,primary_key=True)
sclass= Column(String)
section= Column(String)
---
#studentapp.py - File
from fastapi import FastAPI,APIRouter,Depends,status
from fastapi.params import Body
from sqlalchemy.orm import Session
from .. import schema,models
from .. database import engine,get_connection
router= APIRouter(tags=["Student Application"])
@router.post("/addstudent")
def studentRegister(student:schema.Base, db:Session=Depends(get_connection)):
newdata = models.Student(**student.dict())
db.add(newdata)
db.commit()
return {"message":"db created"}
@router.post("/addstaff")
def staffregister(staff:schema.Base, db:Session=Depends(get_connection)):
newdata = models.staff(**staff.dict())
db.add(newdata)
db.commit()
return {"message":"staff created"}
-----
# Crudapp.py - File
from fastapi import FastAPI
from .routers import studentapp
from .database import engine,get_connection
from . import models,schema
# create table in db while loading model class
models.Base.metadata.create_all(bind=engine)
app=FastAPI()
app.include_router(studentapp.router)
######
Key Difference Between List, Array and Tuple
Feature | List | Array | Tuple |
---|
Mutability | Mutable | Mutable | Immutable |
---|
Data Type | Can store different types | Stores elements of the same type | Can store different types |
---|
Ordered | Yes | Yes | Yes |
---|
Performance | Slower for numerical operations | Faster for numerical operations | Faster than lists (due to immutability) |
---|
Memory Efficiency | Less efficient | More efficient for large data | More memory-efficient than lists |
---|
Usage | General-purpose collection | Numerical and homogeneous data | Fixed data, constants |
---|
Syntax | [ ] | array() | ( ) |
---|
Indexing | Supported | Supported | Supported |
---|