mytuple:(str,int,str) = ("apple", 3, "cherry")
print(mytuple[1]*4)
from turtle import Turtle, Screen
tim = Turtle()
screen = Screen()
def moveForward():
tim.forward(10);
screen.listen()
# use function as a param :
screen.onkey(key="space", fun=moveForward) # trigger function when key.
screen.exitonclick()
class Animal:
def __init__(self):
print("animal created")
def cry(self):
print("cry")
class Bird(Animal):
def __init__(self, eyes):
super().__init__()
self.num = eyes
print(f"bird created with {self.num} eyes")
# methode override
def cry(self):
print("chirp")
class Example:
# constructor overloading based on args
def __init__(self, *args):
# if args are more than 1 sum of args
if len(args) > 1:
self.answer = 0
for i in args:
self.answer += i
# if arg is an integer square the arg
elif isinstance(args[0], int):
self.answer = args[0] * args[0]
# if arg is string Print with hello
elif isinstance(args[0], str):
self.answer = "Hello! " + args[0] + "."
e1 = Example(1, 2, 3, 6, 8)
print("Sum :", e1.answer)
e2 = Example(6)
print("Square :", e2.answer)
e3 = Example("Python")
print("String :", e3.answer)
class MyClass:
def __init__(self, edate=None, fdate=""):
if edate:
print("Constructors", edate)
else:
print("Default Constructor")
obj1 = MyClass("01-Dec-2021")
obj2 = MyClass()
class Book:
def __init__(self, title: str, author: str, pages: int):
self.title = title
self.author = author
self.pages = pages
@classmethod
def from_json(cls, book_as_json: str) -> 'Book':
book = json.loads(book_as_json)
return cls(title=book['title'], author=book['author'], pages=book['pages'])
class Book:
def __init__(self, title: str, author: str, pages: int):
self.title = title
if author is None:
self.author = "default"
self.pages = "default"
return
self.author = author
self.pages = pages
@classmethod
def from_json(cls, title: str) -> 'Book':
return cls(title=title, author=None, pages=None)
file = open("my_file.txt")
contents = file.read()
print(contents)
file.close() # free up resources
# shorter code ver :
with open("my_file.txt") as file:
contents = file.read()
print(contents)
# overwrite :
with open("my_file.txt", mode = "w") as file:
file.write("this was written by python code")
# mode="a" to append text
# if the file doesn't exist it will have been created by writing to it
f = open("file.txt", "r") # return list of lines
print(f.readlines())
# trim string from spaces or new lines (/n):
txt = " hello "
x = txt.strip()
PLACEHOLDER = "[name]"
with open("./Input/Names/invited_names.txt") as names_file:
names = names_file.readlines()
with open("./Input/Letters/starting_letter.txt") as letter_file:
letter_contents = letter_file.read()
for name in names:
stripped_name = name.strip()
new_letter = letter_contents.replace(PLACEHOLDER, stripped_name)
with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.txt", mode="w") as completed_letter:
completed_letter.write(new_letter)
with open("weather_data.csv") as file:
contents = file.readlines()
for line in contents:
print(line)
import csv
with open("weather_data.csv") as file:
data = csv.reader(file)
temprature=[]
# iterate data of csv file :
for row in data:
if row[1] != "temp":
temprature.append(int(row[1]))
print(temprature)
import pandas
# ^ will aks you to auto install
data = pandas.read_csv("weather_data.csv")
# get var data type :
print(type(data))
import pandas
# ^ will aks you to auto install
data = pandas.read_csv("weather_data.csv")
data_dict = data.to_dict() # convert to dictionary
print(data_dict)
# data["temp"] = data.temp (attribute auto generated)
temp_list = data.temp.to_list()
print(temp_list)
print(data["temp"].max())
import pandas
data = pandas.read_csv("weather_data.csv")
# get data in row
print(data[data.day == "Monday"])
# get row with max column value
print(data[data.temp == data.temp.max()])
# get cell without index garbage number
monday = data[data.day == "Monday"]
# data.day = data["day"]
s = monday["condition"].to_string()
print(s[s.find(" "):].strip())
import pandas
data = pandas.read_csv("weather_data.csv")
# get data in row
print(data[data.day == "Monday"])
# get row with max column value
print(data[data.temp == data.temp.max()])
# get cell without index garbage number
monday = data[data.day == "Monday"]
print(monday["condition"].item())
import pandas
# create a panda table :
data_dict = {"students":["s1","s2","s3"],
"scores":[80,90,87]}
data = pandas.DataFrame(data_dict) # can accept lists as well
print(data)
data.to_csv("created_csv.csv") # create new csv file index=False to save without an index
# list comprehension aka lambda expressions
numbers = [1, 2, 3]
new_list = [n + 1 for n in numbers]
print(new_list) # prints 2,3,4
# example 2 string to list with word to letter list
name = "magneto"
letters_list = [letter for letter in name]
print(letters_list) # ['m', 'a', 'g', 'n', 'e', 't', 'o']
# example 3 range
range_list = [num * 3 for num in range(1, 5)]
print(range_list) # [3, 6, 9, 12]
# example 4 conditional add to list
names = ["magneto", "beast", "kitty", "jin", "bobby", "wolverine"]
short_names = [item for item in names if len(item) < 6]
print(short_names) # ['beast', 'kitty', 'jin', 'bobby']
# dictionary comprehension aka lambda expressions
names = ["magneto", "beast", "kitty", "jin", "bobby", "wolverine"]
student_scores = {student: 90 for student in names}
print(student_scores) # {'magneto': 90, 'beast': 90, 'kitty': 90, 'jin': 90, 'bobby': 90, 'wolverine': 90}
# example 2
scores2 = {'magneto': 90, 'beast': 19, 'kitty': 5, 'jin': 70, 'bobby': 60, 'wolverine': 50}
passed_students = {key: value for (key, value) in scores2.items() if value > 50}
print(passed_students) # {'magneto': 90, 'jin': 70, 'bobby': 60}
# dataframe looping
import pandas
student_dict = {
"student": ["magneto", "beast", "kitty"],
"score": [56, 76, 99]
}
student_data_frame = pandas.DataFrame(student_dict)
# loop dataframe
for (index, row) in student_data_frame.iterrows():
# print(row)
print(row.student) # magneto /n beast /n kitty
# print(row.score)
# nato dictionary out of csv file using list and dictionary comprehension
import pandas
data = pandas.read_csv("nato_phonetic_alphabet.csv") # form dataframe
nato_dict = {row.letter: row.code for (index, row) in data.iterrows()} # convert data frame to dictionary
word = input("enter word\n").upper() # python input from user
output_list = [nato_dict[letter] for letter in word] # itterate letters in string to form a list
print(output_list) # output for magneto ['Mike', 'Alfa', 'Golf', 'November', 'Echo', 'Tango', 'Oscar']
# varargs example
def add(*N):
sum1 = 0
# iterate tuple varargs
for num in N:
sum1 += num
return sum1
print(add(1, 7, 2, 4))
# varargs example 2
def add(*N):
return N[1]
print(add(1, 7, 2, 4)) # return 7
import tkinter
# window GUI for the program
window = tkinter.Tk()
window.title("GUI test")
window.minsize(width=500, height=300)
# add a label :
lbl1 = tkinter.Label(text="label1", font=("Times", 24, "bold"))
lbl1.pack() # stick the label view on
lbl1["text"] = "txt changed" # change attribute
lbl1.config(bg="gray51", fg="white")
window.mainloop() # keeps the window alive
https://docs.python.org/3/library/tkinter.html#the-packer
https://www.codegrepper.com/code-examples/python/tkinter+change+label+text+color
from tkinter import *
#Creating a new window and configurations
window = Tk()
window.title("Widget Examples")
window.minsize(width=500, height=500)
#Labels
label = Label(text="This is old text")
label.config(text="This is new text")
label.pack()
#Buttons
def action():
print("Do something")
#calls action() when pressed
button = Button(text="Click Me", command=action)
button.pack()
#Entries
entry = Entry(width=30)
#Add some text to begin with
entry.insert(END, string="Some text to begin with.")
#Gets text in entry
print(entry.get())
entry.pack()
#Text
text = Text(height=5, width=30)
#Puts cursor in textbox.
text.focus()
#Adds some text to begin with.
text.insert(END, "Example of multi-line text entry.")
#Get's current value in textbox at line 1, character 0
print(text.get("1.0", END))
text.pack()
#Spinbox
def spinbox_used():
#gets the current value in spinbox.
print(spinbox.get())
spinbox = Spinbox(from_=0, to=10, width=5, command=spinbox_used)
spinbox.pack()
#Scale
#Called with current scale value.
def scale_used(value):
print(value)
scale = Scale(from_=0, to=100, command=scale_used)
scale.pack()
#Checkbutton
def checkbutton_used():
#Prints 1 if On button checked, otherwise 0.
print(checked_state.get())
#variable to hold on to checked state, 0 is off, 1 is on.
checked_state = IntVar()
checkbutton = Checkbutton(text="Is On?", variable=checked_state, command=checkbutton_used)
checked_state.get()
checkbutton.pack()
#Radiobutton
def radio_used():
print(radio_state.get())
#Variable to hold on to which radio button value is checked.
radio_state = IntVar()
radiobutton1 = Radiobutton(text="Option1", value=1, variable=radio_state, command=radio_used)
radiobutton2 = Radiobutton(text="Option2", value=2, variable=radio_state, command=radio_used)
radiobutton1.pack()
radiobutton2.pack()
#Listbox
def listbox_used(event):
# Gets current selection from listbox
print(listbox.get(listbox.curselection()))
listbox = Listbox(height=4)
fruits = ["Apple", "Pear", "Orange", "Banana"]
for item in fruits:
listbox.insert(fruits.index(item), item)
listbox.bind("<<ListboxSelect>>", listbox_used)
listbox.pack()
window.mainloop()
from tkinter import *
# window GUI for the program
window = Tk()
window.title("GUI test")
window.minsize(width=500, height=300)
# add a label :
lbl1 = Label(text="label1", font=("Times", 24, "bold"))
lbl1.place(x=0, y=0) #precise layout manager to place view at position
lbl1.config(bg="gray51", fg="white")
from tkinter import *
# window GUI for the program
window = Tk()
window.title("GUI test")
window.minsize(width=500, height=300)
# add a label :
lbl1 = Label(text="label1", font=("Times", 24, "bold"))
lbl1.grid(column=0, row=0)
lbl1.config(bg="gray51", fg="white")
# Button
def btn_click():
print("I got clicked")
lbl1["text"] = input.get()
btn1 = Button(text="click me", command=btn_click) # create and link to function
btn1.grid(column=2, row=0)
# Entry (txt box)
input = Entry(width=10)
input.grid(column=3, row=0)
window.mainloop() # keeps the window alive
add padding :
window.config(padx=20, pady=20) # add padding to a view
import math
from tkinter import *
# ---------------------------- CONSTANTS ------------------------------- #
# color pallets hex codes : colorhunt.co
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
timer = None
# ---------------------------- TIMER RESET ------------------------------- #
def reset_timer():
window.after_cancel(timer)
canvas.itemconfig(timer_txt, text="00:00")
# ---------------------------- TIMER MECHANISM ------------------------------- #
def start_timer():
count_down(5 * 60)
# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #
def count_down(count):
minutes = count%60
if minutes < 10:
minutes = f"0{minutes}" # dynamic typing int can become string
canvas.itemconfig(timer_txt, text=f"{math.floor(count/60)}:{minutes}")
if count > 0:
global timer # enable canceling timer
timer = window.after(1000, count_down, count - 1) # passes hello to the say something function
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Pomodoro")
window.config(padx=100, pady=50, bg=YELLOW) # set window background
# label timer
lblTimer = Label(text="label1", font=("Times", 24, "bold"))
lblTimer["text"] = "Timer"
lblTimer.grid(column=1, row=0)
lblTimer.config(font=(FONT_NAME, 26), fg=GREEN, bg=YELLOW, highlightthickness=0)
# canvas
canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0) # image view and set png image background
tomato_img = PhotoImage(file="tomato.png") # image grabber
canvas.create_image(100, 112, image=tomato_img)
timer_txt = canvas.create_text(100, 130, text="00:00", fill="black", font=("Times", 24, "bold"))
# ^ add width= a value < than the canvas width to enable multiline text
canvas.grid(column=1, row=1)
# start button
startBtn = Button(text="Start", highlightthickness=0, command=start_timer)
startBtn.grid(column=0, row=2)
# reset button :
resetBtn = Button(text="Reset")
resetBtn.config(highlightthickness=0, command=reset_timer)
resetBtn.grid(column=2, row=2)
# check marks label
chk_marks = Label(text="✓", fg=GREEN, bg=YELLOW)
chk_marks.grid(column=1, row=3)
window.minsize(width=500, height=500) # negates traceback error
window.mainloop()
try:
file = open("non_existing_file.txt")
except:
print("Ha Ha file not fount err")
file = open("non_existing_file.txt", "w") # create the file
try:
file = open("non_existing_file.txt")
except FileNotFoundError:
print("Ha Ha file not fount err")
file = open("non_existing_file.txt", "w") # create the file
try:
file = open("non_existing_file.txt")
dic = {"ai": "msg"}
print(dic["jlib"])
except FileNotFoundError:
print("Ha Ha file not fount err")
file = open("non_existing_file.txt", "w") # create the file
except KeyError as err_msg:
print(f"ha ha the key {err_msg} does not exist") # dictionary error
try:
file = open("non_existing_file.txt")
dic = {"ai": "msg"}
print(dic["ai"])
except FileNotFoundError:
print("Ha Ha file not fount err")
file = open("non_existing_file.txt", "w") # create the file
except KeyError as err_msg:
print(f"ha ha the key {err_msg} does not exist")
else:
print("no err")
finally:
print("this code will run anyways")
file.close()
import json
def save_json():
website = "supremegents.club"
email = "[email protected]"
password = "qwerty"
new_data = {
website: {
"email": email,
"password": password
}
}
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4) # indent makes it easier to read for humans
def load_json():
with open("data.json", "r") as data_file:
data = json.load(data_file) # type dictionary
print(data)
def update_json():
website = "pokemon.pika"
email = "[email protected]"
password = "southpark"
new_data = {
website: {
"email": email,
"password": password
}
}
try:
with open("data.json", "r") as data_file:
data = json.load(data_file)
# data.update(new_data)
print(data)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
data.update(new_data)
with open("data.json", "w") as data_file:
json.dump(data, data_file, indent=4)
def json_cell(key):
try:
with open("data.json", "r") as data_file:
data = json.load(data_file) # type dictionary
except FileNotFoundError:
print("data not found")
else:
if key in data:
print(data[key]["password"])
else:
print(f"no details for {key}")
# save_json()
load_json()
update_json()
json_cell("supremegents.club")