How to Draw a Triangle in Python Turtle

Python has a simple pen drawing library called turtle. Using simple movement commands, we can draw shapes using the python turtle library. When teaching python to children, turtle is a good library to introduce to get children excited about the language and its features.

The basic actions used in the following examples are,

  • Draw a line with pen – forward() command
  • Move without drawing – penup(), pendown() commands
  • Turn the pen to an angle – left(), right() commands

The following python program draws a simple equilateral triangle,

import turtle

board = turtle.Turtle()

board.forward(100) # draw base

board.left(120)
board.forward(100)

board.left(120)
board.forward(100)

turtle.done()

The following python program draws a right angled triangle,

import turtle

board = turtle.Turtle()

board.forward(100) # draw base

board.left(90)
board.forward(100)

board.left(135)
board.forward(142)

turtle.done()

The following python program draws a star shape by drawing two identical isosceles triangles,

import turtle

board = turtle.Turtle()

# first triangle for star
board.forward(100) # draw base

board.left(120)
board.forward(100)

board.left(120)
board.forward(100)

board.penup()
board.right(150)
board.forward(50)

# second triangle for star
board.pendown()
board.right(90)
board.forward(100)

board.right(120)
board.forward(100)

board.right(120)
board.forward(100)

turtle.done()

How to Calculate SHA256 Hash of a File in Python

SHA256 is a secure hash algorithm which creates a fixed length one way string from any input data. The algorithm is designed in such a way that two different input will practically never lead to the same hash value. This property can be used to verify the integrity of the data. If data and hash is obtained using different methods, we can verify the integrity of the data by computing the hash again and comparing it with the received hash.

SHA 256 hashing algorithm is widely used in security applications and protocols. The following python program computes the SHA256 hash value of a file. Note that the computed hash is converted to a readable hexadecimal string.

# Python program to find SHA256 hexadecimal hash string of a file
import hashlib

filename = input("Enter the input file name: ")
with open(filename,"rb") as f:
    bytes = f.read() # read entire file as bytes
    readable_hash = hashlib.sha256(bytes).hexdigest();
    print(readable_hash)

The above program may fail for large input files since we read the entire string to compute the hash. The following python program is an improved version capable of handling large files,

# Python program to find SHA256 hash string of a file
import hashlib

filename = input("Enter the input file name: ")
sha256_hash = hashlib.sha256()
with open(filename,"rb") as f:
    # Read and update hash string value in blocks of 4K
    for byte_block in iter(lambda: f.read(4096),b""):
        sha256_hash.update(byte_block)
    print(sha256_hash.hexdigest())

Here is a sample output from the above program,

Enter the input file name: sha256hash.py
5f22669f6f0ea1cc7e5af7c59712115bcf312e1ceaf7b2b005af259b610cf2da

How to Calculate Average of Numbers in Python

The average or arithmetic mean of a collection of numbers is calculated by adding the numbers and then dividing it with the number of numbers in the collection. The arithmetic mean is used in almost all scientific disciplines for analysis.

Consider the collection of numbers – 5,7,8,12. The arithmetic mean is (5+7+8+12)/4 = 8.

There are multiple approaches to finding average of numbers in python. Here are some examples,

1. Find average of numbers using for loop in python,

numbers_str = input("Enter numbers separated by spaces: ")
numbers = [float(num) for num in numbers_str.split()]

total = 0;
for x in numbers:
    total = total + x
print("Average of ", numbers, " is ", total / len(numbers))

2. Find average of numbers using built-in functions in python,

numbers_str = input("Enter numbers separated by spaces: ")
numbers = [float(num) for num in numbers_str.split()]

print("Average of ", numbers, " is ", sum(numbers) / len(numbers))

3. Find average of numbers using module functions in python,

import statistics
numbers_str = input("Enter numbers separated by spaces: ")
numbers = [float(num) for num in numbers_str.split()]

print("Average of ", numbers, " is ", statistics.mean(numbers))

Here is the output of the above programs in console,

python3 avg3.py
Enter numbers separated by spaces: 5 7 8 12
Average of  [5.0, 7.0, 8.0, 12.0]  is  8.0

How to Find Factorial in Python

The factorial of a number n is defined as the product of all integers from 1 to the number n. For example, the factorial of number 5 is 1*2*3*4*5 = 120. Factorial of number n is represented as n!. For larger values of n, the factorial value is very high. The factorial of zero by convention is defined as 1.

In mathematics, the factorial operation is used in many areas such as mathematical analysis and algebra. For example, n! represents all the permutations of a set of n objects. The notation n! was introduced by french mathematician Christian Kramp in 1808.

1. The following python program uses a simple for loop for computing factorial,

number = int(input("Please enter a number: "))
if number == 0:
    print("0!=", 1)
else:
    factorial = 1
    for i in range(1,number+1): # start from 1
        factorial = factorial*i
    print(number,"!=",factorial)

2. The following python program uses the built-in math module for calculating factorial,

import math
number = int(input("Please enter a number: "))
print(number,"!=",math.factorial(number))

3. The following python program uses a recursive function for calculating factorial. This is possible since n! = n*(n-1)!.

def factorial(n):
    if n <= 1:
        return 1
    else:
        return n * factorial(n - 1)


number = int(input("Please enter a number: "))
print(number, "!=", factorial(number))

Here is the sample output from the above programs,

python3 fact3.py
Please enter a number: 6
6 != 720

AES 256 Encryption and Decryption in Python

The following python program demonstrates how to perform AES 256 encryption and decryption using the pycrypto library. Please note that this example is written in Python 3.

First ensure that pycrypto library is installed on your system by running the following command,

pip3 install pycrypto

In the following python 3 program, we use pycrypto classes for AES 256 encryption and decryption. The program asks the user for a password (passphrase) for encrypting the data. This passphrase is converted to a hash value before using it as the key for encryption. The following program encrypts a sample text and then prints both the encrypted message and decrypted message on the console.

# AES 256 encryption/decryption using pycrypto library

import base64
import hashlib
from Crypto.Cipher import AES
from Crypto import Random

BLOCK_SIZE = 16
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]

password = input("Enter encryption password: ")


def encrypt(raw, password):
    private_key = hashlib.sha256(password.encode("utf-8")).digest()
    raw = pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw))


def decrypt(enc, password):
    private_key = hashlib.sha256(password.encode("utf-8")).digest()
    enc = base64.b64decode(enc)
    iv = enc[:16]
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc[16:]))


# First let us encrypt secret message
encrypted = encrypt("This is a secret message", password)
print(encrypted)

# Let us decrypt using our original password
decrypted = decrypt(encrypted, password)
print(bytes.decode(decrypted))

Here is the above program in action,

python3 aes_encryption.py
Enter encryption password: my password
b’sYjpPpTpPFSvdsvhTRQrNnyD669siUFtpziX8JrdFDF1zM9PF8kWbjDUnC9uS7lp’
This is a secret message

Note that the above program uses SHA256 algorithm to generate the key from the passphrase. If you want high level of security, this should be replaced with password based key derivation function PBKDF2. The following example uses the PBKDF2 to generate the key,

# AES 256 encryption/decryption using pycrypto library

import base64
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Protocol.KDF import PBKDF2

BLOCK_SIZE = 16
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]

password = input("Enter encryption password: ")


def get_private_key(password):
    salt = b"this is a salt"
    kdf = PBKDF2(password, salt, 64, 1000)
    key = kdf[:32]
    return key


def encrypt(raw, password):
    private_key = get_private_key(password)
    raw = pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw))


def decrypt(enc, password):
    private_key = get_private_key(password)
    enc = base64.b64decode(enc)
    iv = enc[:16]
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc[16:]))


# First let us encrypt secret message
encrypted = encrypt("This is a secret message", password)
print(encrypted)

# Let us decrypt using our original password
decrypted = decrypt(encrypted, password)
print(bytes.decode(decrypted))