Python Tutorial for Beginners


Well Come to Fahad Hussain Free Computer Education, here you can learn different courses FREE... Here is the code session of Python, you can copy, paste the code from here ...

For video tutorial  CLICK_HERE

Enjoy Python Learning

          Here   _ _ _ _ _    is indicating the separate chunk of code in the given tutorial.


Tutorial 1:
For video tutorial  CLICK_HERE

Introduction to Python, using Slider for addition reading you can Click  Here:

Tutorial 2:
For video tutorial  CLICK_HERE

print('Hi, New Programmer in Python!')
print("Hi, New Programmer in Python!")
print('''Hi,
New
Programmer
in
Python!''')
_ _ _ _ _ _ _ _ _ _ _ _ _

a=2;
print("Index number of a is: {} ",format(id(a)))

a=3;
print("Index number of a is: {} ",format(id(a)))
_ _ _ _ _ _ _ _ _ _ _ _ _

#number
a=1;
print(a)

b=2.52
print(b)

c=2+5j;
print(c)
_ _ _ _ _ _ _ _ _ _ _ _ _

#string
s1='Fahad'
s2="Hussain"

#cont
print(s1+s2)
#rep
print(s1*3)
#slic
print(s1[0:4])
#index
print(s1[-1:]+s1[1])
#find
print(s1.find('d'))
#replace
print(s1.replace('d','z'))
#split
print(s1.split('.'))
#count
print(s1.count('a',0,4))
#upper
print(s1.upper())
#max
print(s1.max())
#min
print(s1.min())
#isalpha
print(s1.isalpha())
_ _ _ _ _ _ _ _ _ _ _ _ _

s2 = " Fahad";
s3 = 'Fahad ';
print(s2)
#speace left, right or both side...
print(s1.lstrip())
print(s1.rstrip())
print(s1.strip())

_ _ _ _ _ _ _ _ _ _ _ _ _


#tuple

tup = (1,1.25, 3j, 'a', "ABC")
print(tup)
tup1 = (1,1.25, 3j, 'a', "ABC",(1,2,3,4,"asdf"))
print(tup1)
print(tup1+(11,11))
print(tup*2)
print(tup[1:2])
print([0])


Tutorial 3:
For video tutorial  CLICK_HERE

#DataTypes in Python
#list
li =[1,1.25, "asdf",'as', 5j]
Dict = [1:"abc", 2:"DNA", 3:4+5j]
sett=[1,2,3,4,5]
_ _ _ _ _ _ _ _ _ _ _ _ _

listt =[1, 1.25, "asdf", 'ss', 5j]
listt[0]="Asia"
print(listt)
print(listt+['Fahad'])
print(listt*2)
print(listt[1:3])
print(listt[0])
print(listt.append('ssss'))
print(listt)
print(listt.extend(['s','d',"asd"]))
print(listt)
print(listt.insert(0,'Hussain'))
print(listt)
print(listt.pop())
print(listt)
_ _ _ _ _ _ _ _ _ _ _ _ _
Dict1=[]
Dict=[1:"Fahad", 2:"Hussain", "Faculty:"Yes" ]
print(Dict[1])
print(len(Doit)
print(Dict.keys())
print(Dict.values())
print(Dict.items())
print(Dict.get(1))
print(Dict.update((2:'Ali'}))
print(Dict.pop(2))
_ _ _ _ _ _ _ _ _ _ _ _ _

#Set
s = (1,2,3,4,5,5,5)
print(s)
s1=(1,2,3)
s2 = (1,2,'b')
print(s1 | s2)
print(s1 & s2)
print(s1 - s2)


Tutorial 4:
For video tutorial  CLICK_HERE
a=1;
if(a>=1):
  print("The value of a is 1 or greater "+str(a))

_ _ _ _ _ _ _ _ _ _ _ _ _
a=0;
if(a>=1):
  print("The value of a is 1 or greater "+str(a))
else:
  print("Else Body of if!")
_ _ _ _ _ _ _ _ _ _ _ _ _
a=1;
b=2;
if(a>=1):
  print("The value of a is 1 or greater "+str(a))
  if(b==2):
    print("Nested if!")
  else:
    print("first If body")
else:
  print("first if else body")
 
_ _ _ _ _ _ _ _ _ _ _ _ _
a=10
b=20
c=30
if(a>10):
  print("Greater")
elif b>=20:
  print("20 Greater or equal")
elif c>30:
  print("Greater")

_ _ _ _ _ _ _ _ _ _ _ _ _
a=1
b=2
c=3
if(a>10):
  print("Greater")
elif b>=20:
  print("20 Greater or equal")
elif c>30:
  print("Greater")
else:
  print("Default!")


Tutorial 5:
For video tutorial CLICK_HERE

#Loop in Python....

#For(int i =0; i<=10;i++)
#{
#    print(i)
#}
for a in range(1,11,1):
  print(a)
_ _ _ _ _ _ _ _ _ _ _ _ _
for a in range(2,11,2):
  print(a)
_ _ _ _ _ _ _ _ _ _ _ _ _
for a in range(1,11,2):
  print(a)
_ _ _ _ _ _ _ _ _ _ _ _ _
for a in range(1,11,2):
  print(a)
  for b in range(11,20,2):
    print(b)
_ _ _ _ _ _ _ _ _ _ _ _ _
z=0;
while z<=10:
  print(z)
  z=z+1;
_ _ _ _ _ _ _ _ _ _ _ _ _
z=0;
while z<=10:
  print(z)
  zz=0;
_ _ _ _ _ _ _ _ _ _ _ _ _
while zz<=10:
  print(zz)
  zz=zz+1;
  z=z+1;


#continue, break, pass
for i in range(1,11):

  if i==1:
    pass
  if i==5:
    continue
  if i==8:
    break
  print ("This is iteration no. ", i)



Tutorial 6:
For video tutorial  CLICK_HERE

#Operator in Python

#Arithematic Operation in Python
a=11;b=3;
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a**b)
print(a//b)
_ _ _ _ _ _ _ _ _ _ _ _ _
#Comparision Operation in Python
a=11;b=11;
print(a>b)
print(a<b)
print(a>=b)
print(a<=b)
print(a!=b)
print(a==b)
_ _ _ _ _ _ _ _ _ _ _ _ _
#Assignment Operators (=, +=, -=, *= .....)
a=2;
print(a)
a*=2; # a= a*2
print(a)
_ _ _ _ _ _ _ _ _ _ _ _ _



Tutorial : 07
For video tutorial CLICK_HERE

#Bitwise Operator (&, |, ^, ~, >>, <<)
a=2;
b=3;
print(a & b)
print( a | b)
print(a ^ b)
print(~a)
print (a >> b)
print (a << b)
_ _ _ _ _ _ _ _ _ _ _ _ _
# Logical Operator in Python ( and, or, not)
a = True;
b = True;
print( a and b)
print( a or b)
print( not b)
a=2
b=5
c=50
if ( (a>=5 and b>=10) or (c<=49) ):
  print("True")
else:
  print("Not ture")
_ _ _ _ _ _ _ _ _ _ _ _ _
# Membership Operator (in, not in)
Var=['a', 23, 25.12, "Fahad"]
print(100 not in Var)
_ _ _ _ _ _ _ _ _ _ _ _ _

#identity operator (is, is not)
x=5;
y=5;
z=4;
print( x is y)
print( x is not y)
print( x is z)
_ _ _ _ _ _ _ _ _ _ _ _ _


Tutorial 8:
For video tutorial  CLICK_HERE

File handling:
File handling is an important part of any web application/Development .
Python has several functions for creating, reading, updating, and deleting files.

File Handling
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
also, r+ for both reading and writing ...
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

#To check the working directory
ls


# a=> append file
f = open("FahadFile1.txt", "a")
f.write("Now the file has more content67767!\n")
f.write("Now the file has more content234!\n")
f.write("Now the file has more contentqwer!\n")
f.write("Now the file has more contentasdf!")
f.close()

#open and read the file after the appending:
f = open("FahadFile2.txt", "r")
print(f.read())

#Write on the file
f = open("FahadFile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()


#open and read the file after the appending:
f = open("FahadFile3.txt", "r")
print(f.read())

f = open("NewFile.txt", "x")

f = open("NewFile.txt", "x")

f = open("NewFile.txt", "w")


#for read a file
f = open("FahadFile3.txt", "r")
print(f.read())


f = open("FahadFile3.txt", "r")
print(f.read(5))

f = open("FahadFile2.txt", "r")
print(f.readline())


f = open("FahadFile2.txt", "r")
print(f.readline())
print(f.readline())


f = open("FahadFile2.txt", "r")
for x in f:
    print(x)


#it is good practice to close the file
f = open("FahadFile3.txt", "r")
print(f.readline())
f.close()


#to Delete the file
import os
os.remove("FahadFile2.txt")


#to delete the file using if else...
import os
if os.path.exists("FahadFile2.txt"):
    os.remove("demofile.txt")
else:
    print("The file does not exist")


#To delete folder
import os
os.rmdir("myfolder")


Tutorial 9:
For video tutorial  CLICK_HERE

def printfunction(a):
    a=a*2
    print(a)

printfunction(3)

def returnfunction(b):
    b=b*2
    return b;

printfunction(3)

p= printfunction(3)

r= returnfunction(3)

p

r

type(p)

type(r)
_ _ _ _ _ _ _ _ _ _ _ _ _


Tutorial 10:
For video tutorial  CLICK_HERE

A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.

x = lambda a : a + 10
print(x(5))
_ _ _ _ _ _ _ _ _ _ _ _ _
x = lambda a, b : a * b
print(x(5, 6))
_ _ _ _ _ _ _ _ _ _ _ _ _
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
_ _ _ _ _ _ _ _ _ _ _ _ _
def myfunc(n):
  return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
_ _ _ _ _ _ _ _ _ _ _ _ _
def myfunc(n):
  return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
_ _ _ _ _ _ _ _ _ _ _ _ _
def myfunc(n):
  return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
_ _ _ _ _ _ _ _ _ _ _ _ _

Tutorial 11:
For video tutorial CLICK_HERE

OOP: Object oriented programming:

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects",
which can contain data, in the form of fields (often known as attributes), and code, in the
 form of procedures (often known as methods). A feature of objects is an object's procedures
 that can access and often modify the data fields of the object with which they are associated
(objects have a notion of "this" or "self"). In OOP, computer programs are designed by making
 them out of objects that interact with one anothe

*) Procedure base (top down approach)
*) OOP base       (bottom up approach)
Pillars of OOP:

1) Encapsulation : Define the boundary of code
2) Inheritance   : The implementation and state of each object are privately held inside a defined
 boundary, or class.
3) Polymorphism  : means many form, use a function by different forms
4) Abstraction   : Show only revelent data and hide irrevelent data;

5) Exception Handling.... : avoid to hald the program

Related Term used in OOP:

Class - A user-defined prototype for an object that defines a set of attributes that characterize
 any object of the class. The attributes are data members (class variables and instance variables)
 and methods, accessed via dot notation.

Class variable - A variable that is shared by all instances of a class. Class variables are
 defined within a class but outside any of the class's methods. Class variables are not used
 as frequently as instance variables are.

Data member - A class variable or instance variable that holds data associated with a class
and its objects.

Instance - An individual object of a certain class. An object obj that belongs to a class Circle,
 for example, is an instance of the class Circle.

Object - A unique instance of a data structure that's defined by its class. An object comprises
 both data members (class variables and instance variables) and methods.


Tutorial 12:
For video tutorial  CLICK_HERE

'''
public void abc()
{
int a=2;b=3;
cw(a+b)
}
'''
def Sum():
  a=1;b=3;
  print(a+b)
_ _ _ _ _ _ _ _ _ _ _ _ _
'''
public int abc()
{
return c;
}
'''
def sumpara(a, b):
  return (a+b);
_ _ _ _ _ _ _ _ _ _ _ _ _

sumpara(5,5)

_ _ _ _ _ _ _ _ _ _ _ _ _
'''
public void first()
{
cw("First");
public void Second()
{
cw("Second");
}
Second()

}
_ _ _ _ _ _ _ _ _ _ _ _ _
'''
def first():
  print("first")
  def second():
    print("second")
  second()

first()
_ _ _ _ _ _ _ _ _ _ _ _ _

Tutorial 13:
For video tutorial  CLICK_HERE

'''
int a;
public void abc()
{
this.a =12;
}

'''
class Python:
  def sum(self, a, b):
    #this
    print(a+b)
'''
Python obj = new Python();
obj.sum();
'''
#Creating Object
# Python obj = new Python();
obj=Python()
_ _ _ _ _ _ _ _ _ _ _ _ _


#First Method to call function
Python.sum(obj,1,2)

_ _ _ _ _ _ _ _ _ _ _ _ _

#Second Method to call function

#obj.Sum();
obj.sum(1,4)


Tutorial 14:
For video tutorial CLICK_HERE

'''
public Python(int a, int b)
{
this.a =a;
this.b=b;
}
sum()
{
cw(a+b)
}
Python obj = new Python(2,3);
obj.sum();
'''
#Constructor in Python, with function

class Car():
    # instance attributes
 
    def __init__(self, model, color):
        #instance Variable
        self.model = model
        self.color = color
     # instance Method
    def carmodel(self):
        print("started",self.model)

    def carcolor(self):
        print("stopped",self.color)

#obj = Python();
objj= Car(1993,"Pink")

_ _ _ _ _ _ _ _ _ _ _ _ _

objj.carcolor();
objj.carmodel();


Tutorial 15:
For video tutorial  CLICK_HERE

#local instance ....

class CarAuto():
    wheel=4;
    def __init__(self):
        self.model = "B-147";

Ca1= CarAuto()
Ca2= CarAuto()

Ca1.model="A-147"
print(Ca1.model)
print(Ca2.model)

_ _ _ _ _ _ _ _ _ _ _ _ _


#Global instance ....
class CarAuto():
    wheel=4;
    def __init__(self):
        self.model = "B-147";

Ca1= CarAuto()
Ca2= CarAuto()

CarAuto.wheel="Global"
print(Ca1.model, Ca1.wheel)
print(Ca2.model,Ca2.wheel)

CarAuto.wheel=12;

print(Ca1.model, Ca1.wheel)
print(Ca2.model,Ca2.wheel)


Tutorial 16:
For video tutorial  CLICK_HERE

#inheritance ....(Transfer featuers to sibling from parents)

#single level
#multi level
#multiple level


class Apple:
  def Sweet(self):
    print("Apple is sweet")
  def Sour(self):
    print("Apple is sour not")
#obj = Apple()
#obj.Sweet()
class Orange(Apple):
  def Sweet1(self):
    print("Apple is sweet of Orange Class")
  def Sour1(self):
    print("Apple is sour not")
obj1 = Orange()
obj1.Sweet()
 
_ _ _ _ _ _ _ _ _ _ _ _ _

#Multi level
class Apple:
  def Sweet(self):
    print("Apple is sweet")
  def Sour(self):
    print("Apple is sour not")
#obj = Apple()
#obj.Sweet()
class Orange(Apple):
  def Sweet1(self):
    print("Apple is sweet of Orange Class")
  def Sour1(self):
    print("Apple is sour not")
#obj1 = Orange()
#obj1.Sweet()
class Lemon(Orange):
  def abc(self):
    print("Defalut");
obj2=Lemon()
obj2.Sweet()

_ _ _ _ _ _ _ _ _ _ _ _ _


#Multiple level
class Apple:
  def Sweet(self):
    print("Apple is sweet")
  def Sour(self):
    print("Apple is sour not")
#obj = Apple()
#obj.Sweet()
class Orange():
  def Sweet1(self):
    print("Apple is sweet of Orange Class")
  def Sour1(self):
    print("Apple is sour not")
#obj1 = Orange()
#obj1.Sweet()
class Lemon(Apple,Orange):
  def abc(self):
    print("Defalut");
obj2=Lemon()
obj2.Sweet()


Tutorial 17:
For video tutorial CLICK_HERE

#Polymorphism (means many Form).... Different Method of implementation of code
# (duck typing, method overload, method override)
class Dignoise():
  def run(self):
    print("Your BP is 80/120");
class Hospital():
  def run(self):
    print("Your BP is 80/120");
class Doctor:
  def treatment(self, BP):
    BP.run();
BP=Hospital()
obj= Doctor();
obj.treatment(BP)



Tutorial 18:
For video tutorial  CLICK_HERE

#Polymorphism (means many Form).... Different Method of implementation of code
# (duck typing,Operator Overload, method overload, method override)
#Operator Overload
#print(  5   +   10);
#a="Fahad";
#print(len(a))
class School:
  def __init__(self, fee):
    self.fee=fee;
 
  def __add__(self,other):
    return self.fee+ other.fee;
A=School(300);
B=School(400);
print(A +B);

a =12
b=20;
int.__add__(a,b)

#method overload
''' public void abc(int a)
  {
      print("",a)
  }
public void abc(int a, int b)
{
    printf("a,b")
}
 '''
class ABC:
  def add(self, a, b=None,c=None):
    if c!=None:
      print(a+b+c);
    else:
      print(a+b);
   
obj=ABC()
obj.add(10,20,10)

#method override
class A:
  def first(self):
    print("This is First Value of A")
class B(A):
  def first(self):
    print("This is First Value of B")
obj1=B()
obj1.first()


Tutorial 19:
For video tutorial  CLICK_HERE

#Abstraction: one of the OOP pillar,
#Show only revelent data and hide irrevelent data

from abc import ABC, abstractmethod
class Vegetable(ABC):
  @abstractmethod
  def Tomoto(self):
    pass
  @abstractmethod
  def cucumber(self):
    pass

#obj= Vegetable()
class itscolor(Vegetable):
  def __init__(self, color):
    self.color=color
 
  def Tomoto(self):
    return self.color

  def cucumber(self):
    return self.color

obj =itscolor("Red")
print(obj.Tomoto())



Tutorial 20:
For video tutorial CLICK_HERE

#Try Catch, Try Except finally
try:
  print(1/1);
except IOError:
  print("No Error");
except IOError:
  print("No Error");
except ValueError:
  print("No Error");
except EOFError:
  print("No Error");
except ZeroDivisionError:
  print("ZeroDivisionError")
except:
  print("Default:")
finally:
  print("in both cases it will execute")




3 comments:

Fell free to write your query in comment. Your Comments will be fully encouraged.