🐍 python python grimoire

python

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
auto download packages :

import pkgName

# click on the pkgName error to get an install function

example :

Python:
import heroes

print(heroes.gen())
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
Tuple :

the values inside tuple are constant

mytuple = ("apple", "banana", "cherry")

Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))

A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

access tuple item :
tuple1[0]

convert tuple to list :
l1 = list(tuple1)

explicit tuple :

Python:
    mytuple:(str,int,str) = ("apple", 3, "cherry")
    print(mytuple[1]*4)
 
Last edited:

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
higher order functions : functions that have other functions as parameters

Python:
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()

turtle class documentation
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
inheritance example

Python:
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")

multiple constructors example :

Python:
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)

Constructor overloading in python with default arguments

Python:
class MyClass:
    def __init__(self, edate=None, fdate=""):
        if edate:
            print("Constructors", edate)
        else:
            print("Default Constructor")


obj1 = MyClass("01-Dec-2021")

obj2 = MyClass()

Output:

Constructors 01-Dec-2021
Default Constructor
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
3rd method to overrite c'tor :

Python:
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'])

multiple c'tor example 4 :

Python:
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)
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
save load with text files

create a txt file in the pycharm project (my_file.txt in this example)
you can also use the txt files absolute file path (/Users/cake/Desktop/file.txt)
or the relative path ../../Desktop/file.txt
./ goes to projects starting folder
load :

Code:
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()

EXAMPLE project to create letter list for each name in list out of letter template:

Python:
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)
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
CSV files (excel)
example file used :

day,temp,condition
Monday,12,Sunny
Tuesday,14,Rain
Wednesday,15,Rain
Thursday,14,Cloudy
Friday,21,Sunny
Saturday,22,Sunny
Sunday,24,Sunny

read like a csv txt file :

Code:
with open("weather_data.csv") as file:
    contents = file.readlines()

for line in contents:
    print(line)

read and mine using the csv library :

Python:
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)

csv stuff with the pandas library : https://pandas.pydata.org/


Python:
import pandas

# ^ will aks you to auto install

data = pandas.read_csv("weather_data.csv")

# get var data type :
print(type(data))

the csv table is a panda frame type
the csv column list is a panda series type var

panda conversion examples :

Python:
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())

get specific csv data :

Python:
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())

or better code version :

Python:
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())

create a csv file :

Python:
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
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
screen input :

screen = screen()
answer = screen.textinput(title="",prompt="")
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
Python:
#  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']

Python:
#  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)
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
nato codes dictionary from nato csv file of columns letter, code :

Python:
# 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']
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
double click a function summon (example: turtle.write()) and see
the function doc. var that have ... have default values and are optional



varargs :

Python:
# 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
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
c'tor overload with kwargs

Python:
class Car:

    def __init__(self, **kw):
        self.make = kw.get("make")
        self.model = kw.get("model")


my_car = Car(make="audi")
print(my_car.model)  # none
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
TKinter :

Python:
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

example code 2 :

Python:
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()
 

fukurou

the supreme coder
ADMIN
TKinter Layout managers

place layout manager :


Python:
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")


grid layout :

Python:
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
 

fukurou

the supreme coder
ADMIN
tkinter timer example

Python:
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()

increase spread limit of view with columnspan :

b = Label(bg="blue", width=40, height=5)
b.grid(row=2, column=0, columnspan=2)
 

fukurou

the supreme coder
ADMIN
reverse split list into a string
str1.join(list) # "" to join without buffer string between elements

focus on entry :

e1 = Entry(width=35)
e1.focus()
e1.insert(0, "text") # insert text to entry, use END for the last index
e1.delete(0,END) # clear entry
 

fukurou

the supreme coder
ADMIN
clipboard management

Python:
import pyperclip


# https://pypi.org/project/pyperclip/


pyperclip.copy(str)  # copy str to the clipboard
 

fukurou

the supreme coder
ADMIN
try
try
code snippet
except err_type
code to run on fail or key word 'pass' to not do anything
else
code to run on no err
finally
runs anyways


Python:
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

the code, however, should specify the error type to catch :

Python:
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

multiple errors with error message

Python:
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

full try example :

Python:
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()
 

fukurou

the supreme coder
ADMIN
Python:
# raise custom error
h = float(input("height"))
if h > 3:
    raise ValueError("shingeki kyoujin")
 

fukurou

the supreme coder
ADMIN
JSON format :

Python:
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")

output :

{'supremegents.club': {'email': '[email protected]', 'password': 'qwerty'}, 'pokemon.pika': {'email': '[email protected]', 'password': 'southpark'}}
{'supremegents.club': {'email': '[email protected]', 'password': 'qwerty'}, 'pokemon.pika': {'email': '[email protected]', 'password': 'southpark'}}
no details for semegents.club
 
Top