Output

import numpy as np
import pandas as pd
import pandas_datareader.data as web
# Get stock data  
all_data = {ticker: web.DataReader(ticker,'stooq')
           for ticker in ['AAPL', 'NVDA', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'QCOM', 'SBUX']}
# Extract the 'Adjusted Closing Price'
price = pd.DataFrame({ticker: data['Close']
                     for ticker, data in all_data.items() })
import matplotlib.pyplot as plt
fig1, axes1 = plt.subplots(2,4, sharex = True, sharey = True)

axes1[0,0].plot(price['AAPL'],'-', color = 'gold', label = 'AAPL')
axes1[0,0].legend(loc = 'best')

axes1[0,1].plot(price['NVDA'],'-', color = 'red', label = 'NVDA')
axes1[0,1].legend(loc = 'best')

axes1[0,2].plot(price['MSFT'],'-', color = 'blue', label = 'MSFT')
axes1[0,2].legend(loc = 'best')

axes1[0,3].plot(price['TSLA'],'-', color = 'royalblue', label = 'TSLA')
axes1[0,3].legend(loc = 'best')

axes1[1,0].plot(price['AMZN'],'-', color = 'black', label = 'AMZN')
axes1[1,0].legend(loc = 'best')

axes1[1,1].plot(price['NFLX'],'-', color = 'purple', label = 'NFLX')
axes1[1,1].legend(loc = 'best')

axes1[1,2].plot(price['QCOM'],'-', color = 'pink', label = 'QCOM')
axes1[1,2].legend(loc = 'best')

axes1[1,3].plot(price['SBUX'],'-', color = 'green', label = 'SBUX')
axes1[1,3].legend(loc = 'best') 

# fig1.savefig('stocks1.pdf')
<matplotlib.legend.Legend at 0x11c9e22d0>

png

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(price['AAPL'], '-',color = 'gold', label = 'AAPL')
plt.plot(price['NVDA'],'-', color = 'red', label = 'NVDA')
plt.plot(price['MSFT'],'-', color = 'blue', label = 'MSFT')
plt.plot(price['TSLA'],'-', color = 'royalblue', label = 'TSLA')
plt.plot(price['AMZN'],'-', color = 'black', label = 'AMZN')
plt.plot(price['NFLX'],'-', color = 'purple', label = 'NFLX')
plt.plot(price['QCOM'],'-', color = 'pink', label = 'QCOM')
plt.plot(price['SBUX'],'-', color = 'green', label = 'SBUX')
ax.legend(loc = 'best')
ax.set_ylabel("Price", fontsize=12)
ax.set_xlabel("Year", fontsize=12)
ax.set_title("Sample Portfolio", fontsize = 16)
Text(0.5, 1.0, 'Sample Portfolio')

png

Output and Input

import getpass, sys

def question_and_answer(prompt):
    print("Question: " + prompt)
    msg = input()
    print("Answer: " + msg)


def question_with_response(prompt):
    print("Question: " + prompt)
    msg = input()
    return msg

questions = 10
correct = 0

print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_and_answer("Are you ready to take a test?")

rsp = question_with_response("What does “www” stand for in a website browser?")
if rsp == "World Wide Web":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

rsp = question_with_response("How long is an Olympic swimming pool (in meters)")
if rsp == "50":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

rsp = question_with_response("What geometric shape is generally used for stop signs?")
if rsp == "Octagon":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Which animal can be seen on the Porsche logo?")
if rsp == "Horse":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Who was the first woman to win a Nobel Prize (in 1903)?")
if rsp == "Marie Curie":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Worship of Krishna is observed by which Religious Faith?")
if rsp == "Hinduism":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("What happned on Sept 11, 2001")
if rsp == "Terrorists attacked the World Trade Centers":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Who invented French fries?")
if rsp == "Belgium":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Whats the game plan?")
if rsp == "I hate my life":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Which side of Abundante is better?")
if rsp == "Right side":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))
Hello, tanayshah running /usr/local/bin/python3
You will be asked 10 questions.
Question: Are you ready to take a test?
Answer: Yes
Question: What does “www” stand for in a website browser?
World Wide Web is correct!
Question: How long is an Olympic swimming pool (in meters)
50 is correct!
Question: What geometric shape is generally used for stop signs?
Octagon is correct!
Question: Which animal can be seen on the Porsche logo?
Horse is correct!
Question: Who was the first woman to win a Nobel Prize (in 1903)?
Marie Curie is correct!
Question: Worship of Krishna is observed by which Religious Faith?
Hinduism is correct!
Question: What happned on Sept 11, 2001
Terrorists attacked the World Trade Centers is correct!
Question: Who invented French fries?
Belgium is correct!
Question: What is the common fungi?
Mushrooms is correct!
Question: Which side of Abundante is better?
Right side is correct!
tanayshah you scored 10/10

Programs with lists

import numpy as np
import pandas as pd
import pandas_datareader.data as web
# Get stock data  
all_data = {ticker: web.DataReader(ticker,'stooq')
           for ticker in ['AAPL', 'NVDA', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'QCOM', 'SBUX']}
# Extract the 'Adjusted Closing Price'
price = pd.DataFrame({ticker: data['Close']
                     for ticker, data in all_data.items() })
import matplotlib.pyplot as plt
colors = ['gold', 'red', 'blue', 'royalblue', 'black', 'purple', 'pink', 'green']

fig6 = plt.figure(figsize=(6, 6))
axes6 = fig6.add_subplot(1, 1, 1)

# Create the bar chart with custom colors
priceSTD = price.std()
priceSTD.plot(ax=axes6, kind="bar", rot=45, color=colors)

axes6.set_ylabel("STD", fontsize=12)
axes6.set_xlabel("Stocks", fontsize=12)
axes6.set_title("STD of all 8 stocks", fontsize=20)

plt.show()

#fig6.savefig('stocks4.png')

png

We create and use a list called ‘colors’ which dictates the colors of each of the bars in the graph. Without the list all 8 graphs would be one color, but with it we get that APPL is gold, NVDA is red, and so on and so forth.

priceCORR = price.corr()

fig, ax = plt.subplots(figsize=(10, 6))
priceCORR.plot(kind='bar', stacked=True, ax=ax, color=colors)
ax.set_ylabel("Correlation", fontsize=12)
ax.set_xlabel("Stocks", fontsize=12)
ax.set_title("Correlation between Stocks", fontsize=16)

plt.legend(title='Stocks', loc='upper right')
plt.xticks(rotation=0)  # Rotate x-axis labels if needed
plt.show()

#fig.savefig('stocks5.png')

png

Since the list ‘color’ is already defined in the previous cell we don’t have to redefine it in order to reuse it.

Program with a dictionary

# Command: 
personal_data = {'age': 30, 'pets': [0, 1, 2], 'drinks': ['coffee', 'tea']}
personal_data
{'age': 30, 'pets': [0, 1, 2], 'drinks': ['coffee', 'tea']}
# Command: 
personal_data.keys()
dict_keys(['age', 'pets', 'drinks'])
# Command: 
personal_data.values()
dict_values([30, [0, 1, 2], ['coffee', 'tea']])
# Command: 
type(personal_data)
dict
# Command: 
personal_data['age']
30
# Command: 
personal_data['pets']
[0, 1, 2]
# Command: 
personal_data['drinks']
['coffee', 'tea']
# Command: 
personal_data['age'] = 40
personal_data
{'age': 40, 'pets': [0, 1, 2], 'drinks': ['coffee', 'tea']}
# Command: 
personal_data['sport'] = 'Chess'
personal_data
{'age': 40, 'pets': [0, 1, 2], 'drinks': ['coffee', 'tea'], 'sport': 'Chess'}
# Command: 
del personal_data['sport']
personal_data
{'age': 40, 'pets': [0, 1, 2], 'drinks': ['coffee', 'tea']}

Program with Iteration

Write a for loop that sums up integers in the list below, and skips None values.

sequence = [None, 2, 3, 6, None, 8, None, 11]
sequence = [None, 12, 832, 2, None, 2, None, 11]
total = 0
for i in range(0,len(sequence)): 
    if type(sequence[i]) == int: 
        total += sequence[i]
total
859

Write a while-loop that prints a number as long as it is an even number less than 10, but otherwise, prints it is not less than 10. For example, your output should look like this:

0 is even and less than 10
2 is even and less than 10
.
.
.
10 is not less than 10
number = 0

while number <= 10:
    if number % 2 == 0 and number < 10:
        print(f"{number} is even and less than 10")
    else:
        print(f"{number} is not less than 10")
    number += 2

0 is even and less than 10
2 is even and less than 10
4 is even and less than 10
6 is even and less than 10
8 is even and less than 10
10 is not less than 10

Program with math

def annuity(rate, C, months, rate_check, month_check): 
    if str(rate_check) == "percent": 
        rate=rate/100
        
    if str(month_check) == 'year': 
        months = months*12
        
    PV = (C/rate)*(1-(1/(1+rate)**months))
    annuity = PV + C
    print("The annuity is: {:.2f}$".format(annuity))
    
def perpetuity(rate, C, rate_check): 
        if str(rate_check) == "percent": 
            rate = rate/100
            
        PV = C/rate
        print("The perpetuity of your deposit is: {:.2f}$".format(PV))
        
def futureValue(rate, PV, months, rate_check, month_check):
        if str(rate_check) == "percent": 
            rate = rate/100
        
        if str(month_check) == "year": 
            months = months*12
        
        FV = float(PV)*(1+float(rate))**float(months)
        print("The future value of your deposit is: {:.2f}$".format(FV))
    
def presentValue(rate, FV, months, rate_check, month_check): 
        if str(rate_check) == "percent": 
            rate = rate/100
        
        if str(month_check) == "year": 
            months = months*12
            
        PV = float(FV)/((1+float(rate))**float(months))
        print("The present value of your deposit is: {:.2f}$".format(PV))
annuity(0.12, 1000, 12, "NA", 'months')
The annuity is: 7194.37$
perpetuity(12, 1000, 'percent')
The perpetuity of your deposit is: 8333.33$
futureValue(0.12, 1000, 12, 'NA', 'months')
The future value of your deposit is: 3895.98$
presentValue(12, 1000, 1, 'percent', 'year')
The present value of your deposit is: 256.68$

Program with selection/condition

class Health: 
    weight = 0
    height = 0
    age = 0
    
    def __init__(measurements, weight, height, gender, age): 
        measurements.weight = weight
        measurements.height = height
        measurements.gender = gender
        measurements.age = age
        
    def bmi(measurements):
        bmi_temp = (measurements.weight/(measurements.height**2))*703
        if bmi_temp < 18.5:
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Underweight")
        elif 18.5 < bmi_temp < 24.9:
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Normal")
        elif 25 < bmi_temp < 29.9:
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Overweight")
        else:    
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Obese")
       # return (measurements.weight/(measurements.height**2))*703
    
    def bmr(measurements):
        bmr_temp_M = 66 + (6.3*measurements.weight) + (12.9*measurements.height) - (6.8*measurements.age)
        bmr_temp_F = 655 + (4.3*measurements.weight) + (4.7*measurements.height) - (4.7*measurements.age)
        if measurements.gender == "M":
            print(f"Based on your BMR = {bmr_temp_M:.2f} here are your recommended caloric intakes per activity level:")
            print(f"Sedentary: little or no exercise = {1.2*bmr_temp_M:.2f} Calories")
            print(f"Lightly Active: exercise/sports 1-3 days/week = {1.375*bmr_temp_M:.2f} Calories")
            print(f"Moderately Active: exercise/sports 3-5 days/week = {1.55*bmr_temp_M:.2f} Calories")
            print(f"Very Active: exercise/sports 6-7 days/week = {1.725*bmr_temp_M:.2f} Calories")
            print(f"Extra Active: exercise daily, or physical job = {1.9*bmr_temp_M:.2f} Calories")
        else:
            print(bmr_temp_F)
            print(f"Based on your BMR = {bmr_temp_F:.2f}, here are your recommended caloric intakes per activity level:")
            print(f"Sedentary: little or no exercise = {1.2*bmr_temp_F:.2f} Calories")
            print(f"Lightly Active: exercise/sports 1-3 days/week = {1.375*bmr_temp_F:.2f} Calories")
            print(f"Moderately Active: exercise/sports 3-5 days/week = {1.55*bmr_temp_F:.2f} Calories")
            print(f"Very Active: exercise/sports 6-7 days/week = {1.725*bmr_temp_F:.2f} Calories")
            print(f"Extra Active: exercise daily, or physical job = {1.9*bmr_temp_F:.2f} Calories")
       
vitals = Health(130, 70.8,"F",48)
vitals.bmi()
Based on your BMI = 18.23, you are considered Underweight
vitals.bmr()
1321.1599999999999
Based on your BMR = 1321.16, here are your recommended caloric intakes per activity level:
Sedentary: little or no exercise = 1585.39 Calories
Lightly Active: exercise/sports 1-3 days/week = 1816.59 Calories
Moderately Active: exercise/sports 3-5 days/week = 2047.80 Calories
Very Active: exercise/sports 6-7 days/week = 2279.00 Calories
Extra Active: exercise daily, or physical job = 2510.20 Calories

Program with purpose

# Function to calculate tax based on income
def calculate_tax(income):
    if income <= 10000:
        tax = income * 0.10
    elif income <= 50000:
        tax = 10000 * 0.10 + (income - 10000) * 0.20
    else:
        tax = 10000 * 0.10 + 40000 * 0.20 + (income - 50000) * 0.30
    return tax

# Input the income
income = float(input("Enter your income: "))

# Calculate the tax
tax = calculate_tax(income)

# Display the tax amount
print(f"Your tax amount is: ${tax:.2f}")

Your tax amount is: $24000.00