Categories
Python Answers

How to return multiple values from a function with Python?

Sometimes, we want to return multiple values from a function with Python.

In this article, we’ll look at how to return multiple values from a function with Python.

How to return multiple values from a function with Python?

To return multiple values from a function with Python, we can return a tuple.

For instance, we write

def f():
    return True, False
x, y = f()

to define the f function that returns a tuple with True and False in it.

And then we unpack the returned values returned from f with

x, y = f()

Therefore x is True and y is False.

Conclusion

To return multiple values from a function with Python, we can return a tuple.

Categories
Python Answers

How to read and write CSV files with Python?

Sometimes, we want to read and write CSV files with Python.

In this article, we’ll look at how to read and write CSV files with Python.

How to read and write CSV files with Python?

To read and write CSV files with Python, we can use the csv module.

For instance, we can write database to a csv file with

data = [
    (1, "A towel,", 1.0),
    (42, " it says, ", 2.0),
    (1337, "is about the most ", -1),
]


with open("test.csv", "wt") as fp:
    writer = csv.writer(fp, delimiter=",")
    writer.writerows(data)

to call open to open a csv file to write to.

And then we call csv.write to get a writer object.

And then we call writerows with data to write the tuples into their own rows.

To read csv files, we write

with open("test.csv") as fp:
    reader = csv.reader(fp, delimiter=",", quotechar='"')
    data_read = [row for row in reader]

to call csv.reader with the csv file fp to get the reader object.

And then we use list comprehension to turn the rows from reader into a list.

Conclusion

To read and write CSV files with Python, we can use the csv module.

Categories
Python Answers

How to connect to a MySQL database in Python?

Sometimes, we want to connect to a MySQL database in Python.

In this article, we’ll look at how to connect to a MySQL database in Python.

How to connect to a MySQL database in Python?

To connect to a MySQL database in Python, we can use the MySQLdb package.

To install it, we run

pip install MySQL-python
pip install MySQL-python-connector

Then we use it by writing

import MySQLdb

db = MySQLdb.connect(host='localhost', user='john', passwd='pass',
                     db='jonhydb')

cur = db.cursor()

cur.execute('SELECT * FROM YOUR_TABLE_NAME')

for row in cur.fetchall():
    print row[0]

db.close()

to connect to the database with

db = MySQLdb.connect(host='localhost', user='john', passwd='pass',
                     db='jonhydb')

Then we get the cursor with

cur = db.cursor()

Then we make a query with

cur.execute('SELECT * FROM YOUR_TABLE_NAME')

Then we get the select results with fetchall.

And then we call close to close the database connection once we’re done.

Conclusion

To connect to a MySQL database in Python, we can use the MySQLdb package.

Categories
Python Answers

How to format a timedelta to a string with Python?

Sometimes, we want to format a timedelta to a string with Python.

In this article, we’ll look at how to format a timedelta to a string with Python.

How to format a timedelta to a string with Python?

To format a timedelta to a string with Python, we can call str.

For instance, we write

import datetime

start = datetime.datetime(2022, 2, 10, 14, 00)
end = datetime.datetime(2022, 2, 10, 16, 00)
delta = end - start

print str(delta)

to create a timedelta with

delta = end-start

Then we call str with delta to format timedelta delta into a string.

Conclusion

To format a timedelta to a string with Python, we can call str.

Categories
Python Answers

How to get the return value from a thread in Python?

Sometimes, we want to get the return value from a thread in Python.

In this article, we’ll look at how to get the return value from a thread in Python.

How to get the return value from a thread in Python?

To get the return value from a thread in Python, we can call apply_async and get.

For instance, we write

def foo(bar, baz):
  return 'foo' + baz

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)

async_result = pool.apply_async(foo, ('world', 'foo')) 

# do some other stuff in the main process

return_val = async_result.get()

to create a thread pool with

pool = ThreadPool(processes=1)

then we create a thread that runs foo with

async_result = pool.apply_async(foo, ('world', 'foo')) 

('world', 'foo') are the args for foo.

And then we call async_result.get to return the value returned from foo.

Conclusion

To get the return value from a thread in Python, we can call apply_async and get.