top of page

Python Programming for Beginners

Python Programming for Beginners - 4 small projects



1. Calculator Github: https://github.com/jl3m3/Python-Programming-for-Beginners/blob/main/Python%20Programming%20for%20Beginners%20-%20Calculator.ipynb

def add(x,y):
    return x + y

def subtract(x,y):
    return x - y

def multiple(x,y):
    return x * y

def divide(x,y):
    return x / y

print("Enter 'A' for Addition.")
print("Enter 'S' for Subtract.")
print("Enter 'M' for Multiple.")
print("Enter 'D' for Divide.")


while True:
    choice = input('Enter choice: (A, S, M, D):')
    
    if choice.upper() in ('A', 'ADD', 'ADDITION', 'S', 'SUBTRACT', 'SUBTRACTION', 'M', 'MULTIPLY', 'MULTIPLICATION', 'D', 'DIVIDE', 'DIVISION'):
        num1 = float(input('Enter first number:'))
        num2 = float(input('Enter second number:'))

        if choice.upper() in ('A', 'ADD', 'ADDITION'):
            print(num1, '+', num2, '=', add(num1,num2))

        elif choice.upper() in ('S', 'SUBTRACT', 'SUBTRACTION'):
            print(num1, '-', num2, '=', subtract(num1,num2))

        elif choice.upper() in ('M', 'MULTIPLY', 'MULTIPLICATION'):
            print(num1, '*', num2, '=', multiple(num1,num2))

        elif choice.upper() in ('D', 'DIVIDE', 'DIVISION'):
            print(num1, '/', num2, '=', divide(num1,num2))

    else:
        print('Please input a correct choice')
        
    next_calculation = input("Want to do another calculation? (yes/no?):")
    if next_calculation.lower() in ('no', 'n','nope'):
        break
    

Enter 'A' for Addition. Enter 'S' for Subtract. Enter 'M' for Multiple. Enter 'D' for Divide. Enter choice: (A, S, M, D):m Enter first number:365 Enter second number:5 365.0 * 5.0 = 1825.0 Want to do another calculation? (yes/no?):yes Enter choice: (A, S, M, D):d Enter first number:1825 Enter second number:365 1825.0 / 365.0 = 5.0 Want to do another calculation? (yes/no?):no


2. Unit of Measurement Converter

Github: https://github.com/jl3m3/Python-Programming-for-Beginners/blob/main/Python%20Programming%20for%20Beginners%20-%20Unit%20of%20Measurement%20Convertet.ipynb

convert_from = input("Enter Starting Unit of Measurement(inches, feet, yards): ")

convert_to = input("Enter  Unit of Measurement to Convert to(inches, feet, yards): ")

number_of_inches = input("Enter Starting measurement in Inches: ")

number_of_feet = input("Enter Starting measurement in Feet: ")

number_of_yards = input("Enter Starting measurement in Yards: ")

Enter Starting Unit of Measurement(inches, feet, yards): inches Enter Unit of Measurement to Convert to(inches, feet, yards): feet Enter Starting measurement in Inches: 24 Enter Starting measurement in Feet: 3 Enter Starting measurement in Yards: 1


convert_from = input("Enter Starting Unit of Measurement (inches, feet, yards): ")
convert_to = input("Enter  Unit of Measurement to Convert to (inches, feet, yards): ")

# Convert Inches to feet or yards
if convert_from.lower() in ["inches", "in", "inch"]:
    number_of_inches = int(input("Enter Starting measurement in Inches: "))
    if convert_to.lower() in ["feet", "foot", "ft"]:
        print("Result: " + str(number_of_inches) + " Inches = " + str(round(number_of_inches / 12,2)) + " Feet")
    elif convert_to.lower() in ["yards", "yards", "yds", "yd"]:
        print("Result: " + str(number_of_inches) + " Inches = " + str(round(number_of_inches / 36,2)) + " Yards")
    else:
        print("Please Enter Inches, Feet or Yards")

# Convert Feet to Inches or Yards
elif convert_from.lower() in ["feet", "foot", "ft"]:
    number_of_feet = int(input("Enter Starting measurement in Feet: "))
    if convert_to.lower() in ["inches", "in", "inch"]:
        print("Result: " + str(number_of_feet) + " Feet = " + str(round(number_of_feet * 12)) + " Inches")
    elif convert_to.lower() in ["yards", "yards", "yds", "yd"]:
        print("Result: " + str(number_of_feet) + " Feet = " + str(round(number_of_feet / 3,2)) + " Yards")
    else:
        print("Please Enter Inches, Feet or Yards")

# Convert Yards to Inches or Feet
elif convert_from.lower() in ["yards", "yards", "yds", "yd"]:
    number_of_yards = int(input("Enter Starting measurement in Yards: "))
    if convert_to.lower() in ["inches", "in", "inch"]:
        print("Result: " + str(number_of_yards) + " Yards = " + str(round(number_of_yards * 36)) + " Inches")
    elif convert_to.lower() in ["feet", "foot", "ft"]:
        print("Result: " + str(number_of_yards) + " Yards = " + str(round(number_of_yards * 3)) + " Feet")
    else:
        print("Please Enter Inches, Feet or Yards")
        
# Else if not output
else:
    print("Please Enter Inches, Feet or Yards")

Enter Starting Unit of Measurement (inches, feet, yards): inch Enter Unit of Measurement to Convert to (inches, feet, yards): feet Enter Starting measurement in Inches: 100 Result: 100 Inches = 8.33 Feet


3. Automatic File Sorter

Github: https://github.com/jl3m3/Python-Programming-for-Beginners/blob/main/Python%20Programming%20for%20Beginners%20-%20Automatic%20File%20Sorter.ipynb



import os, shutil
path = r'C:\Users\repos\Data\AutoFileSorter\\'
os.listdir(path)

['CSVFile.csv', 'FakeFile.csv', 'FakeFile.txt', 'Max.png', 'NewFile.tsv', 'NewFile.txt', 'Rosie.png']


#os.makedirs(path + new_folder_name)
folder_names = ['CSV Files', 'Text Files', 'Image Files']

#C:\Users\repos\Data\AutoFileSorter'

for folder in folder_names:
    if not os.path.exists(path + folder):
        os.makedirs(path + folder)

os.listdir(path)

['CSV Files', 'CSVFile.csv', 'FakeFile.csv', 'FakeFile.txt', 'Image Files', 'Max.png', 'NewFile.tsv', 'NewFile.txt', 'Rosie.png', 'Text Files']



file_names = os.listdir(path)
for file in file_names:
    if ".csv" in file and not os.path.exists(path + "CSV Files\\" + file):
        shutil.move (path + file, path + "CSV Files\\" + file)
    elif ".txt" in file and not os.path.exists(path + "Text Files\\" + file):
        shutil.move (path + file, path + "Text Files\\" + file)
    elif ".png" in file and not os.path.exists(path + "Image Files\\" + file):
        shutil.move (path + file, path + "Image Files\\" + file)

path = r'C:\Users\repos\Data\AutoFileSorter\\'

folder_names = ['CSV Files', 'Text Files', 'Image Files']

for folder in folder_names:
    if not os.path.exists(path + folder):
        os.makedirs(path + folder)
        
file_names = os.listdir(path)

for file in file_names:
    if ".csv" in file and not os.path.exists(path + "CSV Files\\" + file):
        shutil.move (path + file, path + "CSV Files\\" + file)
    elif ".txt" in file and not os.path.exists(path + "Text Files\\" + file):
        shutil.move (path + file, path + "Text Files\\" + file)
    elif ".png" in file and not os.path.exists(path + "Image Files\\" + file):
        shutil.move (path + file, path + "Image Files\\" + file)

4. Web Scraper + Regular Expression Project

Github: https://github.com/jl3m3/Python-Programming-for-Beginners/blob/main/Python-programming-for-beginners%20-%20Web%20Scraper%20%2B%20Regular%20Expression%20Project.ipynb



from bs4 import BeautifulSoup
import requests
url = 'http://www.analytictech.com/mb021/mlk.htm'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html')
print(soup)

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <meta content="Microsoft FrontPage 4.0" name="GENERATOR"/> <title>Martin Luther King Jr.'s 1962 Speech</title> </head> <body alink="#FF0000" bgcolor="#FFFFFF" link="#0000FF" text="#000000" vlink="#551A8B"> <h1><font size="5">Transcript of speech by </font><br/> Dr. Martin Luther King Jr. <br/> August 28, 1963. Lincoln Memorial in Washington D.C. </h1> <hr color="#008080" noshade="" size="5"/> <p>I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation. </p> <p>Five score years ago a great American in whose symbolic shadow we stand today signed the Emancipation Proclamation. This momentous decree came as a great beckoning light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity. </p> <p>But one hundred years later the Negro is still not free. One hundred years later the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. </p> <p>One hundred years later the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. </p> <p>One hundred years later the Negro is still languishing in the comers of American society and finds himself in exile in his own land. </p> <p>We all have come to this hallowed spot to remind America of the fierce urgency of now. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to change racial injustice to the solid rock of brotherhood. Now is the time to make justice ring out for all of God's children. </p> <p>There will be neither rest nor tranquility in America until the Negro is granted citizenship rights. </p> <p>We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again we must rise to the majestic heights of meeting physical force with soul force. </p> <p>And the marvelous new militarism which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers have evidenced by their presence here today that they have come to realize that their destiny is part of our destiny. </p> <p>So even though we face the difficulties of today and tomorrow I still have a dream. It is a dream deeply rooted in the American dream. </p> <p>I have a dream that one day this nation will rise up and live out the true meaning of its creed: 'We hold these truths to be self-evident; that all men are created equal." </p> <p>I have a dream that one day on the red hills of Georgia the sons of former slaves and the sons of former slave owners will be able to sit together at the table of brotherhood. </p> <p>I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice. </p> <p>I have a dream that little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. </p> <p>I have a dream today. </p> <p>I have a dream that one day down in Alabama, with its vicious racists, with its Governor having his lips dripping with the words of interposition and nullification, one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers. </p> <p>I have a dream today. </p> <p>I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places plains, and the crooked places will be made straight, and before the Lord will be revealed, and all flesh shall see it together. </p> <p>This is our hope. This is the faith that I go back to the mount with. With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the genuine discords of our nation into a beautiful symphony of brotherhood. With this faith we will be able to work together, pray together; to struggle together, to go to jail together, to stand up for freedom forever, )mowing that we will be free one day. </p> <p>And I say to you today my friends, let freedom ring. From the prodigious hilltops of New Hampshire, let freedom ring. From the mighty mountains of New York, let freedom ring. From the mighty Alleghenies of Pennsylvania! </p> <p>Let freedom ring from the snow capped Rockies of Colorado! </p> <p>Let freedom ring from the curvaceous slopes of California! </p> <p>But not only there; let freedom ring from the Stone Mountain of Georgia! </p> <p>Let freedom ring from Lookout Mountain in Tennessee! </p> <p>Let freedom ring from every hill and molehill in Mississippi. From every mountainside, let freedom ring. </p> <p>And when this happens, when we allow freedom to ring, when we let it ring from every village and hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual, "Free at last! Free at last! Thank God almighty, we're free at last!" </p> </body> </html>


mlkj_speech = soup.find_all('p')
type(mlkj_speech)

bs4.element.ResultSet

speech_combined = [p.text for p in mlkj_speech]

print(speech_combined)

['I am happy to join with you today in what will go down in\r\nhistory as the greatest demonstration for freedom in the history\r\nof our nation. ', 'Five score years ago a great American in whose symbolic shadow\r\nwe stand today signed the Emancipation Proclamation. This\r\nmomentous decree came as a great beckoning light of hope to\r\nmillions of Negro slaves who had been seared in the flames of\r\nwithering injustice. It came as a joyous daybreak to end the long\r\nnight of their captivity. ', 'But one hundred years later the Negro is still not free. One\r\nhundred years later the life of the Negro is still sadly crippled\r\nby the manacles of segregation and the chains of discrimination. ', 'One hundred years later the Negro lives on a lonely island of\r\npoverty in the midst of a vast ocean of material prosperity. ', 'One hundred years later the Negro is still languishing in the\r\ncomers of American society and finds himself in exile in his own\r\nland. ', "We all have come to this hallowed spot to remind America of\r\nthe fierce urgency of now. Now is the time to rise from the dark\r\nand desolate valley of segregation to the sunlit path of racial\r\njustice. Now is the time to change racial injustice to the solid\r\nrock of brotherhood. Now is the time to make justice ring out for\r\nall of God's children. ", 'There will be neither rest nor tranquility in America until\r\nthe Negro is granted citizenship rights. ', 'We must forever conduct our struggle on the high plane of\r\ndignity and discipline. We must not allow our creative protest to\r\ndegenerate into physical violence. Again and again we must rise\r\nto the majestic heights of meeting physical force with soul\r\nforce. ', 'And the marvelous new militarism which has engulfed the Negro\r\ncommunity must not lead us to a distrust of all white people, for\r\nmany of our white brothers have evidenced by their presence here\r\ntoday that they have come to realize that their destiny is part\r\nof our destiny. ', 'So even though we face the difficulties of today and tomorrow\r\nI still have a dream. It is a dream deeply rooted in the American\r\ndream. ', 'I have a dream that one day this nation will rise up and live\r\nout the true meaning of its creed: \'We hold these truths to be\r\nself-evident; that all men are created equal." ', 'I have a dream that one day on the red hills of Georgia the\r\nsons of former slaves and the sons of former slave owners will be\r\nable to sit together at the table of brotherhood. ', 'I have a dream that one day even the state of Mississippi, a\r\nstate sweltering with the heat of injustice, sweltering with the\r\nheat of oppression, will be transformed into an oasis of freedom\r\nand justice. ', 'I have a dream that little children will one day live in a\r\nnation where they will not be judged by the color of their skin\r\nbut by the content of their character. ', 'I have a dream today. ', 'I have a dream that one day down in Alabama, with its vicious\r\nracists, with its Governor having his lips dripping with the\r\nwords of interposition and nullification, one day right there in\r\nAlabama little black boys and black girls will be able to join\r\nhands with little white boys and white girls as sisters and\r\nbrothers. ', 'I have a dream today. ', 'I have a dream that one day every valley shall be exalted,\r\nevery hill and mountain shall be made low, the rough places\r\nplains, and the crooked places will be made straight, and before\r\nthe Lord will be revealed, and all flesh shall see it together. ', 'This is our hope. This is the faith that I go back to the\r\nmount with. With this faith we will be able to hew out of the\r\nmountain of despair a stone of hope. With this faith we will be\r\nable to transform the genuine discords of our nation into a\r\nbeautiful symphony of brotherhood. With this faith we will be\r\nable to work together, pray together; to struggle together, to go\r\nto jail together, to stand up for freedom forever, )mowing that\r\nwe will be free one day. ', 'And I say to you today my friends, let freedom ring. From the\r\nprodigious hilltops of New Hampshire, let freedom ring. From the\r\nmighty mountains of New York, let freedom ring. From the mighty\r\nAlleghenies of Pennsylvania! ', 'Let freedom ring from the snow capped Rockies of Colorado! ', 'Let freedom ring from the curvaceous slopes of California! ', 'But not only there; let freedom ring from the Stone Mountain\r\nof Georgia! ', 'Let freedom ring from Lookout Mountain in Tennessee! ', 'Let freedom ring from every hill and molehill in Mississippi.\r\nFrom every mountainside, let freedom ring. ', 'And when this happens, when we allow freedom to ring, when we\r\nlet it ring from every village and hamlet, from every state and\r\nevery city, we will be able to speed up that day when all of\r\nGod\'s children, black men and white men, Jews and Gentiles,\r\nProtestants and Catholics, will be able to join hands and sing in\r\nthe words of the old Negro spiritual, "Free at last! Free at\r\nlast! Thank God almighty, we\'re free at last!" ']


type(speech_combined)

list


string_speech = ' '.join(speech_combined)
cleaned_string = string_speech.replace('\r\n', ' ')
import re
nopunt_speech = re.sub(r'[^\w\s]','', cleaned_string)
lower_speech = nopunt_speech.lower()
speech_broken_out = re.split(r'\s+', lower_speech)
import pandas as pd
df = pd.DataFrame(speech_broken_out).value_counts()
df

the 54 of 49 to 29 and 27 a 20 .. jews 1 joyous 1 judged 1 land 1 lookout 1 Name: count, Length: 323, dtype: int64


df.to_csv(r'C:\Users\repos\Data\AutoFileSorter\Webscraper + re project\MLKJ_speech_count.csv', header= ['Counts'], index_label=['Word'])








Project Gallery

  • LinkedIn
  • GitHub

©2023 by Janne Lemettinen.

bottom of page