Day 13: Global and local variables
Constants

Day 12: Local vs. Global Scope
Constants

import math

#global scope
best_friend = "Jeff"

# All upper case is a constant
PI= math.pi

class Constants:
def __init__(self):
self._pi = math.pi

@property
def pi(self):
return self._pi

"""
AttributeError: property 'pi' of 'Constants' object has no setter
without the setter below, you can't modify the value of PI

@pi.setter
def pi(self, value):
self._pi = value
"""


BING_URL = "www.bing.com"

"""
best practice is not to modify a global variable at a different
location. You don't want to call and modify it in a local scope

"""

def increase_enemies():
# global best_friend
"""
This will bring the global variable inside a local variable
"""
best_friend = "Bob"
print (f"best friend inside local scoope {best_friend}")


print("-----------------------------------")


increase_enemies()
print(f"best friend outside function {best_friend}")

print("-----------------------------------")

print(f"pi = {PI}")
print(f"Bing: {BING_URL}")

constants = Constants()
print(constants.pi)

#this throws an Attribute error seen above.
# constants.pi = 3.14
# print(constants.pi)

-----------------------------------
best friend inside local scoope Bob
best friend outside function Jeff
-----------------------------------
pi = 3.141592653589793
Bing: www.bing.com
3.141592653589793

Process finished with exit code 0

Day 16: Tables

from tabulate import tabulate
from prettytable import PrettyTable

print()
print("\t\t\tusing tabulate")
print()

all_data = [
[1,"Harry",88,""],
[2,"Hermione",95,""],
[3,"Ron",78,""],
[4,"Draco",75,""],
[5,"Neville",60,""]
]

# create header
headers = ["Roll \n Number","Student \n name","Marks", "Grade"]

print(tabulate(all_data, headers=headers, tablefmt="grid"))

row = 0
while True:
grade = all_data[row][2]

if grade >= 91:
all_data[row][3] = "Outstanding"
elif grade >= 81:
all_data[row][3] = "Exceeds Expectations"
elif grade >= 71:
all_data[row][3] = "Acceptable"
else:
all_data[row][3] = "Fail"
row +=1
if row == 5:
break
print(tabulate(all_data, headers=headers, tablefmt="grid"))

print("")
print("\t\t\tusing prettytable")
print("")

table = PrettyTable()
table.field_names = ["Roll Number","Student name","Marks"]
# table.align["Roll Number"] ="l" align table l, c, r
table.add_rows(
[
[1, "Harry", 88],
[2, "Hermione", 95],
[3, "Ron", 78],
[4, "Draco", 75],
[5, "Neville", 60]
]
)

print(table)
row = 0
list_grade = []
while True:
grade = all_data[row][2]

if grade >= 91:
list_grade.append("Outstanding")
elif grade >= 81:
list_grade.append("Exceeds Expectations")
elif grade >= 71:
list_grade.append("Acceptable")
else:
list_grade.append("Fail")
row +=1
if row == 5:
break

table.add_column ("Grade",list_grade)

# print entire table
print(table)

# print second row of data
print(table[1])
 +-----------+------------+---------+---------+
| Roll       | Student | Marks | Grade |
| Number | name    |            |           |
+===========+============+=========+=========+
| 1           | Harry     | 88       |           |
+-----------+------------+---------+---------+
| 2           | Hermione | 95     |           |
+-----------+------------+---------+---------+
| 3           | Ron          | 78     |           |
+-----------+------------+---------+---------+
| 4           | Draco      | 75      |            |
+-----------+------------+---------+---------+
| 5           | Neville     | 60      |             |
+-----------+------------+---------+---------+
  +-----------+------------+---------+--------------+
| Roll       | Student | Marks | Grade |
| Number | name    |            |            |
+===========+============+=========+==============+
| 1           | Harry     | 88       | Exceeds |
|             |           |          | Expectations |
+-----------+------------+---------+--------------+
| 2           | Hermione | 95     | Outstanding |
+-----------+------------+---------+--------------+
| 3           | Ron          | 78     | Acceptable |
+-----------+------------+---------+--------------+
| 4           | Draco      | 75      | Acceptable |
+-----------+------------+---------+--------------+
| 5           | Neville     | 60      | Fail            |
+-----------+------------+---------+--------------+            
+-------------+--------------+-------+----------------------+

| Roll Number | Student name | Marks |        Grade         |

+-------------+--------------+-------+----------------------+

|      1      |    Harry     |   88  | Exceeds Expectations |

|      2      |   Hermione   |   95  |     Outstanding      |

|      3      |     Ron      |   78  |      Acceptable      |

|      4      |    Draco     |   75  |      Acceptable      |

|      5      |   Neville    |   60  |         Fail         |

+-------------+--------------+-------+----------------------+

+-------------+--------------+-------+-------------+

| Roll Number | Student name | Marks |    Grade    |

+-------------+--------------+-------+-------------+

|      2      |   Hermione   |   95  | Outstanding |

+-------------+--------------+-------+-------------+  




Process finished with exit code 0

Day 17: Classes

class User:

#method
def __init__(self, user_id, username):
print("new user being created")
self.id = user_id
self.username = username
self.followers = 0
self.following = 0

def follow(self, user):
user.followers += 1
self.following += 1


user_1 = User("001", "Bob")
print("------")
print("user id: " + user_1.id)
print("name: " + user_1.username)
print(f"Folowers: {user_1.followers} ")
print(f"Following: {user_1.following} ")

user_2 = User("002", "Charlie")
user_1.follow(user_2)

print("------")
print("user id: " + user_1.id)
print("name: " + user_1.username)
print(f"Folowers: {user_1.followers} ")
print(f"Following: {user_1.following} ")
print("------")
print("user id: " + user_2.id)
print("name: " + user_2.username)
print(f"Folowers: {user_2.followers} ")
print(f"Following: {user_2.following} ")
C:\Users\netadmin\PycharmProjects\Day17\.venv\Scripts\python.exe C:\Users\netadmin\PycharmProjects\Day17\main.py 
new user being created
------
user id: 001
name: Bob
Folowers: 0
Following: 0
new user being created
------
user id: 001
name: Bob
Folowers: 0
Following: 1
------
user id: 002
name: Charlie
Folowers: 1
Following: 0

Process finished with exit code 0

Day 18: Turtle

Square
Rectangle
Circle
Dotted line square

import turtle
from turtle import Turtle, Screen

timmy_the_turtle = Turtle()
timmy_the_turtle.shape("turtle")
timmy_the_turtle.color("red")

# draw square
x = 0
while True:
timmy_the_turtle.forward(100)
timmy_the_turtle.right(90)
x += 1
if x > 3:
break

x = 0
while True:
# draw rectangle
if x % 2 == 0:
timmy_the_turtle.forward(300)
timmy_the_turtle.right(90)
if x % 2 == 1:
timmy_the_turtle.forward(150)
timmy_the_turtle.right(90)
x += 1
if x > 3:
break

turtle.color("coral")
turtle.circle(200)



timmy_the_turtle.left(90)
timmy_the_turtle.forward(20)
x = 0
y = 0
while True:
# dotted line square
if x % 2 == 0:
timmy_the_turtle.pendown()
timmy_the_turtle.forward(10)

if x % 2 == 1:
timmy_the_turtle.penup()
timmy_the_turtle.forward(10)
x += 1
if x > 30:
timmy_the_turtle.right(90)
x = 0
y += 1
if y > 3:
break





screen = Screen()
screen.exitonclick()

Create, Read, Write and Append to a file

import os

current_directory = os.getcwd()
print(f"Current path: {current_directory}")


with open("my_file.txt") as file:
contents = file.read()
print(contents)

# append writes to the bottom of the file.
with open("my_file.txt", mode="a") as file:
file.write("\nNew text.")

with open("my_file.txt") as file:
contents = file.read()
print(contents)

# this will clear the file and write new text
with open("my_file.txt", mode="w") as file:
file.write("\nNew text.")

with open("my_file.txt") as file:
contents = file.read()
print(contents)

# create a new subdirectory under current working path
new_dir = "\\subdir"
subdirectory_path = current_directory + new_dir

try:
os.makedirs(subdirectory_path, exist_ok=True)
print(f"Subdirectory '{subdirectory_path}' created successfully.")
except OSError as e:
print(f"Error creating subdirectory: {e}")

new_dir = "subdir"
new_directory_path = os.path.join(current_directory, new_dir)
print(f"new path: {new_directory_path}")
os.chdir(new_directory_path)
print(f"Current Working Directory: {os.getcwd()} ")


# this will clear the file and write new text
with open("new_myfile.txt", mode="a") as file:
file.write("\n Created in \\subdir\\new_myfile.txt.")


with open("new_myfile.txt") as file:
contents = file.read()
print(contents)
C:\Users\netadmin\PycharmProjects\ReadWriteFile\.venv\Scripts\python.exe C:\Users\netadmin\PycharmProjects\ReadWriteFile\main.py 
Current path: C:\Users\netadmin\PycharmProjects\ReadWriteFile

New text.

New text.
New text.

New text.
Subdirectory 'C:\Users\netadmin\PycharmProjects\ReadWriteFile\subdir' created successfully.
new path: C:\Users\netadmin\PycharmProjects\ReadWriteFile\subdir
Current Working Directory: C:\Users\netadmin\PycharmProjects\ReadWriteFile\subdir

Created in \subdir\new_myfile.txt.

Process finished with exit code 0