07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 1 ■ Introduction to Cryptography and Python 27

functions is that if you decide you need to change the script, you can change it

in one place and not have to search for other areas in which you performed the

same logic. This will help in both troubleshooting and code maintenance. We

will be using functions quite a bit throughout this book.

In Python, you can declare some arguments as optional. Examine the following

segment of code, paying attention to the third and fourth arguments:

def func(a, b, c=10, d=100):

! print (a, b, c, d)

>>> func(1,2)

1 2 10 100

>>> func(1,2,3,4)

1,2,3,4

Something to watch out for is that all functions have a return value even if

you do not provide a return line inside the code. Functions that do not provide

a return line will return the special value of None. Note also that, unlike other

languages, Python does not provide a way to overload a method, so you are not

allowed to have two different functions with the same name and a different

list of arguments. Some benefits to functions include that they can be used as

arguments to functions, return values of functions, and be assigned to variables,

and may contain parts of tuples, lists, and other objects.

Downloading Files Using Python

You can download files and content in Python in a number of ways. One of the

preferred ways in Python 3 is to use the requests module. The get method of

the requests module is used to download the file contents in binary format. You

can then use the open method to open a file on your system. Here’s an example

of downloading files using the requests module:

>>> import requests

>>> print('Beginning file download with requests')

>>> url = 'https://raw.githubusercontent.com/noidentity29/

AppliedCryptoPython/master/secret.txt'

>>> r = requests.get(url)

>>>

>>> # Windows Path - C:\Users\ShannonBray\Downloads\

>>> with open('/Users/ShannonBray/Downloads/secrets.txt', 'wb') as f:

>>> f.write(r.content)

>>>

>>> # Retrieve HTTP meta-data

>>> print(r.status_code)

>>> print(r.headers['content-type'])

>>> print(r.encoding)

>>>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!