Phyton Preparation
Phyton Preparation
MOD
7%3=4
2**3=8
String
print(“hello \n World”)
result:
hello
World
print(“hellow \t world”)
Result:
Hellow world
len(“I am”)
Reuslt:
Syntax of string
[start:stop:step]
a[2:3:4] # in this example it will start to count from 2 till 3 and jumping 4
a=”Hi Kamran”
Result: Kamran
'H arn'
'narmaK iH’
print("{} {} {}".format("Salam","Kamran","Necesen"))
result=101.214
print("{r:1.2f}".format(r=result))
101.21
name="Xose"
>>>
List in Python
my_list=[1,2,3,4]
my_list1=[5,6,7,8]
my_list+mylist1=[1.2.3.4.5.6.7.8]
-------------
my_list[0]=999
result: my_list=[999.2.3.4]
------------
my_list.append(121)
---------------
my_list.pop(0)
result:my_list=[2,3,4,’List’]
------------------
my_file=['d','t','b','a','k']
>>> my_file.sort()
>>> my_file
---------------------
my_list=[1,4,2,3]
my_list.reverse()
Result: 4.3.2.1
Dictionary in python
prices={'orange':2.25,'banana':1.23,'grape':2.01}
>>> prices
>>> prices[‘banana’]
1.23
prices
>>> prices["banana"]
1.23
>>>
>>> prices1={'k1':[0,2,3,4]}
>>> prices1
>>> prices1['k1'][1]
2
prices1={'k1':[0,2,3,4],'k2':{'insideKey':100}}
print(prices1['k2']['insideKey'])
prices1={'k1':[0,2,3,4],'k2':{'insideKey':100},'k3':['a','b','c']}
print(prices1['k2']['insideKey'])
print(prices1['k3'][2].upper())
C
>>> prices1.keys()
------------------------------
>>> prices.values()
-----------------------
>>> prices.items()
dict_items([('orange', 2.25), ('banana', 1.23), ('grape', 2.01)]) (shows all dic tree)
>>>
t=('a','b',1,2,3,4)
print(type(t))
------------------
print(t[0])
Result:a
SET in python. In set all elemnts must be unique and one character can be added at one time
st=set()
st.add(1)
Result: {1}
Booleans
myfile=open('myfile.txt')
myexcellfile=open('Gi_SGi_20200320_152800.csv')
When we want to read the file for the second time, need to seek the cursor at the begging of
the line
myfile.seek(0)
print(myfile.read())
--------------------
print(myexcellfile.readlines())
------------------------------
mytestfile=open("C:/Users/k80044720/Desktop/x.txt")
we can open the file as briefly and later no need to close it back
context=mynewfile.read()
print(context)
-------------------------------
context=f.read()
print(context)
with open('myfile.txt', mode='a') as f:
Comparation operators
not 2==2
Statements in python
if loc=="Auto Shop" :
elif loc=="Shops" :
elif loc=="Supermarket" :
print("Supermarjet is cool!")
else:
Loops in Pyhton
mylist=[1,2,3,4,5,6,7,8,9,10]
if num % 2 == 0:
else:
print(a)
print(b)
dic={'k1':1,'k2':2,'k3':3,'k4':4}
print(key,":",value)
While in Python
x=0.0
print(type(x))
while x<=5:
if x!=3:
x=x+1
else:
x=x+1
else:
print("count is stopped")
-----------------------------
mylist=[1,2,3,4,5]
print(f'{num}')
Result:
------------------------
print(f'{num}')
Result:
----------------------------
Generate numbers
x=list(range(0,10,1))
print(x)
Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
---------------------------
print(item,"-:-",index)
Result:
0 -:- a
1 -:- b
2 -:- c
3 -:- d
4 -:- e
5 -:- f
6 -:- g
7 -:- h
8 -:- l
-------------------------------
list1=[1,2,3,]
list2=['a','b','c']
list3=[100,200,300]
print(item)
Result:
x= list(zip(list1,list2,list3))
print(x)
Result:
-----------------------------------
Great method of checking if the letter exist in list, dictionaries and for others
word='abcdefghlmnopqrstwxzaaa'
if 'y' in word:
else:
-----------------------------------
min(list4)
max(list4)
---------------------------------------
Firstly lets import python built in library. In this example we imported shuffle library
list1=[1,2,3,4,5,6,7,8,9,10]
shuffle(list1)
print(list1)
-----------------------------------------
(
string1='hello'
list1=[]
list1.append(letter)
string1='hello'
print(list2)
celcius=[50,100,30.40,12,3.5,10]
print(faranheyt)
faranheyt1=[]
faranheyt1.append((9/5)*temp1+32)
print(faranheyt1)
--------------------------------------
Functions
Some examples:
def test_function():
'''
NO input
-------
output:hello.
'''
print("Hello")
test_function()
def say_fuc(name):
print("hello", name)
say_fuc('Kamran')
def say_func1(name='David'):
print("hello",name)
say_func1("Kamran By")
def add(n1=0,n2=0):
return n1+n2
print(add(123,321))
def dog_check(mystring):
------------------------------------------
Args accepts all input without limit. And it shows the result as tuple
def sumup(*args):
return sum(args)
print(sumup(1,2,3,4,5,6,7,8,9,0,0,9,8,7,6,5,4,3,2,1,))
def sumup(*spam):
return sum(spam)
print(sumup(1,2,3,4,5,6,7,8,9,0,0,9,8,7,6,5,4,3,2,1))
--------------------------------
def sumup(*args):
result=[]
result.append(items)
return result
print(sumup(1,2,3,4,5))
------------------------------
def veg(**kwargs):
print(kwargs)
if "fruit" in kwargs:
else:
veg(fruit="apple")
dic={'fruit':'qeni'}
print(dic['fruit'])
----------------------------------
Lets combine args and kwargs together.
dic={'fruit':'qeni'}
print(dic['fruit'])
def myfunc(*args,**kwargs):
print(args)
print(kwargs)
print(myfunc(1,2,3,4,56,fruit="apple",food="bread"))
Result:
(1, 2, 3, 4, 56)
None
-------------------------------------
.join is used to join some parameters and it changes the format of list to the string
l2=['hello', 'Kamran','From','Zaqatala']
l3=" ".join(l2)
print(l3)
print(type(l2))
--------------------------------
--------------------------------------
def square(num):
return num**2
mystring=[1,3,5,9,11,13]
for items in map(square,mystring):
print(items)
print(list(map(square,mystring))) Result:
Result:
25
81
121
169
-----------------------
return a + b
print(x)
print(list(x))
---------------------------
Filter does the same thing but it returns value if the result of function is true(Boolean)
def funnkc1(num):
return num%2==0
print(res1=list(filter(funnkc1,mystring)))
Result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
-----------------------------
Mysting=[1,2,3,4]
list1=list(map(lambda num:num**2,mystring))
print(list1)
Result: [1,4,9,16]
OOP in python
class Calculation():
def __init__(self,num1,num2):
self.add=num1+num2
self.minus=num1-num2
self.devide=num1/num2
self.multiply=num1*num2
multi=Calculation(num1=12, num2=2)
print(multi.multiply)
Result:24
------------------------
class Calculation():
def __init__(self,num1,num2):
self.add=num1+num2
self.minus=num1-num2
self.multi=num1*num2
self.devide=num1/num2
res=Calculation(12, 3)
print(res.names)
---------------------------
class Calculation():
def __init__(self,num1,num2):
self.add=num1+num2
self.minus=num1-num2
self.multi=num1*num2
self.devide=num1/num2
def description(self):
res=Calculation(12, 3)
res.description()
------------------------
class Calculation():
def __init__(self,num1,num2):
self.add=num1+num2
self.minus=num1-num2
self.multi=num1*num2
self.devide=num1/num2
def description(self):
result1=self.add+self.minus+self.multi+self.devide
return result1
res=Calculation(12, 3)
print(res.names)
print(res.description())
Result=64.0
-------------------------
def __init__(self,num1,num2):
self.add=num1+num2
self.minus=num1-num2
self.multi=num1*num2
self.devide=num1/num2
def description(self,a):
result1=(self.add+self.minus+self.multi+self.devide)*a
return result1
res=Calculation(12, 3)
print(res.names)
print(res.description(10))
Result:640
------------------------------------
Another example
class circle():
pi=3.14
def __init__(self,radius):
self.radius=radius
def cal(self):
return self.radius*self.radius*circle.pi*2
myres=circle(10)
print(myres.cal())
Result:628
------------------------------
Inheritance
class Animal():
def __init__(self):
print("Animal is created")
def who_am_i(self):
print("I am animal")
def eat(self):
print("I am eating")
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog is created")
def color(self):
Animal.who_am_i(self)
mydog=Dog()
mydog.eat()
mydog.color()
Result:
Animal is created
Dog is created
I am eating
I am animal
-------------------
Polymorpysim in pyhton
class Dog():
def __init__(self,name):
self.name=name
def speak(self):
class Cat():
def __init__(self,name):
self.name=name
def speak(self):
reks=Dog("Reks")
tom=Cat("Tom")
def pet_speak(pet):
print(pet.speak())
pet_speak(reks)
pet_speak(tom)
Result:
----------------------
another example
class India():
def capital(self):
def language(self):
def type(self):
class USA():
def capital(self):
def language(self):
def type(self):
obj_ind = India()
obj_usa = USA()
country.language()
country.type()
------------------------------
Magic function
mylist=[1,2,3,4,5]
class Book():
def __init__(self,title,author,page):
self.title=title
self.author=author
self.page=page
def __str__(self):
def __len__(self):
return self.page
def __del__(self):
b=Book("Python","Kamran Carayev",500)
Result:
500
print(b)
----------------------------------------------------
C:\Users\k80044720\Desktop\phyton\sub\sub1
mymodule.by file:
def myfunc():
myprogram.py file:
myfunc()
sub.funksub()
from sub.sub1 import sub1
sub1.subfunc1()
sub.py file:
def funksub():
print("I am in subdirector")
sub1.py file:
def subfunc1():
-------------------------------------------------
Error Handling
try:
def add(n1,n2):
return n1+n2
num1=10
num2=int(input("enter NUM2:"))
result=add(num1,num2)
except:
else:
print("Succesfuly executed")
print(result)
-------------------------------
try:
f=open("test1234",'r')
except TypeError:
except OSError:
finally:
----------------------------------------
Another example
def ask():
tr=0
while True:
try:
except:
if tr>=5:
break
else:
tr+=1
continue
else:
break
finally:
ask()
---------------------------------------------
Python decoration
def hello(name="Kamran"):
def greet():
def Welcome():
if name=="Kamran":
return greet
else:
return Welcome
myfunk=hello("Kamran")
print(myfunk())
----------------------
def hello():
def other(some_def_func):
print(some_def_func())
print(other(hello))
Result:
Hi i am hello()
-----------------------------------------
def new_decerater(original_funck):
def wrap_funck():
original_funck()
return wrap_funck
def i_need_decoration():
print("decorate me")
my_value=new_decerater(i_need_decoration)
print(my_value())
Result:
decorate me
None
--------------------------------
Decoration with @
def new_decerater(original_funck):
def wrap_funck():
original_funck()
return wrap_funck
@new_decerater
def i_need_decoration():
print("decorate me")
print(i_need_decoration())
Result:
decorate me
--------------------------------
def create_cubs(n):
for i in range(n):
yield i**3
for x in create_cubs(10):
print(x)
Result:
27
64
125
216
343
512
729
--------------------
def create_cubs(n):
for i in range(n):
yield i**3
g=create_cubs(4)
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
Result:
27
-------------------------
Iteration of string
s='hello'
s_iter=iter(s)
print(next(s_iter))
Result:
Djange Web
2.1 Djang o 2
Che at She e t .p d f.p d f
URLS:
Everything about URLS are processed in urls.py file. Basically the url syntax is like below
urlpatterns = [
path('admin/', admin.site.urls),
]
Lets create one example for this URL: in this case we need to create options.py and import it to urls.py
from . import options
urlpatterns = [
path('', options.home),
]
It means that when user firstly enter the web page the request is coming to urls.py file. Then it will
redirect the request to the home() function which is located in options.py file
In home() function example we will return one string as the web page
from django.http import HttpResponse
def home(request):
return HttpResponse("THis the home Page function")
Using templates:
First thing we should do is that create one folder which allows to insert all web page documentations. So
in this case we need to create one folder (for example 'folderdir' on root directory and then create
index.html file.
'DIRS': ['folderdir'],
Then we need to input render into the options.py file end redirect request in home function
from django.shortcuts import render
def home(request):
return render(request, "index.html")
In addition we can pass any argument in with render to the next page
def kamran(request):
return render(request,"kamran.html", {'key1':"THis is the Value of key
1"})
in Kamran.html file:
{{key1}}
<html>
<body>
<h1>Index.htlm file is activated</h1>
<form action="{% url 'count' %}">
<textarea cols="40" rows="8" name="full_text"></textarea>
<br/>
<input type="submit" value="TEXT"></input>
</form>
</body>
</html>
Need to add one more path for count and redirect it to options.py
path('count/', options.count, name='count'),
Then create count function and render to count.html and forward the text
def count(request):
fulltext=request.GET['full_text']
return render(request,'count.html', {'KEY1':fulltext})
index.html
<html>
<h1>Count web page</h1>
{{KEY1}}
</html>
First enter the project directory and start git there from command line
#git init
#git add –A
#git status
Then enter the github.com web site and create new repository. After that enter your project to the new
repository by below commands
or
#vurtualenv env1
#source env1/bin/activate
In Windows:
#env\bin\Scripts\activate
#deactivate
Even we have installed djnago on PC, we need to download and install Django after entering new
envisonment
after creating new web site we may want to stop uploading some important files to GIT
to do that need to create .gitignore file and specify all required files to omit
APPs in python
MODELS in Django
In first step lets go to jobs/models.py and add below lines. It will be
used for working with images
from django.db import models
class jobs(models.Model):
image=models.ImageField(upload_to='images/')
summary=models.CharField(max_length=200)
Admin in Django
First we need to create superuser from CMD
#python manage.py createsuperuser
Then we will be able to login admin web page
Its time to see the jobs in admin panel. To do that we need to imports
jobs from models.py in jobs directory
jobs/admin.py
from .models import jobs
PostgreSQL
Firstly need to install PostgreSQL db on server or computer then need
to open shell t login to the DB
then type below command to see current user
#\du
by fefault postgres user dont have password. lets set pasword
#\password postgres
then lets create database
#CREATE DATABASE portfoliodb
thats all for confiruation in DB. the next section we will go to change
DB settings in django prject
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'portfoliodb',
'USER': 'postgres',
'PASSWORD': 'admin',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
Lets start:
1)Create class in blogs/models.py
class Blog(models.Model):
title=models.CharField(max_length=255)
pub_date=models.DateTimeField()
body=models.TextField()
image=models.ImageField(upload_to='images/')
3) Create migration
#python manage.py makemigrations
4) migrate
#python manage.py migrate
5) add to the admin (register in admin page) in blods/admin.py
from .models import Blog
admin.site.register(Blog)
def home(request):
jobs1=jobs.objects
return render(request, 'jobs/index.html', {'KEY1':jobs1})
{% for i in KEY1.all %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="bd-placeholder-img card-img-top" width="100%" heig
ht="225" src="{{ i.image.url }}" preserveAspectRatio="xMidYMid slice" focu
sable="false" role="img" aria-label="Placeholder: Thumbnail
"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c
"/><text x="50%" y="50%" fill="#eceeef" dy=".3em"></text>
<div class="card-body">
<p class="card-text">{{i.summary}}</p>
</div>
</div>
</div>
{% endfor %}
Create blog page and query all data in separate blog page
/portfolio/urls.py
from django.urls import path, include
path('blog/', include('blog.urls')),
urlpatterns = [
path('', views.allblogs, name='allblogs'),
def allblogs(request):
blogs=Blog.objects
{% for y in KEY2.all %}
<a href=""><h3>{{y.title}}</h3> </a>
<h5>{{y.pub_date}}</h5>
<img src="{{ y.image.url }}" class="img-fluid" height="200"
width="250" >
<p>{{ y.body }}</p>
{% endfor %}
Its better not to query all data in summary page. So we will create
additional function def summary(self) in /blog/models.py to limit the
number of symbols
/blog/modules.py
class Blog(models.Model):
title=models.CharField(max_length=255)
pub_date=models.DateTimeField()
body=models.TextField()
image=models.ImageField(upload_to='images/')
def summary(self):
return self.body[:100]
<p>{{ y.summary }}......</p>
st rft im e .d o cx
in the next step lets query all detail information when enter blog detail
page.
Firstly need to create new url in blog/urls.py
urlpatterns = [
path('', views.allblogs, name='allblogs'),
path('<int:blog_id>/', views.detail, name='detail'),
]
def detail(request, blog_id):
detailblog=get_object_or_404(Blog, pk=blog_id)
return render(request,'blogs/detail.html', {'KEY4':detailblog})
{% for y in KEY2.all %}
<a href="{% url 'detail' y.id %}"><h3>{{y.title}}</h3> </a>
<h5>{{y.pub_date_summary}}</h5>
<img src="{{ y.image.url }}" class="img-fluid" height="200" widt
h="250" >
<p>{{ y.summary }}......</p>
{% endfor %}
</div>
Lets create new static files in Django. This files are never changed.
We create one static folder in portfolio/static and put two files there.
One is resume in pdf format and another one is jpeg file
Then we need to add below scripts in portfolio/settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'portfolio/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
Then we need to load static files into the directory where we need
them. In this example we will load them in index.html file
{% load static %}
link" href="{% static 'Kamran_JarayevCV.pdf' %}">Resume</a>
Adding HTML header or as separate entity in Django
Firstly lets create base.html under
projecthunt/templates/base.html
(projecthunt is the project name)
Then add below scripts. It means that this html file is
the header or footer html where all other templates
will use it
Hello this is the header
{% block content %}
{% endblock %}
Hello this is the this is the footer
{% extends 'base.html' %}
{% block content %}
<br>
THis it the home.html file
<br>
{% endblock %}
Sign Up function
Based on our design we will redirect all accounts
request to the accounts/urls.py page from main
urls.py
path('accounts/', include('accounts.urls')),
Then we will enter below script in accounts/urls.py
urlpatterns = [
path('signup', views.signup, name='signup'),
]
{% extends 'base.html' %}
{% block content %}
<br>
{% if error %}
{{ error }}
{% endif %}
<h1>Signup</h1>
<form method="POST" action="{% url 'signup' %}">
{% csrf_token %}
Username:
<br/>
<input type="text" name="username">
<br/>
Firstname:
<br/>
<input type="text" name="firstname">
<br/>
Last name:
<br/>
<input type="text" name="lastname">
<br/>
E-mail:
<br/>
<input type="email" name="email">
<br/>
<!--
-->
Password:
<br/>
<input type="password" name="password1"/>
<br/>
Confirm Password:
<br/>
<input type="password" name="password2"/>
<br/>
<br/>
<input class="btn btn-primary " type="submit" value="Sign UP!"/>
</form>
<br>
{% endblock %}
Log IN
Firstly need to work on login.html
{% extends 'base.html' %}
{% block content %}
<br>
{% if error %}
{{ error }}
{% endif %}
<h1>Log-in page</h1>
<form method="POST" action="{% url 'login' %}">
{% csrf_token %}
Username:
<br/>
<input type="text" name="username">
<br/>
Password:
<br/>
<input type="password" name="password"/>
<br/>
<br/>
<br/>
<input class="btn btn-primary " type="submit" value="Login"/>
</form>
<br>
{% endblock %}
def login(request):
if request.method=='POST':
user = auth.authenticate(username=request.POST['username'], passwo
rd=request.POST['password'])
if user is not None:
auth.login(request, user)
return redirect('home')
else:
return render(request, 'accounts/login.html', {'error':'Userna
me or password does not exsit, or account does not exist '})
else:
return render(request, 'accounts/login.html')
{% endif %}
Logout page
Need to create logout path in /accounts/urls.py
path('logout', views.logout, name='logout'),
def logout(request):
if request.method=='POST':
auth.logout(request)
return redirect('home')
{% if user.is_authenticated %}
<li class="nav-item active">
<a class="nav-link enable" href="javascript:
{document.getElementById('logout').submit()}" onclick="">Log Out</a>
<form id="logout" method="POST" action="{% url 'lo
gout' %}">
{% csrf_token %}
<input type="hidden"/>
</form>
</li>
{% else %}
<li class="nav-item active">
<a class="nav-link enable" href="{% url 'signup' %
}">Sign UP</a>
</li>
<li class="nav-item active">
<a class="nav-link enable" href="{% url 'login' %}
">Sign in</a>
</li>
{% endif %}
Customization of admin
site when adding model
class Post(models.Model):
title=models.CharField(max_length=120, blank=True)
content=models.CharField(max_length=500)
created_date=models.DateTimeField(auto_now_add=True)
update_date=models.DateTimeField(auto_now=True)
def __str__(self):
return (self.title)
class Meta:
verbose_name="Post Model control panel"
#verbose_name_plural="Main Control Unit"
ordering=['created_date']
def __str__(self):
return self.category_name
class Meta:
verbose_name='Categories'
class Post(models.Model):
post_category=models.ManyToManyField(Category)
title=models.CharField(max_length=120, blank=True)
content=models.CharField(max_length=500)
created_date=models.DateTimeField(auto_now_add=True)
update_date=models.DateTimeField(auto_now=True)
def __str__(self):
return (self.title)
class Meta:
verbose_name="Post Model control panel"
#verbose_name_plural="Main Control Unit"
ordering=['created_date']
admin.site.register(Post)
admin.site.register(Category)
In views.py
def one_example(request):
if request.method=='POST':
data={}
received_message=request.POST.get('test_message',None)
data={'received_message':received_message}
return render(request, 'posts/form.html',data)
print(data)
return render(request, 'posts/form.html')
in form.html
<html>
<form action="" method="POST">
{% csrf_token %}
<input type="text" name="test_message">
<input type="submit" value="send">
</form>
<br>
{% if received_message%}
<h1>{{ received_message }}</h1>
{% endif %}
</html>