Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Coding Samples 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

PYTHON SAMPLE PROGRAMS

Example 1 : Write a Python program to get system command output.

import subprocess
# file and directory listing
returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
print("dir command to list file and directory")
print(returned_text)

Output:

6d2c5fa0-5ef2-11e6-8ff4-d5b1b3f27f4d ead74d50-beb7-11e6-933b-47978
84c7124
6d33f7a0-242d-11e7-820d-03f0e944369f eae8e560-767d-11e6-a3fc-0fb5e
bee9d44

6d36f6e0-8616-11e6-affa-0dc8296ec630 eafedbe0-ed01-11e6-a189-7956f
7e10ca1
6d462c20-758e-11e6-a935-b7db6295ac51 eb190a30-bae6-11e6-a2d1-75a31
a870ce2

------
7feae620-bece-11e6-ad81-456cada677e8 sss.dat\n
7fef9710-7fc2-11e6-97c3-c153b6e0fe23 temp.txt
7ff17310-9c22-11e6-9e03-95cb39e2a59d test.txt
801a70f0-4414-11e6-a0ac-5bb3315a1c3b

Example 2 : Write a Python program to extract the filename from a given path.

import os
print()
print(os.path.basename('/users/system1/student1/homework-1.py'))
print()
Output:

homework-1.py

Example 3 : Write a Python program to find the first duplicate element in a given array of
integers. Return -1 If there are no such elements.

def find_first_duplicate(nums):
num_set = set()
no_duplicate = -1

for i in range(len(nums)):

if nums[i] in num_set:
return nums[i]
else:
num_set.add(nums[i])

return no_duplicate

print(find_first_duplicate([1, 2, 3, 4, 4, 5]))
print(find_first_duplicate([1, 2, 3, 4]))
print(find_first_duplicate([1, 1, 2, 3, 3, 2, 2]))

Output:

4
-1
1
Example 4 : Write a Python program to find those numbers which are divisible by 7 and multiple
of 5, between 1500 and 2700 (both included).

nl=[]

for x in range(1500, 2701):


if (x%7==0) and (x%5==0):
nl.append(str(x))

print (','.join(nl))

Output:

1505,1540,1575,1610,1645,1680,1715,1750,1785,1820,1855,1890,1925,1960,1995,2030,
2065,2100,2135,2170,2205,2240,
2275,2310,2345,2380,2415,2450,2485,2520,2555,2590,2625,2660,2695

Example 5 : Write a Python program to convert temperatures to and from celsius, fahrenheit.

Python: Centigrade and Fahrenheit Temperatures :

The centigrade scale, which is also called the Celsius scale, was developed by Swedish astronomer
Andres Celsius. In the centigrade scale, water freezes at 0 degrees and boils at 100 degrees. The
centigrade to Fahrenheit conversion formula is:

Fahrenheit and centigrade are two temperature scales in use today. The Fahrenheit scale was
developed by the German physicist Daniel Gabriel Fahrenheit . In the Fahrenheit scale, water freezes
at 32 degrees and boils at 212 degrees.

C = (5/9) * (F - 32)

temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) :
")
degree = int(temp[:-1])
i_convention = temp[-1]
if i_convention.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius"
else:
print("Input proper convention.")
quit()

print("The temperature in", o_convention, "is", result, "degrees.")

Output:

Input the temperature you like to convert? (e.g., 45F, 102C etc.) : 104f
The temperature in Celsius is 40 degrees.

Example 6 : Write a Python program that prints each item and its corresponding type from the
following list.

Sample List : datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V',
"section":'A'}]

datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
for item in datalist:
print ("Type of ",item, " is ", type(item))

Output:

Type of 1452 is <class 'int'>


Type of 11.23 is <class 'float'>
Type of (1+2j) is <class 'complex'>
Type of True is <class 'bool'>
Type of w3resource is <class 'str'>
Type of (0, -1) is <class 'tuple'>
Type of [5, 12] is <class 'list'>
Type of {'class': 'V', 'section': 'A'} is < class 'dict'>

Example 7 : Print this pattern

Sample Output:

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

rows = 9
for i in range(1, rows):
for i in range(0, i, 1):
print(format(2 ** i, "4d"), end=' ')
for i in range(-1 + i, -1, -1):
print(format(2 ** i, "4d"), end=' ')
print("")

Output:

1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

Example 8 : Display 1 to 10 number in Pattern

Sample Output:

1
2 3 4
5 6 7 8 9

currentNumber = 1
stop = 2
rows = 3 # Rows you want in your pattern

for i in range(rows):
for column in range(1, stop):
print(currentNumber, end=' ')
currentNumber += 1
print("")
stop += 2

Output:

1
2 3 4
5 6 7 8 9

Example 9 : Even number pattern


Sample Output:

10
10 8
10 8 6
10 8 6 4
10 8 6 4 2

rows = 5
LastEvenNumber = 2 * rows
evenNumber = LastEvenNumber
for i in range(1, rows+1):
evenNumber = LastEvenNumber
for j in range(i):
print(evenNumber, end=' ')
evenNumber -= 2
print("\r")

Output:

10
10 8
10 8 6
10 8 6 4
10 8 6 4 2

Example 10 : Python Program to Count the Number of Vowels Present in a String using Sets .

s=raw_input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)

Output:

Case 1:
Enter string:Hello world

Count of the vowels is:


3

Case 2:
Enter string:Python Program

Count of the vowels is:


3

Example 11 : Python Program to Check Common Letters in Two Input Strings .

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")
a=list(set(s1)&set(s2))

print("The common letters are:")


for i in a:
print(i)

Output:

Case 1:
Enter first string:Hello

Enter second string:How are you

The common letters are:


H
e
o
Case 2:
Enter first string:Test string

Enter second string:checking

The common letters are:


i
e
g
n

Example 12 : Write a Python program to create a SQLite database and connect with the database
and print the version of the SQLite database.

import sqlite3
try:
sqlite_Connection = sqlite3.connect('temp.db')
conn = sqlite_Connection.cursor()
print("\nDatabase created and connected to SQLite.")
sqlite_select_Query = "select sqlite_version();"
conn.execute(sqlite_select_Query)

record = conn.fetchall()
print("\nSQLite Database Version is: ", record)
conn.close()

except sqlite3.Error as error:


print("\nError while connecting to sqlite", error)
finally:
if (sqlite_Connection):
sqlite_Connection.close()

print("\nThe SQLite connection is closed.")

Output:

Database created and connected to SQLite.


SQLite Database Version is: [('3.11.0',)]

The SQLite connection is closed.

Example 13 : Write a Python program to create a SQLite database connection to a database that
resides in the memory.

import sqlite3
try:
sqlite_Connection = sqlite3.connect('temp.db')
conn = sqlite3.connect(':memory:')
print("\nMemory database created and connected to SQLite.")
sqlite_select_Query = "select sqlite_version();"
conn.execute(sqlite_select_Query)

print("\nSQLite Database Version is: ", sqlite3.version)


conn.close()

except sqlite3.Error as error:


print("\nError while connecting to sqlite", error)
finally:
if (sqlite_Connection):
sqlite_Connection.close()

print("\nThe SQLite connection is closed.")

Output:

Memory database created and connected to SQLite.

SQLite Database Version is: 2.6.0

The SQLite connection is closed.

Example 4 : Write a Python program to list the tables of given SQLite database file.
import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)

def sql_table(conn):
cursorObj = conn.cursor()
# Create two tables
cursorObj.execute("CREATE TABLE agent_master(agent_code
char(6),agent_name char(40),working_area char(35),commission
decimal(10,2),phone_no char(15) NULL);")
cursorObj.execute("CREATE TABLE temp_agent_master(agent_code
char(6),agent_name char(40),working_area char(35),commission
decimal(10,2),phone_no char(15) NULL);")
print("List of tables:")
cursorObj.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursorObj.fetchall())
conn.commit()

sqllite_conn = sql_connection()
sql_table(sqllite_conn)

if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

List of tables:

[('agent_master',), ('temp_agent_master',)]

The SQLite connection is closed.


Example 14 : Write a Python program to create a table and insert some records in that table.
Finally selects all rows from the table and display the records.

import sqlite3

from sqlite3 import Error

def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)

def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name char(30),
city char(35), commission decimal(7,2));")
# Insert records
cursorObj.executescript("""

INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);


INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
""")
conn.commit()

cursorObj.execute("SELECT * FROM salesman")


rows = cursorObj.fetchall()
print("Agent details:")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

Agent details:

(5001, 'James Hoog', 'New York', 0.15)


(5002, 'Nail Knite', 'Paris', 0.25)
(5003, 'Pit Alex', 'London', 0.15)
(5004, 'Mc Lyon', 'Paris', 0.35)
(5005, 'Paul Adam', 'Rome', 0.45)

The SQLite connection is closed.

Example 15 : Write a Python program to insert a list of records into a given SQLite table.

import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)

def sql_table(conn, rows):


cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name
char(30), city char(35), commission decimal(7,2));")
sqlite_insert_query = """INSERT INTO salesman
(salesman_id, name,
city, commission)
VALUES (?, ?, ?, ?);"""
cursorObj.executemany(sqlite_insert_query, rows)

conn.commit()

print("Number of records after inserting rows:")


cursor = cursorObj.execute('select * from salesman;')
print(len(cursor.fetchall()))

# Insert records
rows = [(5001,'James Hoog', 'New York', 0.15),
(5002,'Nail Knite', 'Paris', 0.25),
(5003,'Pit Alex', 'London', 0.15),
(5004,'Mc Lyon', 'Paris', 0.35),
(5005,'Paul Adam', 'Rome', 0.45)]

sqllite_conn = sql_connection()
sql_table(sqllite_conn, rows)

if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

Number of records after inserting rows :

The SQLite connection is closed.

Example 16 : Write a Python program to insert values to a table from user input.

import sqlite3
conn = sqlite3 . connect ( 'mydatabase.db' )
cursor = conn.cursor ()
#create the salesman table
cursor.execute("CREATE TABLE salesman(salesman_id n(5), name char(30), city
char(35), commission decimal(7,2));")
s_id = input('Salesman ID:')
s_name = input('Name:')
s_city = input('City:')
s_commision = input('Commission:')
cursor.execute("""

INSERT INTO salesman(salesman_id, name, city, commission)


VALUES (?,?,?,?)
""", (s_id, s_name, s_city, s_commision))
conn.commit ()
print ( 'Data entered successfully.' )
conn . close ()
if (conn):
conn.close()

print("\nThe SQLite connection is closed.")

Output:

Salesman ID: 5
Name: Jhon Edin

City: New York

Commission: 5
Data entered successfully.

The SQLite connection is closed.

Example 17 : Write a Python program to count the number of rows of a given SQLite table.

import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)

def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name
char(30), city char(35), commission decimal(7,2));")
print("Number of records before inserting rows:")
cursor = cursorObj.execute('select * from salesman;')
print(len(cursor.fetchall()))
# Insert records
cursorObj.executescript("""

INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);


INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
""")
conn.commit()

print("\nNumber of records after inserting rows:")


cursor = cursorObj.execute('select * from salesman;')
print(len(cursor.fetchall()))

sqllite_conn = sql_connection()
sql_table(sqllite_conn)

if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

Number of records before inserting rows :

0
Number of records after inserting rows :

The SQLite connection is closed.

Example 18 : Write a Python program to update a specific column value of a given table and
select all rows before and after updating the said table.

import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name
char(30), city char(35), commission decimal(7,2));")
# Insert records
cursorObj.executescript("""

INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);


INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
""")
cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("Agent details:")
for row in rows:
print(row)
print("\nUpdate commission .15 to .45 where id is 5003:")
sql_update_query = """Update salesman set commission = .45 where
salesman_id = 5003"""
cursorObj.execute(sql_update_query)

conn.commit()

print("Record Updated successfully ")


cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("\nAfter updating Agent details:")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)

if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

Agent details:

(5001, 'James Hoog', 'New York', 0.15)


(5002, 'Nail Knite', 'Paris', 0.25)
(5003, 'Pit Alex', 'London', 0.15)
(5004, 'Mc Lyon', 'Paris', 0.35)
(5005, 'Paul Adam', 'Rome', 0.45)

Update commission .15 to .45 where id is 5003:


Record Updated successfully

After updating Agent details:

(5001, 'James Hoog', 'New York', 0.15)


(5002, 'Nail Knite', 'Paris', 0.25)
(5003, 'Pit Alex', 'London', 0.45)
(5004, 'Mc Lyon', 'Paris', 0.35)
(5005, 'Paul Adam', 'Rome', 0.45)

The SQLite connection is closed.


Example 19 : Write a Python program to update all the values of a specific column of a given
SQLite table.

import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE
TABLE salesman(salesman_id n(5), name
char(30), city char(35), commission decimal(7,2));")
# Insert records
cursorObj.executescript("""

INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);


INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
""")
cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("Agent details:")
for row in rows:
print(row)
print("\nUpdate all commision to .55:")
sql_update_query = """Update salesman set commission = .55"""
cursorObj.execute(sql_update_query)

conn.commit()

print("Record Updated successfully ")


cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("\nAfter updating Agent details:")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)

if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

Agent details:

(5001, 'James Hoog', 'New York', 0.15)


(5002, 'Nail Knite', 'Paris', 0.25)
(5003, 'Pit Alex', 'London', 0.15)
(5004, 'Mc Lyon', 'Paris', 0.35)
(5005, 'Paul Adam', 'Rome', 0.45)

Update all commision to .55:


Record Updated successfully

After updating Agent details:

(5001, 'James Hoog', 'New York', 0.55)


(5002, 'Nail Knite', 'Paris', 0.55)
(5003, 'Pit Alex', 'London', 0.55)
(5004, 'Mc Lyon', 'Paris', 0.55)
(5005, 'Paul Adam', 'Rome', 0.55)

The SQLite connection is closed.

Example 20 : Write a Python program to delete a specific row from a given SQLite table.

import sqlite3
from sqlite3 import Error
def sql_connection():
try:
conn = sqlite3.connect('mydatabase.db')
return conn
except Error:
print(Error)
def sql_table(conn):
cursorObj = conn.cursor()
# Create the table
cursorObj.execute("CREATE TABLE salesman(salesman_id n(5), name char(30),
city char(35), commission decimal(7,2));")
# Insert records
cursorObj.executescript("""

INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);


INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
""")
cursorObj.execute("SELECT * FROM salesman")
rows = cursorObj.fetchall()
print("Agent details:")
for row in rows:
print(row)
print("\nDelete Salesman of ID 5003:")
s_id = 5003
cursorObj.execute("""

DELETE FROM salesman


WHERE salesman_id = ?
""", (s_id,))
conn.commit()

cursorObj.execute("SELECT * FROM salesman")


rows = cursorObj.fetchall()
print("\nAfter updating Agent details:")
for row in rows:
print(row)
sqllite_conn = sql_connection()
sql_table(sqllite_conn)

if (sqllite_conn):
sqllite_conn.close()

print("\nThe SQLite connection is closed.")

Output:

Agent details:

(5001, 'James Hoog', 'New York', 0.15)


(5002, 'Nail Knite', 'Paris', 0.25)
(5003, 'Pit Alex', 'London', 0.15)
(5004, 'Mc Lyon', 'Paris', 0.35)
(5005, 'Paul Adam', 'Rome', 0.45)

Delete Salesman of ID 5003:

After updating Agent details:

(5001, 'James Hoog', 'New York', 0.15)


(5002, 'Nail Knite', 'Paris', 0.25)
(5004, 'Mc Lyon', 'Paris', 0.35)
(5005, 'Paul Adam', 'Rome', 0.45)

The SQLite connection is closed.

Example 21 : Write a Python program to create a backup of a SQLite database.

import sqlite3
import io
conn = sqlite3.connect('mydatabase.db')
with io.open('clientes_dump.sql', 'w') as f:
for linha in conn.iterdump():
f.write('%s\n' % linha)
print('Backup performed successfully.')
print('Saved as mydatabase_dump.sql')
conn.close()

Output:

Backup performed successfully.

Saved as mydatabase_dump.sql

Example 22 : Write a Python program to find the class wise roll number from a tuple-of-tuples.

from collections import defaultdict


classes = (
('V', 1),
('VI', 1),
('V', 2),
('VI', 2),
('VI', 3),
('VII', 1),
)

class_rollno = defaultdict(list)

for class_name, roll_id in classes:


class_rollno[class_name].append(roll_id)

print(class_rollno)

Output:

defaultdict(<class 'list'>, {'VII': [1], 'VI': [1, 2, 3], 'V': [1, 2]})
Example 23 : Write a Python program to create an instance of an OrderedDict using a given
dictionary. Sort the dictionary during the creation and print the members of the dictionary in
reverse order.

from collections import OrderedDict


dict = {'Afghanistan': 93, 'Albania': 355, 'Algeria': 213, 'Andorra': 376,
'Angola': 244}
new_dict = OrderedDict(dict.items())
for key in new_dict:
print (key, new_dict[key])

print("\nIn reverse order:")


for key in reversed(new_dict):
print (key, new_dict[key])

Output:

Angola 244
Albania 355
Andorra 376
Algeria 213
Afghanistan 93

In reverse order:

Afghanistan 93
Algeria 213
Andorra 376
Albania 355
Angola 244
Example 24 : Write a Python program to get the name of the operating system (Platform
independent), information of current operating system, current working directory, print files and
directories in the current directory and raises error in the case of invalid or inaccessible file
names and paths.

import os
print("Operating System:",os.name)
print("\nInformation of current operating system: ",os.uname())
print("\nCurrent Working Directory: ",os.getcwd())
print("\nList of files and directories in the current directory:")
print(os.listdir('.'))
print("\nTest if a specified file exis or not:")
try:
filename = 'abc.txt'
f = open(filename, 'r')
text = f.read()
f.close()

except IOError:
print('Not accessed or problem in reading: ' + filename)

Output:

Operating System: posix

Information of current operating system : posix.uname_result(sysname='Linux',


nodename='b0e45c20d4ca', release='4.4.0-169-generic', version='#198-Ubuntu SMP Tue
Nov 12 10:38:00 UTC 2019', machine='x86_64')

Current Working Directory: /tmp/sessions/7ae3772408a46b98

List of files and directories in the current directory:


['main.py']

Test if a specified file exis or not:


Not accessed or problem in reading: abc.txt

You might also like