🐍 python python grimoire

python

magneto

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

print("hello world")

^ online compiler

^ offline debugger

print("hello\n world") //new line print
settings, code intelligence //enable/disable code corrections
print("hello " + input("what is your name ")) //input prompt

or select the line and cmd + / (mac) ctrl + / (windows)
string length : len("str")

keyboard shortcuts :
# this is a python comment
+/ or cmd / (mac) : toggle comment
run code : ctrl + entr
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
DATA TYPES

get data type : type(123)

Strings :
get char :
#subscripting :
print("hello"[0]) # output : h

num = 5
new_num = str(num) # convert number to string

#f-string
f"your score is {n1}"

int
1234123 #can write as 1_234_123+
exponent : print(3**2) #9

float :
a= float(123) # convert to float, works with strings also
round(num) # rounds

Decimal
round(num,2) #how many places after the point to round
8 // 3 # divition to integer (floored remainder)
/= div result
+=, -=, *=
 

magneto

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

draw.io # flowchart tool

Python:
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

shorthand if

if a > b: print("a is greater than b")

Short Hand If ... Else

a = 2
b = 330
print("A") if a != b else print("B")

multiple else statements on the same line:
print("A") if a == b else print("=") if a == b else print("B")

gates :
AND OR

mod (remainder):
7%3 # =1
 

magneto

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

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
list :
fruits = ["banana", "apple", "peach"]
l1 = [l2,l3] #lists c'tor
fruits[0] # get indexed item
fruits[-1] # get last indexed item
fruits.append("grapes") # add to list
len(fruits) # list size
random.choice(fruits) # selects rand from list

explicit list :
l1: list[str] = {'hello','hi'}


list matrix example:

Python:
row1 = ["□","□","□"];row2 = ["□","□","□"];row3 = ["□","□","□"];
map = [row1,row2,row3];
print(f"{row1}\n{row2}\n{row3}\n")
position = input("where do you want to put the treasure ? \n")
x = int(position[0]) #left right
y = int(position[1]) # up down
map[y][x] = 'x'
print(f"{row1}\n{row2}\n{row3}\n")

list slicing :

Python:
# Initialize list
List = [-999, 'G4G', 1706256, '^_^', 3.1496]
 
# Show original list
print("\nOriginal List:\n", List)
 
print("\nSliced Lists: ")
 
# Display sliced list
print(List[10::2])
 
# Display sliced list
print(List[1:1:1])
 
# Display sliced list
print(List[-1:-1:-1])

#[start,end,jump]
 
Last edited:

magneto

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

Python:
parts = ["feet","legs","hands"]
for part in parts:
  print(part)
# loop chars in string
for x in "banana":
  print(x)
#Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

#Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)

#continue
#Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

#range for loop
for x in range(6):
  print(x)

#range for loop
for _ in range(6):
  print("no index")

for x in range(2, 6):
  print(x)

# step for loop
for x in range(2, 30, 3):
  print(x)

# else in for loop :
for x in range(6):
  print(x)
else:
  print("Finally finished!")

#for loops cannot be empty, but if you for some reason have a for loop with no content,
#put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:
  pass
 

magneto

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

Python:
def my_function():
  print("Hello from a function")

my_function()

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes")

If the number of arguments is unknown, add a * before the parameter name:

Code:
def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Python:
def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

If the number of keyword arguments is unknown, add a double ** before the parameter name:

Python:
def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

function with default param

Python:
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

passing a list param

Python:
def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
return :
Python:
def my_function(x):
  return 5 * x

print(my_function(3))

function definitions cannot be empty, but if you for some reason have a function definition with no content,
put in the pass statement to avoid getting an error.

Python:
def myfunction():
  pass

recurssion :

Python:
def tri_recursion(k):
  if(k > 0):
    result = k + tri_recursion(k - 1)
    print(result)
  else:
    result = 0
  return result

print("\n\nRecursion Example Results")
tri_recursion(6)

explicit function :

Python:
def getCurrentTimeStamp(self) -> str:
        '''This method returns the current time (hh:mm)'''
        right_now = datetime.datetime.now()
        return str(right_now.hour) + ":" + str(right_now.minute)
 

magneto

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

Python:
i = 1
while i < 6:
  print(i)
  i += 1

# break:
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1
# continue:
i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

Print a message once the condition is false (while finalizer):

Python:
i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

on settings indent type should be set to spaces
and indent size to 4
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
#insert char

Python:
def insertStr(word,insert,index):
    if(index > len(word)or index<0):
        return word
    result = word[:index] + insert + word[index:]
    return result
#replace char
def replaceChar(word,insert,index):
    if(index > len(word)or index<0):
        return word
    result = word[:index] + insert + word[index+1:]
    return result

# contains :
if "h" not in "owl":
    print("true")

#############################################

clear replit.com output screen :
from replit import clear
clear()
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
dictionary

Python:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict["brand"])
str1="brand"
thisdict[str1]="ok" # this can creat a new entry for non preexisting keys
print(thisdict[str1])
# iterate dictionary :
for key in thisdict:
    print(key);print(thisdict[key])

explicit dictionary example :

pain:dict[str, int] = {}
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
Python:
# python docstring
def hellothere():
    """this function print a
    meaningless line of text"""
    print("hello there")

hellothere()

Python:
#storing functions as vars and in dictionaries:
def foo():
  print('nice')
def bar():
  print('drink')
dispatcher = {'foo': foo, 'bar': bar}
# Note that the values are foo and bar which are the function objects, and NOT foo() and bar().
dispatcher['foo']()
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
accessing global variables locally :

Python:
lives = 1

def increaseLives():
    global lives
    lives+=1
    print(f"global var modified and now equals : {lives}")

print(lives)
increaseLives()

or :

Python:
lives = 1

def increaseLives():
    print(f"global var access point 1 : {lives}")
    return lives +1

lives=increaseLives()#global var access point 2
print(lives)

PI = 3.14159 # constant declaration example

pythone debugger :
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
multiple import elements :

Python:
# importing variables from a file named art.py
from art import logo,vs

switch case

Python:
#select case
def week(i):
    switcher={
        0:'Sunday',
        1:'Monday',
        2:'Tuesday',
        3:'Wednesday',
        4:'Thursday',
        5:'Friday',
        6:'Saturday'
        }
    return switcher.get(i,"Invalid day of week")

print(week(8))

alter select case example :

Python:
def zero():
    return 'zero'
def one():
    return 'one'
def indirect(i):
    switcher={
        0:zero,
        1:one,
        2:lambda:'two'
        }
    func=switcher.get(i,lambda :'Invalid')
    return func()
print(indirect(2))
 

magneto

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


on the install wizard, check Add Python to PATH
if you see a msg saying :
Disable path length limit
^click on it

at this point you can delete the installer.

step 2 : DL PyCharm

^select the community version

starting a new project, on base interpreter, select the latest python ver you've
installed

pycharms special features :

suggests corrections to match common style guide conventions

right click tab to split screen

view local history : VCS, local history, show history (view code edits)
you can click revert or copy code snippets to restore codes

view code structure : click structure tab, this makes navigation of large code piles easier

name refactoring : select items name, right click, refactor, rename

TODO tracking
# TODO: 1. do something
the todos are accessible via the todo tab
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
Python:
# summonig objects with turtle cls as example

from turtle import Turtle, Screen

batch = Turtle()
print(batch)
batch.shape("turtle")
batch.color("blue")
batch.forward(100) # moves the object
myScreen = Screen()
print(myScreen.canvheight)
myScreen.exitonclick()  # makes the prog exit on screen click

^ https://docs.python.org/3/library/turtle.html
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
python package index : UL/DL packages :

to DL :
file, settings

to DL on mac :
PyCharm, pref

click on your project, project interpreter, +, type package name to search, install package, click ok

code example (imported prettytable, a pkg to display ascii tables)

Python:
#right click the pkg name in the code after implement, goto, implementation to view its code
import prettytable

tbl = prettytable.PrettyTable()
tbl.add_column("pokemon", ["electabuzz", "charmander", "mew"])
tbl.add_column("type", ["electric", "fire", "psychic"])
tbl.align="l"
print(tbl)

output :
+------------+----------+
|  pokemon   |   type   |
+------------+----------+
| electabuzz | electric |
| charmander |   fire   |
|    mew     | psychic  |
+------------+----------+
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
All classes have a function called __init__(), which is always executed when the class is being initiated.

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

Python:
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    self.hair_color = "green" # default value attribute

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

print(p1.name)
print(p1.age)

The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
self can also be named anything else
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
You can delete properties on objects by using the del keyword:
del p1.age

or delete an object :
del p1

or add attributes externally :
p1.level = 9

protip : to clean pasted long lines of code : code, reformat code
 

magneto

闇の伝説
戦闘 コーダー
🦈 VIP 🦈
Python:
# refer to a module using an alias
import ClockUtil as cu

print(cu.getTimeStamp())
 
Top