Skip to main content

Python Tutorial

https://docs.python.org

Install Python

How to verify installation

  • Go to command prompt and type
python --version

Write first python file

C:\Users\toman>>>python

print("hello world")
hello world #output

Python .py files

  • Open notepad.exe
  • save the file with .py extention
  • To execute type command
python <filename>>>.py

Python Variables

  • No need to explicitly declare the variables before using it.
  • For example, a variable "x" can be created and assigned when needed.
x = 5
print(x)
5 #output

Python Numbers

x = 15
print(type(x))
<class 'int'> #output

y = 1.15
print(type(y))
<class 'float'> #output

Python Strings

a = "hello World"
print(a)

b = "3rd Row is here"
print(type(b))

String Methods

a = "sudhir singh"
a.upper()
print(a)
SUDHIR SINGH #output

a.capitalize()
print(a)
Sudhir Singh #output

a.split(" ")
['sudhir', 'singh']
print(a.split(" ")[0])

The complete list of string:

Python Casting Data Types

#String to Integer
a = "3"
int(a)
print(a)

#Integer to String
a = 3
str(a)
print (type(a))

Python Operators

  • same as other language
a = 5 #assignment operator
b = 30
a + b #addition
a * b #multiplication

Python Assignment Operators

x = 1
x = x + 1
x += 1 #increment by 1
x *= x #self multiplications

Python Comparison Operators

a = 5
b = 10
a == b #equal to
a == 5 #equal to
a != b #not equal
a > 4 #greate than
b <= 5 #less than equal to

Python collections

myList = ["read", "green", "blue"] #defining a list
print (myList) #to print list
print (myList[1]) #to get one value from #1 position

Python List Constructor

myList = ["read", "green", "blue"]
print (type(myList)) #to print type of list
awesomeList = list(("patrick, "logan","brent")) #another way to define a list

List Append Method

myList = ["Red", "Blue", "Green"]
print(myList[1]) #prints Blue
print(myList) #prints ["Red", "Blue", "Green"]
myList.append("Purple") #To append another list to myList
print(myList) #prints ["Red", "Blue", "Green", "Purple"]

More List Methods

myList = ["Red", "Blue", "Green"]
len(myList) #prints lenght of a list
myList.reverse() #to reverse the order in a list
myList.clear() #to delete all the element of a list
myList.remove(y) #to removes the first item from the list whose value is y.

Complete listting of Python List methods https://docs.python.org/2/tutorial/datastructures.html

Python Tuple Data Tpye

  • Tuples are readonly
myTuple = ("red", "green", "blue") #to define tuple
pritn(type(myTuple)) #To find the type of element
print(len(myTuple)) #To find length of a tuple

Differences between List Type and Tuple Type

  • List is changable
  • Tuple is readonly, can not be changed
  • List takes more memory
  • Tuple is secured
myList = ["Red", "Blue", "Green"] #defining List
myTuple = ("Red", "Blue", "Green") #defining Tuple
print("List Methods") #Prints List methods
print(dir(myList)) # prints all th methods of myList

print("Tuple Methods") #Prints List methods
print(dir(myTuple)) # prints all the methods of myList

Python Set Data Type

mySet = {"Red", "Green", "Blue"} #Curly braces is used for defining a Set
print(dir(mySet)) #prints list of all the methods in a Set
mySet.add("Purple") #to add element in to a Set
len(mySet) #To find lenght of a Set
remove("Green") #to remove the an element
mySet.discard("Green") #no error is returned in case of element does not exist

Set Methods

A = {1, 2, 3, 4}
B = {3, 4, 5, 6, 7}
#To merge two lists
A.union(B) #print {1, 2, 3, 4, 5, 6, 7}

#To sorting out common elements
A.intersection(B) #prints {3, 4}

#To sorting out different elements
A.differnce(B) #prints {1, 2}

Python Dictionary Data Type

  • it is a key/value pair like a map
newD = {100:"Patrick", 200:"Joe", 300:"Martin"} #to define dictionary
print(newD) #prints the newD dictionary
newD[200] #prints joe
newD[400] = "Logan" #add a new data into a dictionary
len(newD) #to find the lenght of the dictionary
newD[100] = "leaf" #to update the attribute value

Working with Python Shell and IDLE

  • How to use IDLE to write python programme.
- Open IDLE from "Start" menu by searching Python
- In IDLE click on "File" menu and click on "New File"
- A new windows is opened
- Write the py code and Save the file to a directory
- To execute the file, click on "Run" and then click "Run module" or press "F5" button

Python Whitespace

  • Deals with whitespaces
  • Whitespacing matters in python
  • so always watch for whitespacing
a = 10
b = 20 #exception while running these two lines

Python Comments

  • "#" is used for single line comment
  • """ (three double quote) is used for mulitline comments
""" below are just for comment purpose
mulitiline"""
a = 10
b = 20
print (a+b) #this prints the results

Understanding and importing Python Modules

  • Python library are called modules
  • import the module to your project and use the functions of that module
import math #to import the modules

math.sqrt(9)
3.0 #prints the squre of 9

dir() Python Method

  • to find what is inside the module
  • what the module contains
dir(math) #to find the details of module and its functions

help() Python Method

  • to get more information of function within a module
help (math.pow) #return the details of pow method
help (math.sin)
help (math.reminder)

Mehtod Alias

  • Modules another name is called alias
import math as m
print(m.sqrt(6)) #m is alias of math module
import calendar as cal
print(cal.month(2018, 8))

Python Program Flow

if conditions

a = 10
b = 15
if a > b: # indendation is important as well colon is used to separate the conditions from statement
print("A is > B")

elif condition

a = 10
b = 15
if a > b:
print("A is > B")
elif a < B: # else if statement
print("A is < B")

if... else condition

a = 15
b = 15
if a > b:
print("A is > B")
elif a < B: # else if statement
print("A is < B")
else: # else statement
print("A is = B")

OR condition in an if statement

x = "George"
if a == "Gerorge" or x = "Fred": # OR statement
print("permission granted")
else:
print("permission denied");

AND condition in an if statement

a = 10
if a > 5 and a< 15: #and statement
print("permission granted")
else:
print("permission denied");

While Loop

i = 1
while i <= 10: #loop the next statement
print (i)
i += 1

Break keyword

import random

i = 1
while i <= 10: #loop the next statement
newrand = random.randint(0, 20)
print (newrand)
if newrand == 6:
print("BREAK")
break #next statement will not execute and program breaks
i += 1

Continue keyword

import random

i = 1
while i <= 10: #loop the next statement
newrand = random.randint(0, 20)
print (newrand)
if newrand == 6:
print("Continue")
continue #next statement will not execute and program continues
i += 1

For loops

userNames = ["patrick", "joe", "brent", "Martin"]
for x in userNames:
print(x) #loops thru the userNames and prints names

Looping through String Values

a = "Hello"
for x in a:
print(x)

Range function in For loops

a = "Hello"
for x in rage(2, 10):
for x in range(10):
print(x) #print 0 to 9 as range starts from zero

For loop else statement

for x in range(0, 10):
print(x)
else:
print("for loop has been completed)

Project 1 - Python Magic 8 Ball

  • System showa a prompt and asks a question as user inputs and reply to that question randomly.
#import modules
import sys
import random

#variables
responses = ["it is certain", "you may rely on", "outlook is good", "most likely", "Without a doubt"]
questions = True

#loop
while questions:
qeus = input(" Please ask the magig 8 ball question ") #continue running and asing questions

if ques == "":
sys.exit()
else :
print(responses[random.randint(0, 4)]) #randomaly show answers

Working with Files in Python

Read a File

#open text file (data_sales.txt)
f = open("sales_data.txt", "r") #read mode of document
print(type(f)) #prints the type
print(f.read()) #to read all the file contents
print(f.readline()) #to read on line at a time
print(f.read(10)) #to read specific characters from a file

#use loop to read each line of the text file
for x in f:
print(x.strip()) # print the content by triming the spaces

Write to a file

#a = append
f = open("sales_data.txt", "a") #write by appending the content
#\n = new line
f.write("\nJan 2019 $2500") #add the content to a new line
f.close() #closing the connection of file and save the data

Create a text file

f = open("salex.txt", "x") #x = create

Project 2 - Read/Write a .csv file

Read a csv file

#import the csv module
import csv

#print(csv)
#print(dir(csv))

#open csv file
file = open("example.csv", "r")

#read the csv file
rdr = csv.reader(file, delimiter=",")

#output csv content
for row in rdr:
print(row)
print(row[3]) #to print a particular column
if row[3] == "IT":
print(row) #to filter the content from csv file

#close the csv connection
file.close()

Write to the csv file

#import the csv module
import csv

#open csv file
file = open("example.csv", "a") #append to an existing file

newRec = ["1005", "Patrick", "Marieau", "IT"]

#writh to the csv file
wrt = csv.writer(file)
wrt.writerow(newRec)

#close the csv connection
file.close()

Python OS Module

  • works more closly with your systems
import os

#print(dir(os))
#print(help(os.getcwd))

#To get current working directory
print(os.getcwd())

#To list directory files
print(os.listdir())

#To change the working directory
print(os.getcwd())
os.chdir("/users/desktop")
print(os.getcwd())
print(os.listdir())

#To create Directory
os.makedirs("Python-os")

#To check the files availability
os.path.isfile("Booking.docs") #prints true or false base of file availability
os.path.isdir("Python-os") #prints true

#To delete the file
os.remove("python.txt") #not results means file deleted successfully
os.removedirs("python")

Functions in Python

#to define the function
def hello_func(): # to define the function use "def" keyword
print("Hello world")

#To call the function
hello_func() #must use parenthesis

#Passing Arguments to a function
def hello_func(fName):
print("Hello " + fName)

hello_func("Sudhir")
hello_func("Ramesh")

def addNums(arg1, arg2):
print(arg1 + arg2)

#Using Named Arguments
hello_func(lastN ="sing", fName ="sudhir")

#Default Arguments

def hello_func(firstName = "user"):
print("Hello " + firstName)

hello_func() #no firstname passed, it will print "user"

#Variable Scope
total = 10

def add_nums(arg1, arg2):
total = arg1 + arg2
print(total) #prints 6

add_nums(3, 3)
print(total) #prints 10

#Returning from a function
def add_nums(arg1, arg2):
total = arg1 + arg2
return total

newTotal = add_nums(2, 2)
print(newTotal) #prints 4

OOPS in Python

Class in Python

class course:
pass # to pass the runtime error

#to create instance
c1 = course() # c1 instance created
c2 = sourse()

#properties in class
class course:
name = "Python"
student = ["Patric", "Joe", "Brent"]

c1 = course()
c1.name #retuns Python
cl.list #returns List

#Class __init__ function to initilize the class function
class course:
def __init__(self):
print("Hello course");

class course:
def __init__(self, name)
self.name = name
self.student = []

c1 = course("Python") #passing argument to class constructure
c1.name
c1.students

# Class self Argument
class course:
def __init__(self, name)
self.name = name
self.students = []

c1 = course("Python")
c2 = course("html")

c1.name
c2.name

#Python class Functions
class course:
def __init__(self, name)
self.name = name
self.students = []

def add_student(self, student):
self.student.append(student)

c1 = course("Python")
c1.add_students("Joe")
c1.add_students("Patric")
c1.students

c2 = course ("html")
c2.students

#class function return
def student_count(self):
return len(self.students) #Return from the class method

c1 = course("Python")
c1.student_count()
c1.add_students("joe")
c1.student_count()

#Private properties in Python
lass course:
def __init__(self, name)
self.__name = name #to define private properties use double underscore__
self.students = []

def add_student(self, student):
self.student.append(student)
self.__write_student(student) #To call private method

def get_course_name(self):
return self.__name # to access the private attribute use get method

def __write_student(self, student): #to define private method use __ as prefix
print("hello " + student)

# to delete an object
c1 = course("Python")
c2 = course("Html")
del c1 #to delete the object use del

Inheritance in Python

#user.py
class user:
def __init__(slef, fname, lname):
self.__fname = fname
self.__lname = lname

def get_full_name(self):
return self.__fname + " " + self.__lname

def user_login(self, username):
print("Access Denied")

def user_work(self):
print(self.__fname + " is working")

u1 = user("sudhir", "singh") #to call
u1.get_full_name() #to call

class superUser(user): #inheriting user class by superUser
def __init__(self, fname, lname, superlevel):
user.__init__(self, fname, lname) #calling the reference of super class

def super_user_work(self):
print("performing super work")

su1 = superUser("sudhir", "singh", 10) #to call
su1.get_full_name() #to call

Error handling in Python

Handling Exception (errors)

print(y) #name 'y' is not defined

#try statement
try:
print(y) #error happened
except:
print("error occurred") #control goes to catch in case of exception

print("continuing..")

#Catch specific error in Pyton
try:
print(y) #error happened
except NameError: #catching specific error
print("error occurred for y value") #control goes to catch in case of exception
except :
print("generic error")
print("continuing..")

Project 3 - Magic 8 Ball using Class

#import modules
import random, csv, sys

class magic8ball:
def __init__(self, name):
self.__name = name
self.__mQuestions = []
self.__start_game()

def __start_game(self):
mResponse = ["It is certian", "you may rely on it", "As I see it", "Well done", "go ahead","welcome"]
iQuestions = True
print ("Welcome " + self.__name)

while iQuestions:
mQues = input("Plase enter a question: ")
mRespond = mResponse[random.randint(0,5)]

if mQues == "":
print("Thank you for Playing")
self.__write_questions()
sys.exit()
else:
print(mRespond)
self.__mQuestions.append(mQues)

def __write_questions(self):
f = open("magic_question.csv", "a", newline="")
wrt = csv.writer(f)
for q in self.__mQuestions:
wrt.writerow([q])
f.close()

String Formating in Python

print("hello world")
print("Earth is the 3rd rock from the sun")
name = "sudhir"
age = 31
print ("hello " + name)
print("hello " + name + " you are : " + age + " years old")

#Creating formated string
print("Hello %s" %name) #use variable to insert at placeholder
age = 31
print("you are %d years old" %age) #use %d for integer and %s for string

print("Hello %s you are %d years old!" %(name, age)) #multiple variable in a string

user = ["Sudhir", "21", "IT"]
print("Hello %s you are %d years old and you are in ti %s dept" %(users[0], users[1], users[2])) #multiple varibale