Python Coding Samples 1
Python Coding Samples 1
Python Coding Samples 1
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=[]
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.
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()
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:
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
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
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
Case 2:
Enter string:Python Program
Output:
Case 1:
Enter first string:Hello
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()
Output:
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)
Output:
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()
Output:
List of tables:
[('agent_master',), ('temp_agent_master',)]
import sqlite3
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("""
Output:
Agent details:
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)
conn.commit()
# 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()
Output:
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("""
Output:
Salesman ID: 5
Name: Jhon Edin
Commission: 5
Data entered successfully.
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("""
sqllite_conn = sql_connection()
sql_table(sqllite_conn)
if (sqllite_conn):
sqllite_conn.close()
Output:
0
Number of records after inserting rows :
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("""
conn.commit()
if (sqllite_conn):
sqllite_conn.close()
Output:
Agent details:
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("""
conn.commit()
if (sqllite_conn):
sqllite_conn.close()
Output:
Agent details:
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("""
if (sqllite_conn):
sqllite_conn.close()
Output:
Agent details:
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:
Saved as mydatabase_dump.sql
Example 22 : Write a Python program to find the class wise roll number from a tuple-of-tuples.
class_rollno = defaultdict(list)
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.
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: