Location via proxy:
[ UP ]
[Report a bug]
[Manage cookies]
No cookies
No scripts
No ads
No referrer
Show this form
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
36 views
Python Module 5 Important Questions
Uploaded by
akshay s
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python Module 5 Important Questions For Later
Download
Save
Save Python Module 5 Important Questions For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
36 views
Python Module 5 Important Questions
Uploaded by
akshay s
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python Module 5 Important Questions For Later
Carousel Previous
Carousel Next
Save
Save Python Module 5 Important Questions For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 14
Search
Fullscreen
1 Explain connect, cursor, execute and close command of a database with suitable example. A import sqites conn = sqlite3.connect(music.sqite’) /! The connect operation makes a “connection” to the database stored in the file music sqiite3 in the current directory. cur = conn.cursor() Calling cursor() is very similar conceptually to calling open() when dealing with text files. curexecute((DROP TABLE IF EXISTS Tracks’) it We can begin to execute commands on the contents of the database using the execute() method. curexecute(CREATE TABLE Tracks (tile TEXT, plays INTEGER)’ conn.close() close() is used to close the database. Design python program to retrieve node present in XML tree. Write a note on XML. A XML looks very similar to HTML, but XML is more structured than HTML.Often itis helpful to think of an XML document as a tree structure where there is a top tag person and other tags such as phone are drawn as children of their parent nodes. limport xml.etree.EiementTree as ET input ="
001
Chuck
009
Brent
stuff = ET.fromstring (input) \st = stuff findall(users/user’) print(User count’, len('st)) for item in ist: print(’Name’, item find(name’) text) print(ld, item find¢ idl) text) print(Attribute’, item. get(’x")) Output: User count: 2 Name Chuck Scanned with CamScannerId 001 Attribute 2 Name Brent Id 009 Attribute 7 Write a python code to read the file from web using urib and retrieve the data of the file. Also compute the frequency of each word in the file A The equivalent code to read the sample. file from the web using urlib is as follows: impor uriib request, urlib parse, urlib.error fhand = urlib. request urlopen(http://data prée.org/sample.txt’) for line in than: print(ine.decode().strip()) We can write a program to retrieve the data for sample.txt and compute the frequency of each word in the file as follows: import urilib.request, urllib parse, urlib.error counts = dict() fhand = urlib. request.urlopen(‘http://data prée.org/sample.txt’) for line in fhand: words = line.decode() split() for word in words: counts|word] counts.get(word, 0) + 1 print(counts) Explain googie geocoding web service with program. ‘A: Google has an excellent web service that allows us to make use of their large database of geographic information. We can submit a geographical search string like "Ann Arbor, MI" to their geocoding AP! and have Google retum its best guess as to where on a map we might find our search string and tell us about the landmarks nearby. The geocoding service is free but rate limited so you cannot make unlimited use of the API in ‘a commercial application. But if you have some survey data where an end user has entered a location in a free-format input box, you can use this API to clean up your data quite nicely. The following is a simple application to prompt the user for a search string, call the Google geocoding API, and extract information from the returned JSON. import uni request, uriib. parse, unlib.error import json serviceurl while True: address = input('Enter location: ') if len(address) < 1: break url= serviceuri + urlib.parse.uriencode({'sensor: false’, ‘address': address}) print(Retrieving’, url) ttp:simaps. googleapis. com/maps/api/geocode/json” Scanned with CamScanneruh = urllib. request urlopen(url) data = uh.read().decode() print(Retrieved’, len(data), ‘characters') ty, js = json loads(data) except js = None if not js or ‘status’ not in js or js{status'] print('==== Failure To Retrieve print(data) cor le print(json.dumps(js, indent=4)) lat = js['results"[0]["geometry"I[ "location" }["iat"] Ing = js["results"0][' geometry’ ocation"['ing’] print(‘at’, lat, ‘ing’, Ing) location = jsfresults'][0]['formatted_address'] print(location) Output: lat 42,2808256 Ing -83.7430378 Ann Arbor, MI, USA Describe creation of database table using database cursor architecture. A: The code to create a database file and a table named Tracks with two columns in the database is as follows: import sqiite3 conn = sqlite3.connect(‘music.sqite’) cur = conn.cursor() curexecute(DROP TABLE IF EXISTS Tracks’) cur.execute(CREATE TABLE Tracks (tite TEXT, plays INTEGER)) conn.ciose() The connect operation makes a “connection” to the database stored in the file music.sqlite3 in the current directory. Ifthe file does not exist, it will be created. The reason this is called a Connection" is that sometimes the database is stored on a separate “database server" from the server on which we are running our application. A cursor is like a file handle that we can use to perform operations on the data stored in the database. Calling cursor() is very similar conceptually to calling open() when dealing with text files, Scanned with CamScannerexecute fetchone fetchall Courses Figure 15.2 A Database Cursor Once we have the cursor, we can begin to execute commands on the contents of the database using the execute() method. Brief on Structures Query Language. with suitable python program explain function involved in creating, inserting, displaying, deleting and updating database table in python. A import sqiite3 conn = sqlite3.connect(‘music. sqlite’) cur = conn.cursor() cur.execute(INSERT INTO Tracks (title, plays) VALUES (?, 2)’ (Thunderstruck, 20)) cur.execute(INSERT INTO Tracks (title, plays) VALUES (?, 2)’ (My Way’, 15)) cconn.commit() print("Tracks:’) cur.execute(‘SELECT title, plays FROM Tracks’) for row in cur: print(row) cur.execute(DELETE FROM Tracks WHERE plays < 100’) cur.ciose() When we create a table, we indicate the names and types of the columns CREATE TABLE Tracks (title TEXT, plays INTEGER) To insert a row into a table, we use the SQL INSERT command INSERT INTO Tracks (title, plays) VALUES (‘My Way’, 15) The INSERT statement specifies the table name, then a list of the fields/columns that you would like to set in the new row, and then the keyword VALUES and a list of corresponding values for each of the fields. The SQL SELECT command is used to retrieve rows and columns from a database. The SELECT statement lets you specify which columns you would like to retrieve as well as a WHERE clause to select which rows you would like to see. It also allows an optional ORDER BY clause to control the sorting of the returned rows. SELECT * FROM Tracks WHERE title = "My Way’ Using * indicates that you want the database to return all of the columns for each row that matches the WHERE clause You can request that the retumed rows be sorted by one of the fields as follows: Scanned with CamScannerSELECT title plays FROM Tracks ORDER BY title To remove a row, you need a WHERE clause on an SQL DELETE statement. The WHERE clause determines which rows are to be deleted DELETE FROM Tracks WHERE title = ‘My Way’ itis possible to UPDATE a column or columns within one or more rows in a table using the SQL UPDATE statement as follows: UPDATE Tracks SET plays = 16 WHERE title = 'My Way’ The UPDATE statement specifies a table and then a list of fields and values to change after the SET keyword and then an optional WHERE clause to select the rows that are to be updated. Explain any 2 socket function. Explain support for parsing HTML using regular expression with an example. A listen() - establishes a socket to listen for incoming connection. send() - sends data on a connected socket. sendto() - sends data on an unconnected socket. recv() - receives data from a connected socket. One simple way to parse HTML is to use regular expressions to repeatedly search for and extract substrings that match a particular pattern We can construct a well-formed regular expression to match and extract the link values as follows: href="http:// +2" We add parentheses to our regular expression to indicate which part of our matched string we would like to extract, and produce the following program: # Search for lines that start with From and have an at sign import urilib.request, urilib parse, urlib.error import re url= input(Enter -") html = urliib request uriopen(url).read() links = re.findall(b'href="(http:/."2)", him) for link in links: print(ink.decode()) Output Enter - http:/iwww.dr-chuck.com/paget.htm. http:siwww dr-chuck.com/page2. htm Write a program to parse HTML using BeautifulSoup, A We will use urllib to read the page and then use BeautifulSoup to extract the href attributes from the anchor (a) tags. Program: import unlib request, urlib.parse, unlib.error Scanned with CamScannerfrom bs4 import BeautifulSoup input(Enter -*) him = urlib request.urlopen(url).read() soup = BeautifulSoup(htmi, 'html.parser’) # Retrieve all of the anchor tags tags = soup(') for tag in tags: print(tag.get(href, None)) Explain with a neat diagram of Service-Oriented Architecture. List the advantages of the same. ‘A: When we begin to build our programs where the functionality of our program includes access to services provided by other programs, we call the approach a Service-Oriented Architecture or SOA. A SOA approach is one where our overall application makes use of the services of other applications. A non-SOA approach is where the application is a single standalone application which contains al of the code necessary to implement the application. The data for hotel's is not stored on the airline computers. Instead, the airline computers contact the services on the hotel computers and retrieve the hotel data and present it to the user. When the user agrees to make a hotel reservation using the airline site, the airline site uses another web service on the hotel systems to actually make the reservation. And when it comes time to charge your credit card for the whole transaction, still other computers become involved in the process. Travel Application ve 132: Service Oriented Architecture A Service-Oriented Architecture has many advantages including (1) we always maintain only one copy of data (this is particularly important for things like hotel reservations where we do not want to over-commit) (2) the owners of the data can set the rules about the use of their data. With these advantages, an SOA system must be carefully designed to have good performance and meet the user's needs. Scanned with CamScanner410. What is JSON? Illustrate the concept of parsing JSON python code A: The JSON format was inspired by the object and array format used in the JavaScript language. But since Python was invented before JavaScript, Python's syntax for dictionaries, and lists influenced the syntax of JSON. So the format of JSON is nearly identical to a combination of Python lists and dictionaries. In the following program, we use the built-in json library to parse the JSON and read through the data. Compare this closely to the equivalent XML data and code above. The JSON has less detail, so we must know in advance that we are getting a list and that the list is of users and each user is a set of key-value pairs. The JSON is more succinct (an advantage) but also is less self-describing (a disadvantage). import json data = info = json loads(data) print((User count: len(info)) for item in into: print(Name’,item[name’)) print(Ic’, itemfia') print( Attribute’, item[x]) Output User count: 2 Name Chuck Id 001 Attribute 2 Name Brent Id 009 Attribute 7 Scanned with CamScannerRetrieving an image over HTTP *We can use a similar program to retrieve an image across using HTTP. * Instead of copying the data to the screen as the program runs, we accumulate the data in a string, trim off the headers, and then save the image data to a file as follows: Program MOST data pre ong thc senda GET hp ote oor pg MTH/LOMAANAND time seep(025) court = count + fen(daa) lenaata) count) snysoch. cose) Contd... # Look for the end of the header (2 CRLF) pos = picture.find(b"\r\n\r\n") print('Header length’, pos) print(picture[:pos].decode()) # Skip past the header and save the picture data picture = picture[pos+4:] fhand = open("stuff.jpg", "wb") fhand.write(picture) fhand.close() Scanned with CamScanner— Security and API Usage Public APIs can be used by anyone without any problem. But, if the API is set up by some private vendor, then one must have API key to use that API. If API key is available, then it can be included as a part of POST method or as a parameter on the URL while calling API. Sometimes, vendor wants more security and expects the user to provide cryptographically signed messages using shared keys and secrets. The most common protocol used in the internet for signing requests is OAuth. As the Twitter API became increasingly valuable, Twitter went from an open and public API to an API that required the use of OAuth signatures on each API request. But, there are still a number of convenient and free OAuth libraries so you can avoid writing an OAuth implementation from scratch by reading the specification. These libraries are of varying complexity and have varying degrees of richness. ‘The OAuth web site has information about various OAuth libraries. Scanned with CamScannerEx4, Write a program to create a Student database with a table consisting of student name and age. Read n records from the user and insert them into database. Write queries to display all records and to display the students whose age is 20. import sqlite} conn=sqlite3.connect('StudentDB.db') e=conn.cursor() c.execute(‘CREATE TABLE thlStudent(name text, age Integer)’) n-int(input(“Enter number of records:”)) for i in range(n): nm=input("Enter Name:") ag=int(input("Enter age:")) c.execute("INSERT INTO tblStudent VALUES\ nm,ag)) conn.commit() c.execute("select * from thlStudent ") print(c.fetchall()) c.execute("select * from tblStudent where age=20") print(e.fetchall()) conn.close() Scanned with CamScanner— Using JOIN to Retrieve Data © When we follow the rules of database normalization and have data separated into multiple tables, linked together using primary and foreign keys, we need to be able to build a SELECT that reassembles the data across the tables, + SQL uses the JOIN clause to reconnect these tables. In the JOIN clause you specify the fields that are used to reconnect the rows between the tables. Mamatha A, Asst Prof, Dept of CSE, SVIT. Page 25 Scanned with CamScannerHypertext Transfer Protocol — HTTP * The protocols that are used to transfer hypertext between two computers is known as Hypertext Transfer Protocol. * HTTP provides standard between a web browser and web server to establish communication * It is set of rules for transferring data from one computer to another. * Data such as text, images, and other multimedia files are shared on the World Wide Web. * The network protocol that powers the web is actually quite simple and there is built-in support in Python called socket which makes it very easy to make network connections and retrieve data over those sockets in a Python program. Contd... *A socket is much like a file, except that a single socket provides a two-way connection between two programs. * We can both read from and write to the same socket. * If we write something to a socket, it is sent to the application at the other end of the socket. * If we read from the socket, you are given the data which the other application has sent. * A protocol is a set of precise rules that determine who is to go first, what they are to do, and then what the responses are to that message, and who sends next, and so on. Scanned with CamScannerContd... * We can write a program to retrieve the data for romeo.txt and compute the frequency of each word in the file as follows: import urllib.request, urllib.parse, urllib.error fhand = urllib.request.urlopen(‘http://data.pr4e.org/romeo.txt') counts = dict() for line in fhand: words = line.decode().split() for word in words: counts[word] = counts.get(word, 0) + 1 print(counts) Scanned with CamScannerSpidering Twitter using a database * bttos://www.pv4e.com/code3/twspiderpy ‘Simple database dumpers: import sqlite3 conn = sqlite3.connect{'spider-sqlite’) cur = conn.cursor() curexecute('SELECT * FROM Twitter’) count = 0 for row in cur: print(row) count = count +1 print(count, ‘rows.') cur.close() Scanned with CamScanner
You might also like
Hourglass Workout Program by Luisagiuliet 2
PDF
76% (21)
Hourglass Workout Program by Luisagiuliet 2
51 pages
12 Week Program: Summer Body Starts Now
PDF
87% (46)
12 Week Program: Summer Body Starts Now
70 pages
Read People Like A Book by Patrick King-Edited
PDF
57% (82)
Read People Like A Book by Patrick King-Edited
12 pages
Livingood, Blake - Livingood Daily Your 21-Day Guide To Experience Real Health
PDF
77% (13)
Livingood, Blake - Livingood Daily Your 21-Day Guide To Experience Real Health
260 pages
Cheat Code To The Universe
PDF
94% (79)
Cheat Code To The Universe
34 pages
Facial Gains Guide (001 081)
PDF
91% (45)
Facial Gains Guide (001 081)
81 pages
Curse of Strahd
PDF
95% (467)
Curse of Strahd
258 pages
The Psychiatric Interview - Daniel Carlat
PDF
91% (34)
The Psychiatric Interview - Daniel Carlat
473 pages
The Borax Conspiracy
PDF
91% (57)
The Borax Conspiracy
14 pages
COSMIC CONSCIOUSNESS OF HUMANITY - PROBLEMS OF NEW COSMOGONY (V.P.Kaznacheev,. Л. V. Trofimov.)
PDF
94% (215)
COSMIC CONSCIOUSNESS OF HUMANITY - PROBLEMS OF NEW COSMOGONY (V.P.Kaznacheev,. Л. V. Trofimov.)
212 pages
TDA Birth Certificate Bond Instructions
PDF
97% (285)
TDA Birth Certificate Bond Instructions
4 pages
The Secret Language of Attraction
PDF
86% (108)
The Secret Language of Attraction
278 pages
How To Develop and Write A Grant Proposal
PDF
83% (542)
How To Develop and Write A Grant Proposal
17 pages
Penis Enlargement Secret
PDF
60% (124)
Penis Enlargement Secret
12 pages
Workbook For The Body Keeps The Score
PDF
89% (53)
Workbook For The Body Keeps The Score
111 pages
Donald Trump & Jeffrey Epstein Rape Lawsuit and Affidavits
PDF
83% (1016)
Donald Trump & Jeffrey Epstein Rape Lawsuit and Affidavits
13 pages
KamaSutra Positions
PDF
78% (69)
KamaSutra Positions
55 pages
7 Hermetic Principles
PDF
93% (30)
7 Hermetic Principles
3 pages
27 Feedback Mechanisms Pogil Key
PDF
77% (13)
27 Feedback Mechanisms Pogil Key
6 pages
Frank Hammond - List of Demons
PDF
92% (92)
Frank Hammond - List of Demons
3 pages
Phone Codes
PDF
79% (28)
Phone Codes
5 pages
36 Questions That Lead To Love
PDF
91% (35)
36 Questions That Lead To Love
3 pages
How 2 Setup Trust
PDF
97% (307)
How 2 Setup Trust
3 pages
100 Questions To Ask Your Partner
PDF
78% (36)
100 Questions To Ask Your Partner
2 pages
The 36 Questions That Lead To Love - The New York Times
PDF
94% (34)
The 36 Questions That Lead To Love - The New York Times
3 pages
Satanic Calendar
PDF
25% (56)
Satanic Calendar
4 pages
The 36 Questions That Lead To Love - The New York Times
PDF
95% (21)
The 36 Questions That Lead To Love - The New York Times
3 pages
Jeffrey Epstein39s Little Black Book Unredacted PDF
PDF
75% (12)
Jeffrey Epstein39s Little Black Book Unredacted PDF
95 pages
14 Easiest & Hardest Muscles To Build (Ranked With Solutions)
PDF
100% (8)
14 Easiest & Hardest Muscles To Build (Ranked With Solutions)
27 pages
1001 Songs
PDF
70% (73)
1001 Songs
1,798 pages
The 4 Hour Workweek, Expanded and Updated by Timothy Ferriss - Excerpt
PDF
23% (954)
The 4 Hour Workweek, Expanded and Updated by Timothy Ferriss - Excerpt
38 pages
Zodiac Sign & Their Most Common Addictions
PDF
63% (30)
Zodiac Sign & Their Most Common Addictions
9 pages
NB 9
PDF
No ratings yet
NB 9
29 pages
CS1.1.1
PDF
No ratings yet
CS1.1.1
2 pages
5th Module Notes
PDF
No ratings yet
5th Module Notes
20 pages
Python Unit - 5
PDF
No ratings yet
Python Unit - 5
8 pages
Python MYSQL
PDF
No ratings yet
Python MYSQL
29 pages
Unit-5 Python
PDF
100% (1)
Unit-5 Python
36 pages
Sqlite3 A
PDF
No ratings yet
Sqlite3 A
25 pages
Interrupt: (String1, String2) : String1 String2
PDF
No ratings yet
Interrupt: (String1, String2) : String1 String2
18 pages
441761879-Investigatory-project-Contact-Book conv
PDF
No ratings yet
441761879-Investigatory-project-Contact-Book conv
38 pages
ML PGM
PDF
No ratings yet
ML PGM
8 pages
Python Interface With SQL Databases
PDF
No ratings yet
Python Interface With SQL Databases
8 pages
Interface python with sql
PDF
No ratings yet
Interface python with sql
7 pages
CONNECTIVITY BETWEEN PYTHON AND MYSQL (1)
PDF
No ratings yet
CONNECTIVITY BETWEEN PYTHON AND MYSQL (1)
14 pages
SBL Python LAB Manual by NY Expt. No. 6.docx
PDF
No ratings yet
SBL Python LAB Manual by NY Expt. No. 6.docx
5 pages
Unit-6
PDF
No ratings yet
Unit-6
20 pages
Inteface python with mysql
PDF
No ratings yet
Inteface python with mysql
13 pages
2 Interface Python With Mysql - Programs
PDF
No ratings yet
2 Interface Python With Mysql - Programs
2 pages
Unit 4 Python
PDF
No ratings yet
Unit 4 Python
52 pages
Python Record Manual
PDF
No ratings yet
Python Record Manual
18 pages
Unit 5 Python
PDF
No ratings yet
Unit 5 Python
13 pages
Chapter-3
PDF
No ratings yet
Chapter-3
4 pages
12.6. Sqlite3 - DB-API 2.0 Interface For SQLite Databases - Python 3.6
PDF
100% (2)
12.6. Sqlite3 - DB-API 2.0 Interface For SQLite Databases - Python 3.6
24 pages
Interface Python With SQL
PDF
No ratings yet
Interface Python With SQL
17 pages
CSE 4508 RDBMS Lab Task Winter 2024
PDF
No ratings yet
CSE 4508 RDBMS Lab Task Winter 2024
7 pages
Copy of Python Database Connectivity
PDF
No ratings yet
Copy of Python Database Connectivity
24 pages
Pydblite - Documentation
PDF
No ratings yet
Pydblite - Documentation
35 pages
Travel Agency Management System
PDF
No ratings yet
Travel Agency Management System
41 pages
Lecture6 (1)
PDF
No ratings yet
Lecture6 (1)
28 pages
Interface Python With MYSQL
PDF
No ratings yet
Interface Python With MYSQL
10 pages
DB Python Unit 3
PDF
No ratings yet
DB Python Unit 3
10 pages
Chapter 10 - Interface Python With MySQL
PDF
No ratings yet
Chapter 10 - Interface Python With MySQL
7 pages
sql-update-delete
PDF
No ratings yet
sql-update-delete
6 pages
Python MySQL Connectivity
PDF
No ratings yet
Python MySQL Connectivity
26 pages
PPFSD - Question - Bank Answers New
PDF
No ratings yet
PPFSD - Question - Bank Answers New
61 pages
Python+Mysql 7
PDF
No ratings yet
Python+Mysql 7
11 pages
Sqlite3 Cheatsheet For Python 3 GitHub
PDF
No ratings yet
Sqlite3 Cheatsheet For Python 3 GitHub
6 pages
Databases Python
PDF
No ratings yet
Databases Python
44 pages
DB Connectivity
PDF
No ratings yet
DB Connectivity
67 pages
Python Sqlite Tutorial
PDF
100% (2)
Python Sqlite Tutorial
42 pages
database_programming
PDF
No ratings yet
database_programming
16 pages
MySQL Connectivity with Python
PDF
No ratings yet
MySQL Connectivity with Python
7 pages
Interface Python With MySQL - 1
PDF
No ratings yet
Interface Python With MySQL - 1
28 pages
Python Guide
PDF
No ratings yet
Python Guide
162 pages
Interface Python With MySQL
PDF
No ratings yet
Interface Python With MySQL
40 pages
SQLiteUsingPython
PDF
No ratings yet
SQLiteUsingPython
49 pages
A SQLite Tutorial With Python PDF
PDF
100% (1)
A SQLite Tutorial With Python PDF
14 pages
MODULE 4
PDF
No ratings yet
MODULE 4
30 pages
The Python Database API
PDF
No ratings yet
The Python Database API
9 pages
T4_L8_Host_Program_Python
PDF
No ratings yet
T4_L8_Host_Program_Python
17 pages
Python SQLite Tutorial - The Ultimate Guide
PDF
No ratings yet
Python SQLite Tutorial - The Ultimate Guide
12 pages
VKS-Interface Python With MySQL
PDF
No ratings yet
VKS-Interface Python With MySQL
27 pages
Notes on File Handling
PDF
No ratings yet
Notes on File Handling
4 pages
Exp10 Python
PDF
No ratings yet
Exp10 Python
10 pages
Unit - V (Python Programming)
PDF
No ratings yet
Unit - V (Python Programming)
16 pages
CH 8,9,10 SQL
PDF
No ratings yet
CH 8,9,10 SQL
62 pages
Programming 2 Lectures
PDF
No ratings yet
Programming 2 Lectures
52 pages
4th module python
PDF
No ratings yet
4th module python
33 pages
Lecture 4 Notes
PDF
No ratings yet
Lecture 4 Notes
32 pages