0% found this document useful (0 votes)
7 views16 pages

Python Tutorials

This document provides an overview of Python keywords and built-in functions, specifically focusing on their usage with SQLite database operations. It includes examples related to an accounting application, demonstrating how to create a database, define tables, and perform various operations using Python syntax. The document also categorizes keywords into control flow, function definitions, exception handling, and more, along with corresponding database examples.

Uploaded by

alexanderyusra9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

Python Tutorials

This document provides an overview of Python keywords and built-in functions, specifically focusing on their usage with SQLite database operations. It includes examples related to an accounting application, demonstrating how to create a database, define tables, and perform various operations using Python syntax. The document also categorizes keywords into control flow, function definitions, exception handling, and more, along with corresponding database examples.

Uploaded by

alexanderyusra9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Keywords and Built-in Functions with

Database Examples

May 18, 2025

Introduction
This document lists all 35 Python keywords and 71 built-in functions (Python 3.11), with
descriptions and examples using SQLite database operations. The examples are based
on an [Link] database with accounts (name, currency) and transactions
(id, account_name, amount, currency, date) tables, relevant to an accounting application
similar to the load_balances function.

Database Setup
Run the following code to create the database:
1 import sqlite3
2 conn = [Link](”[Link]”)
3 cursor = [Link]()
4 [Link](”””
5 CREATE TABLE IF NOT EXISTS accounts (
6 name TEXT PRIMARY KEY,
7 currency TEXT
8 )
9 ”””)
10 [Link](”””
11 CREATE TABLE IF NOT EXISTS transactions (
12 id INTEGER PRIMARY KEY AUTOINCREMENT,
13 account_name TEXT,
14 amount REAL,
15 currency TEXT,
16 date TEXT,
17 FOREIGN KEY (account_name) REFERENCES accounts(name)
18 )
19 ”””)
20 [Link](”INSERT OR IGNORE INTO accounts (name, currency) VALUES
(’Abbas’, ’PKR’), (’Adnan’, ’USD’), (’TMN’, ’TMN’)”)
21 [Link](”INSERT INTO transactions (account_name, amount, currency,
date) VALUES (’Abbas’, 1000.50, ’PKR’, ’2025-05-01’), (’Adnan’,
-200.75, ’USD’, ’2025-05-02’), (’TMN’, 500.25, ’TMN’, ’2025-05-03’)”)
22 [Link]()
23 [Link]()

1
1 Python Keywords
1.1 Control Flow Keywords
if, elif, else Conditional statements for decision-making.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE account_name =
’Abbas’”)
4 amount = [Link]()[0]
5 if amount > 0:
6 print(”Positive balance”)
7 elif amount == 0:
8 print(”Zero balance”)
9 else:
10 print(”Negative balance”)
11 [Link]()

for Iterates over a sequence.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT name, currency FROM accounts”)
4 for name, currency in [Link]():
5 print(f”Account: {name}, Currency: {currency}”)
6 [Link]()

while Loops while a condition is true.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT id, amount FROM transactions”)
4 total = 0
5 while True:
6 row = [Link]()
7 if row is None:
8 break
9 total += row[1]
10 print(f”Total transactions: {total}”)
11 [Link]()

break Exits a loop.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 for amount in [Link]():
5 if amount[0] < 0:
6 print(”Found negative transaction”)
7 break
8 [Link]()

continue Skips to the next loop iteration.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)

2
4 for amount in [Link]():
5 if amount[0] <= 0:
6 continue
7 print(f”Positive amount: {amount[0]}”)
8 [Link]()

pass No-operation placeholder.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT currency FROM accounts”)
4 if [Link]()[0] == ”PKR”:
5 pass
6 else:
7 print(”Non-PKR account”)
8 [Link]()

1.2 Function and Class Definition Keywords


def Defines a function.
1 def get_balance(account_name):
2 conn = [Link](”[Link]”)
3 cursor = [Link]()
4 [Link](”SELECT SUM(amount) FROM transactions WHERE
account_name = ?”, (account_name,))
5 balance = [Link]()[0] or 0
6 [Link]()
7 return balance
8 print(get_balance(”Abbas”))

flyttreturn] Returns a value from a function.


1 def has_transactions(account_name):
2 conn = [Link](”[Link]”)
3 cursor = [Link]()
4 [Link](”SELECT COUNT(*) FROM transactions WHERE
account_name = ?”, (account_name,))
5 count = [Link]()[0]
6 [Link]()
7 return count > 0
8 print(has_transactions(”Adnan”))

class Defines a class.


1 class AccountManager:
2 def __init__(self):
3 [Link] = [Link](”[Link]”)
4 def get_currencies(self):
5 cursor = [Link]()
6 [Link](”SELECT DISTINCT currency FROM accounts”)
7 currencies = [row[0] for row in [Link]()]
8 [Link]()
9 return currencies
10 manager = AccountManager()
11 print(manager.get_currencies())

3
lambda Creates an anonymous function.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 amounts = sorted([Link](), key=lambda x: x[0])
5 print(amounts)
6 [Link]()

yield Yields values from a generator.


1 def transaction_generator(currency):
2 conn = [Link](”[Link]”)
3 cursor = [Link]()
4 [Link](”SELECT amount FROM transactions WHERE currency =
?”, (currency,))
5 for row in [Link]():
6 yield row[0]
7 [Link]()
8 for amount in transaction_generator(”PKR”):
9 print(amount)

async, await Defines and awaits asynchronous operations.


1 import aiosqlite
2 async def fetch_accounts():
3 async with [Link](”[Link]”) as conn:
4 cursor = await [Link](”SELECT name FROM accounts”)
5 accounts = await [Link]()
6 return [row[0] for row in accounts]
7 import asyncio
8 print([Link](fetch_accounts()))

1.3 Exception Handling Keywords


try, except, finally Handles exceptions.
1 try:
2 conn = [Link](”[Link]”)
3 cursor = [Link]()
4 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Unknown’”)
5 print([Link]()[0])
6 except IndexError:
7 print(”No transactions found”)
8 finally:
9 [Link]()

raise Raises an exception.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Unknown’”)
4 if not [Link]():
5 raise ValueError(”Account not found”)
6 [Link]()

4
1.4 Variable and Scope Keywords
global Declares a global variable.
1 total_balance = 0
2 def update_total():
3 global total_balance
4 conn = [Link](”[Link]”)
5 cursor = [Link]()
6 [Link](”SELECT SUM(amount) FROM transactions”)
7 total_balance = [Link]()[0] or 0
8 [Link]()
9 update_total()
10 print(total_balance)

nonlocal Declares a nonlocal variable.


1 def process_transactions():
2 count = 0
3 def update_count():
4 nonlocal count
5 conn = [Link](”[Link]”)
6 cursor = [Link]()
7 [Link](”SELECT COUNT(*) FROM transactions”)
8 count = [Link]()[0]
9 [Link]()
10 update_count()
11 return count
12 print(process_transactions())

del Deletes an object.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”DELETE FROM transactions WHERE amount = 0”)
4 [Link]()
5 [Link]()

1.5 Logical and Membership Keywords


and Logical AND.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT amount testers\lstinline|and|] Logical AND.
4 \begin{lstlisting}
5 conn = [Link](”[Link]”)
6 cursor = [Link]()
7 [Link](”SELECT amount FROM transactions WHERE account_name =
’Abbas’ AND currency = ’PKR’”)
8 print([Link]()[0])
9 [Link]()

or Logical OR.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE currency = ’PKR’ OR
currency = ’USD’”)

5
4 print([row[0] for row in [Link]()])
5 [Link]()

not Logical NOT.


1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE NOT currency = ’TMN’”)
4 print([row[0] for row in [Link]()])
5 [Link]()

in Membership test.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE currency IN (’PKR’,
’USD’)”)
4 print([row[0] for row in [Link]()])
5 [Link]()

is Identity test.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE account_name =
’Abbas’”)
4 result = [Link]()
5 if result is None:
6 print(”No transactions”)
7 [Link]()

1.6 Import and Module Keywords


import, from, as Imports modules.
1 from sqlite3 import connect as db_connect
2 conn = db_connect(”[Link]”)
3 cursor = [Link]()
4 [Link](”SELECT name FROM accounts”)
5 print([row[0] for row in [Link]()])
6 [Link]()

1.7 Miscellaneous Keywords


assert Debugging assertion.
1 conn = [Link](”[Link]”)
2 cursor = [Link]()
3 [Link](”SELECT COUNT(*) FROM accounts”)
4 count = [Link]()[0]
5 assert count > 0, ”No accounts found”
6 [Link]()

with Context manager.

6
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT SUM(amount) FROM transactions”)
4 print([Link]()[0] or 0)

True, False, None Boolean and null values.


1 def is_active(account_name):
2 with [Link](”[Link]”) as conn:
3 cursor = [Link]()
4 [Link](”SELECT COUNT(*) FROM transactions WHERE
account_name = ?”, (account_name,))
5 return [Link]()[0] > 0 is True
6 print(is_active(”Abbas”))
7 print(is_active(”Unknown”))
8 print(None if is_active(”Unknown”) else ”Inactive”)

2 Python Built-in Functions


2.1 Type Conversion and Creation
bool() Converts to boolean.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 print(bool([Link]()[0]))

int() Converts to integer.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 print(int([Link]()[0]))

float() Converts to float.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 print(float([Link]()[0]))

complex() Creates a complex number.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE WATCH
account_name = ’Abbas’”)
4 amount = [Link]()[0]
5 print(complex(amount, 0))

str() Converts to string.

7
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 print(str([Link]()[0]))

bytes() Converts to bytes.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Abbas’”)
4 print(bytes([Link]()[0], ’utf-8’))

bytearray() Creates mutable bytearray.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Abbas’”)
4 print(bytearray([Link]()[0], ’utf-8’))

list() Converts to list.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts”)
4 print(list([Link]()))

tuple() Converts to tuple.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts”)
4 print(tuple([Link]()))

set() Converts to set.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT currency FROM accounts”)
4 print(set(row[0] for row in [Link]()))

frozenset() Creates immutable set.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT currency FROM accounts”)
4 print(frozenset(row[0] for row in [Link]()))

dict() Creates dictionary.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name, currency FROM accounts”)
4 print(dict([Link]()))

object() Creates base object.

8
1 class DBObject(object):
2 def __init__(self):
3 [Link] = [Link](”[Link]”)
4 db = DBObject()
5 print([Link](”SELECT name FROM accounts”).fetchall())
6 [Link]()

slice() Creates slice object.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 amounts = [row[0] for row in [Link]()]
5 print(amounts[slice(0, 2)])

range() Creates range object.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT id FROM transactions”)
4 for i in range(len([Link]())):
5 print(f”Transaction {i+1}”)

2.2 Numeric and Mathematical Operations


abs() Returns absolute value.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Adnan’”)
4 print(abs([Link]()[0]))

divmod() Returns quotient and remainder.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 amount = [Link]()[0]
5 print(divmod(int(amount), 100))

pow() Raises to power.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 amount = [Link]()[0]
5 print(pow(amount, 2))

round() Rounds a number.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 print(round([Link]()[0], 1))

9
sum() Sums an iterable.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 print(sum(row[0] for row in [Link]()))

max() Returns maximum value.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 print(max(row[0] for row in [Link]()))

min() Returns minimum value.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 print(min(row[0] for row in [Link]()))

2.3 String and Character Operations


chr() Returns character from Unicode.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT ascii(name) FROM accounts WHERE name =
’Abbas’”)
4 print(chr([Link]()[0]))

ord() Returns Unicode of character.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Abbas’”)
4 print(ord([Link]()[0][0]))

format() Formats a value.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions WHERE
account_name = ’Abbas’”)
4 print(format([Link]()[0], ”.2f”))

hex() Converts to hexadecimal.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT id FROM transactions WHERE account_name =
’Abbas’”)
4 print(hex([Link]()[0]))

oct() Converts to octal.

10
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT id FROM transactions WHERE account_name =
’Abbas’”)
4 print(oct([Link]()[0]))

bin() Converts to binary.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT id FROM transactions WHERE account_name =
’Abbas’”)
4 print(bin([Link]()[0]))

2.4 Iteration and Functional Programming


iter() Creates an iterator.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 iterator = iter([Link]())
5 print(next(iterator))

next() Gets next iterator item.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 iterator = iter([Link]())
5 print(next(iterator, (0,)))

map() Applies function to iterable.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 amounts = list(map(lambda x: x[0] * 2, [Link]()))
5 print(amounts)

filter() Filters iterable.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 positive = list(filter(lambda x: x[0] > 0, [Link]()))
5 print(positive)

zip() Combines iterables.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name, currency FROM accounts”)
4 names, currencies = zip(*[Link]())
5 print(names, currencies)

11
reversed() Reverses an iterable.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 amounts = [row[0] for row in [Link]()]
5 print(list(reversed(amounts)))

sorted() Sorts an iterable.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 amounts = sorted(row[0] for row in [Link]())
5 print(amounts)

all() Checks if all items are true.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 print(all(row[0] > 0 for row in [Link]()))

any() Checks if any item is true.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 print(any(row[0] < 0 for row in [Link]()))

enumerate() Iterates with indices.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts”)
4 for i, row in enumerate([Link]()):
5 print(f”Account {i+1}: {row[0]}”)

2.5 Object Introspection and Manipulation


hasattr() Checks for attribute.
1 class DB:
2 conn = [Link](”[Link]”)
3 db = DB()
4 if hasattr(db, ’conn’):
5 [Link](”SELECT name FROM accounts”).fetchall()
6 [Link]()

getattr() Gets attribute value.


1 class DB:
2 currency = ”PKR”
3 db = DB()
4 with [Link](”[Link]”) as conn:
5 cursor = [Link]()
6 [Link](”SELECT name FROM accounts WHERE currency = ?”,
(getattr(db, ’currency’),))
7 print([Link]())

12
setattr() Sets attribute value.
1 class DB:
2 pass
3 db = DB()
4 setattr(db, ’conn’, [Link](”[Link]”))
5 [Link](”SELECT name FROM accounts”).fetchall()
6 [Link]()

delattr() Deletes attribute.


1 class DB:
2 conn = [Link](”[Link]”)
3 db = DB()
4 delattr(db, ’conn’)
5 print(hasattr(db, ’conn’))

dir() Lists attributes.


1 with [Link](”[Link]”) as conn:
2 print(dir(conn))

vars() Returns object dictionary.


1 class DB:
2 currency = ”PKR”
3 db = DB()
4 print(vars(db))

id() Returns object ID.


1 with [Link](”[Link]”) as conn1:
2 with [Link](”[Link]”) as conn2:
3 print(id(conn1), id(conn2))

type() Returns object type.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 print(type([Link]()))

isinstance() Checks instance type.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 print(isinstance([Link](), list))

issubclass() Checks subclass relationship.


1 class DBConnection([Link]):
2 pass
3 print(issubclass(DBConnection, [Link]))

callable() Checks if callable.


1 with [Link](”[Link]”) as conn:
2 print(callable([Link]))

13
hash() Returns hash value.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Abbas’”)
4 print(hash([Link]()[0]))

len() Returns length.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts”)
4 print(len([Link]()))

repr() Returns string representation.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT amount FROM transactions”)
4 print(repr([Link]()))

ascii() Returns ASCII-escaped string.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Abbas’”)
4 print(ascii([Link]()[0]))

locals() Returns local variables.


1 def query():
2 conn = [Link](”[Link]”)
3 print(locals())
4 [Link]()
5 query()

globals() Returns global variables.


1 conn = [Link](”[Link]”)
2 print(globals())
3 [Link]()

2.6 Input/Output and File Handling


input() Reads user input.
1 account = input(”Enter account name: ”)
2 with [Link](”[Link]”) as conn:
3 cursor = [Link]()
4 [Link](”SELECT amount FROM transactions WHERE
account_name = ?”, (account,))
5 print([Link]())

print() Prints output.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name, currency FROM accounts”)
4 print(*[Link](), sep=”\n”)

14
open() Opens a file.
1 with open(”[Link]”, ”w”) as f, [Link](”[Link]”)
as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts”)
4 [Link](”\n”.join(row[0] for row in [Link]()))

2.7 Code Execution and Compilation


compile() Compiles code.
1 code = compile(”with [Link](’[Link]’) as conn:
print([Link](’SELECT name FROM accounts’).fetchall())”, ””,
”exec”)
2 exec(code)

exec() Executes code.


1 code = ”with [Link](’[Link]’) as conn:
print([Link](’SELECT name FROM accounts’).fetchall())”
2 exec(code)

eval() Evaluates expression.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT COUNT(*) FROM transactions”)
4 expr = ”x * 2”
5 x = [Link]()[0]
6 print(eval(expr))

2.8 Memory and Resource Management


memoryview() Creates memory view.
1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 [Link](”SELECT name FROM accounts WHERE name = ’Abbas’”)
4 data = bytes([Link]()[0], ’utf-8’)
5 print(memoryview(data))

super() Accesses parent class.


1 class DBConnection([Link]):
2 def execute(self, *args):
3 print(”Custom execute”)
4 return super().execute(*args)
5 conn = DBConnection(”[Link]”)
6 print([Link](”SELECT name FROM accounts”).fetchall())
7 [Link]()

2.9 Debugging and Help


help() Displays help.
1 help([Link])

15
i mport( ) Imports module.
1 sqlite3 = __import__(”sqlite3”)
2 with [Link](”[Link]”) as conn:
3 print([Link](”SELECT name FROM accounts”).fetchall())

2.10 Miscellaneous
aiter(), anext() Asynchronous iteration.
1 import aiosqlite
2 async def async_fetch():
3 async with [Link](”[Link]”) as conn:
4 cursor = await [Link](”SELECT amount FROM transactions”)
5 async_iter = aiter(cursor)
6 print(await anext(async_iter))
7 import asyncio
8 [Link](async_fetch())

breakpoint() Enters debugger.


1 with [Link](”[Link]”) as conn:
2 cursor = [Link]()
3 breakpoint()
4 [Link](”SELECT name FROM accounts”)

classmethod() Defines class method.


1 class DB:
2 @classmethod
3 def connect(cls):
4 return [Link](”[Link]”)
5 conn = [Link]()
6 print([Link](”SELECT name FROM accounts”).fetchall())
7 [Link]()

staticmethod() Defines static method.


1 class DB:
2 @staticmethod
3 def get_version():
4 with [Link](”[Link]”) as conn:
5 return [Link](”SELECT
sqlite_version()”).fetchone()[0]
6 print(DB.get_version())

16

You might also like