投稿

2月, 2021の投稿を表示しています

The Zen of Python

Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! The meaning of the 6th line is as follows. Sparse is better than dense. — In short, “don't try to stick too much code on one line.” [X] Although efficien...

Sequence Types -- str, unicode, list, tuple, buffer, xrange

イメージ
There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects. This table lists the sequence operations sorted in ascending priority (operations in the same box have the same priority). In the table, s and t are sequences of the same type; n, i and j are integers: from here

time モジュール & datetime モジュール

import time as t now=t.localtime() print('localtime()') print(now) print() print("t.strftime('%y-%m-%d %H:%M:%S',now)") print(t.strftime('%y-%m-%d %H:%M:%S',now)) import datetime as dt nowdt= dt.datetime.now() print() print('nowdt') print(nowdt) print('nowdt.isoformat()') print(nowdt.isoformat()) nextyear=dt.datetime(2022,1,1) print() print('delta.days') delta=nextyear-nowdt print(delta.days) ==== RESTART: C:/python/time&datetimeTest.py === localtime() time.struct_time(tm_year=2021, tm_mon=2, tm_mday=28, tm_hour=10, tm_min=37, tm_sec=53, tm_wday=6, tm_yday=59, tm_isdst=0) t.strftime('%y-%m-%d %H:%M:%S',now) 21-02-28 10:37:53 nowdt 2021-02-28 10:37:53.398604 nowdt.isoformat() 2021-02-28T10:37:53.398604 delta.days 306 >>>

turtle 多角形描画

イメージ
import turtle as t def takakkei(n,w): p=t.Pen() p.reset() p.up() p.goto(-25,-120) p.down() c=('red','green','pink','aqua','blue') deg=360//n for x in range(1,n+1): z=x%5 p.color(c[z]) p.forward(w) p.left(deg) t.setup(width=300,height=300) t.bgcolor("white") for i in range(3,16): takakkei(i,50) 実行結果 >>> === RESTART: C:/python/turtleDrawTakakkei.py === >>>

pandas csv入力 ピボット集計

import pandas as pd import os import numpy as np path=os.getcwd() print(path) def2=pd.read_csv('c:\python\sample2.csv') print(def2) table=pd.pivot_table(def2,values='price', index=['date'], columns=['item'],aggfunc=np.sum) print() print("ピボット集計 結果") print(table) ==== RESTART: C:/Users/ooshi/AppData/Local/Programs/Python/Python39/pandasCloss.py ==== C:\Users\ooshi\AppData\Local\Programs\Python\Python39 date item price 0 2015-01-01 apple 300 1 2015-01-01 apple 300 2 2015-01-01 orange 250 3 2015-01-02 orange 240 4 2015-01-02 orange 240 5 2015-01-02 banana 260 ピボット集計 結果 item apple banana orange date 2015-01-01 600.0 NaN 250.0 2015-01-02 NaN 260.0 480.0 >>>

pandas データ定義とピボット集計

import pandas as pd import numpy as np df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"], "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"], "C": ["small", "large", "large", "small", "small", "large", "small", "small", "large"], "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]}) print(df) table = pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'], aggfunc=np.su...

Pythonのおもな組み込み型の分類表

イメージ
Pythonのおもな組み込み型の分類表 変更不可(イミュータブル、immutable) 値を変更するには、箱ごと変えなければいけない(中身を変えられない箱) 変更可(ミュータブル、mutable) 箱はそのままで、中身の値だけを変えることができる(中身を変えられる箱) 反復可(イテラブル、iterable) 要素を1つずつ返すことができるオブジェクト」です。 わかりやすく言うと、for文のinのうしろに置いて、 1つずつデータを取り出せるオブジェクトです。 シーケンス(sequence) 整数のインデックスを指定して、要素にアクセスできる」データ型です。 組み込み関数len()で要素数(長さ)を取得できます。 文字列(str)もシーケンスです。 マッピング(mapping) 任意のキーで要素を検索できる」データ型です。 シーケンスが整数のインデックスを指定して要素にアクセスするのに対して、 マッピングは任意のキーを使用できます。 辞書(dict)が代表的なマッピング型です。

help("yield")

>>> help("yield") The "yield" statement ********************* yield_stmt ::= yield_expression A "yield" statement is semantically equivalent to a yield expression. The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements yield yield from are equivalent to the yield expression statements (yield ) (yield from ) Yield expressions and statements are only used when defining a *generator* function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. For full details of "yield" semantics, refer to the Yield expressions section. >>>

yield sample progaram

def myfunc(): yield 'one' yield 'two' yield 'three' yield 12345 print("test myfunc") for s in myfunc(): print(s) print("test myfunc by next") gene = myfunc() print(next(gene)) print(next(gene)) print(next(gene)) def myfunc2(x:int): # 0からxまでの値を2倍して返す for z in range(x): yield z*2 print("test myfunc2") for i in myfunc2(5): print(i) ===== RESTART: C:/python/yieldTest20210224.py === test myfunc one two three 12345 test myfunc by next one two three test myfunc2 0 2 4 6 8 >>>

Why do we use yield in Python?

We should use yield when we want to iterate over a sequence but don't want to store the entire sequence in memory. yield is used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.

generate cubes of numbers

#solution : generate cubes of numbers def cubicvar(): i=1 while True: yield i*i*i i +=1 print("cubes of number") for num in cubicvar(): if num> 1000: break print(num) ======= RESTART: C:/python/generateCubesOfNUmber.py ==== cubes of number 1 8 27 64 125 216 343 512 729 1000 >>>

calculate BMI by numpy array

Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are that they are fast, easy to work with, and give users the opportunity to perform calculations across entire arrays. In the following example, you will first create two Python lists. Then, you will import the numpy package and create numpy arrays out of the newly created lists. # Create 2 new lists height and weight height = [1.6, 1.87, 1.87, 1.82, 1.91] weight = [55.2,81.65, 97.52, 95.25, 92.98] print("height") print(height) print("weight") print(weight) # Import the numpy package as np import numpy as np # Create 2 numpy arrays from height and weight np_height = np.array(height) np_weight = np.array(weight) print("type") print(type(np_height)) # Calculate bmi bmi = np_weight / np_height ** 2 # Print the result print("BMI") print(bmi) # For a boolean response print("bmi > 23") print(bmi > 23) print("bmi 23]...

Generators

import random def lottery(): # returns 6 numbers between 1 and 40 for i in range(6): yield random.randint(1, 40) # returns a 7th number between 1 and 15 yield random.randint(1,15) # returns a 8th number between 100 and 120 yield random.randint(100,120) for random_number in lottery(): print("And the next number is... %d!" %(random_number)) ========= RESTART: C:/python/lottery20210222.py ======== And the next number is... 25! And the next number is... 25! And the next number is... 16! And the next number is... 38! And the next number is... 22! And the next number is... 4! And the next number is... 9! And the next number is... 115! >>>

About Interactive Tutorials(learnpython.org)

learnpython.org is a free interactive Python tutorial - one of the Interactive Tutorials websites. Interactive Tutorials is a personal project of mine aimed at making everyone in the world be able to learn how to code for free. The servers used to run the tutorials and the time invested in writing tutorials is funded through ads. The vision is to teach coding within the browser using short and effective exercises. By running actual code directly from the web browser, students are able to try out coding without installing and executing it locally, which can be hard and redundant for the purpose of learning how to code. This creates a more efficient learning process, because students focus on learning instead of setting up coding environments. This website and its content may be used freely and without charge, and it will always be free. source from here

pandas DataFrames Basic

Pandas is a high-level data manipulation tool developed by Wes McKinney. It is built on the Numpy package and its key data structure is called the DataFrame. DataFrames allow you to store and manipulate tabular data in rows of observations and columns of variables. There are several ways to create a DataFrame. One way way is to use a dictionary. For example: dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"], "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"], "area": [8.516, 17.10, 3.286, 9.597, 1.221], "population": [200.4, 143.5, 1252, 1357, 52.98] } import pandas as pd print(dict) brics = pd.DataFrame(dict) print(brics) brics.index = ["BR", "RU", "IN", "CH", "SA"] print(brics) ===== RESTART: C:/python/PandasDataFrames...

pip list (Vostro 15 3000)

C:\Users\ooshi>python -m pip install --upgrade pip Requirement already satisfied: pip in c:\users\ooshi\appdata\local\programs\python\python39\lib\site-packages (21.0.1) C:\Users\ooshi>pip list Package Version ------------------------- --------- altgraph 0.17 cycler 0.10.0 et-xmlfile 1.0.1 future 0.18.2 jdcal 1.4.1 kiwisolver 1.3.1 matplotlib 3.3.3 numpy 1.19.4 openpyxl 3.0.5 panda3d 1.10.8 pandas 1.2.2 pefile 2019.4.18 Pillow 8.1.0 pip 21.0.2 pygame 2.0.1 pyinstaller 4.2 pyinstaller-hooks-contrib 2020.11 pyparsing 2.4.7 python-dateutil 2.8.1 pytz 2021.1 pywin32 300 pywin32-ctypes 0.2.0 reportlab ...

Python keyword 36

>>> import keyword >>> dir(keyword) ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'iskeyword', 'issoftkeyword', 'kwlist', 'softkwlist'] >>> keyword.iskeyword("for") True >>> keyword.issoftkeyword('for') False >>> keyword.softkwlist [] >>> keyword.kwlist ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', ...

Python | Menu widget in Tkinter

イメージ
Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used package for GUI applications which comes with the Python itself. Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows. # importing only those functions # which are needed from tkinter import * from tkinter.ttk import * from time import strftime # creating tkinter window root = Tk() root.title('Menu Demonstration') # Creating Menubar menubar = Menu(root) # Adding File Menu and commands file = Menu(menubar, tearoff = 0) menubar.add_cascade(label ='File', menu = file) file.add_command(label ='New File', command = None) file.add_command(label ='Open...', command = None) file.add_command(l...

Python Tkinter – ScrolledText Widget

イメージ
Tkinter is a built-in standard python library. With the help of Tkinter, many GUI applications can be created easily. There are various types of widgets available in Tkinter such as button, frame, label, menu, scrolledtext, canvas and many more. A widget is an element that provides various controls. ScrolledText widget is a text widget with a scroll bar. The tkinter.scrolledtext module provides the text widget along with a scroll bar. This widget helps the user enter multiple lines of text with convenience. Instead of adding a Scroll bar to a text widget, we can make use of a scrolledtext widget that helps to enter any number of lines of text. # Python program demonstrating # ScrolledText widget in tkinter import tkinter as tk from tkinter import ttk from tkinter import scrolledtext # Creating tkinter main window win = tk.Tk() win.title("ScrolledText Widget") # Title Label ttk.Label(win, text = "ScrolledText Widget Example insert"...

Python 標準ライブラリ

Python 言語リファレンス ではプログラミング言語 Python の厳密な構文とセマンティクスについて説明されていますが、このライブラリリファレンスマニュアルでは Python とともに配付されている標準ライブラリについて説明します。また Python 配布物に収められていることの多いオプションのコンポーネントについても説明します。 Python の標準ライブラリはとても拡張性があり、下の長い目次のリストで判るように幅広いものを用意しています。このライブラリには、例えばファイル I/O のように、Python プログラマが直接アクセスできないシステム機能へのアクセス機能を提供する (Cで書かれた) 組み込みモジュールや、日々のプログラミングで生じる多くの問題に標準的な解決策を提供するPython で書かれたモジュールが入っています。これら数多くのモジュールには、プラットフォーム固有の事情をプラットフォーム独立な API へと昇華させることにより、Pythonプログラムに移植性を持たせ、それを高めるという明確な意図があります。 From here

PyGame: A Primer on Game Programming in Python

From here

Beginning Game Programming for Teens with Python

From Here

組み込み関数

関数 結果 説明 abs(-10) 10 bool(0) False bool(my_null_list) my_null_list=[] False リストが空か調べる exec(my_small_program) my_small_progaram=‘‘‘print(‘dog‘) print(‘cat‘)‘‘‘ 引数の中にプログラムを書く eval('10*5') 50 float(12) 12.0 float('12.345' 12.345 len('this is a test string') 21 max([10,200,30,50]) 200 min([10,200,30,50]) 10 print(list(range(0,3))) 結果 [0,1,2] イテレータをリストに変換 sum((1,2,3)) 6 タプルの合計 sum([1,2,3,4]) 10 リストの合計 sum(range(11)) 55 イテレータの合計

イベントバインディング  リモートコントロール

イメージ
from tkinter import * tk=Tk() canvas=Canvas(tk,width=400,height=400) canvas.pack() id1=canvas.create_polygon(10,10,10,60,50,35,fill="yellow") canvas.itemconfig(id1,outline="red") id2=canvas.create_arc(10,10,30,30,extent=359,style=ARC) canvas.itemconfig(id2, outline="blue") def movetriangle(event): canvas.move(id1,5,0) def movetriangle2(event): if event.keysym == 'Up': canvas.move(id2,0,-5) if event.keysym == 'Down': canvas.move(id2,0,5) if event.keysym == 'Left': canvas.move(id2,-5,0) if event.keysym == 'Right': canvas.move(id2,5,0) canvas.bind_all(' ',movetriangle2) canvas.bind_all(' ',movetriangle2) canvas.bind_all(' ',movetriangle2) canvas.bind_all(' ',movetriangle2) canvas.bind_all(' ',movetriangle)

GIF画像&TEXT表示

イメージ
from tkinter import * tk=Tk() canvas=Canvas(tk, width=600, height=400) canvas.pack() myImage=PhotoImage(file='tenor.gif') canvas.create_image(0,0,anchor=NW, image=myImage) canvas.create_text(200,350,text='gif画像のみ読み込めます。',font=('Times',20))

画像表示 matplotlib

イメージ
source code import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('mydog2020.PNG') imgplot = plt.imshow(img) plt.show()

tkinter canvas create_rectangle

イメージ
from tkinter import * import random tk=Tk() canvas=Canvas(tk, width=400,height=400) canvas.pack() def random_rectangle(width,height,fill_color): x1=random.randrange(width) y1=random.randrange(height) x2=random.randrange(x1+random.randrange(width)) y2=random.randrange(y1+random.randrange(height)) if abs(x1-x2)*abs(y1-y2)>20000: return if abs(x1-x2)

tkinter Canvas methods

メソッド 説明 self.canvas = tkinter.Canvas(root, bg="white", height=300, width=300) canvas.create_rectangle(10, 20, 100, 50, fill = 'red') canvas.create_oval(100, 100, 150, 150) canvas.create_polygon(250, 10, 220, 100, 150, 100,fill="green") 最低3点必要 canvas.create_line(10, 200, 150, 150, fill='red') 引数 stipple = ビットマップ 塗りつぶしの模様 引数 outline = 色 枠の色 引数 width = 3 枠の幅デフォルト1 canvas.pack() canvas.place(x=0, y=0) Window上の位置指定

what is python good for

Professionally,  Python  is  great  for backend web development, data analysis, artificial intelligence, and scientific computing. Many developers have also used  Python  to build productivity tools, games, and desktop apps, so there are plenty of resources to help you learn how to do those as well.

turtle methods

setup(w,h) setup(width=500,height=500) pen() 自動的にキャンパスを生成 pensize(2) bgcolor("black") up() down() goto(x,y) home() 中心に戻す reset() 図形を消して最初の位置に戻る clear 図形を消去する setheading() forward(100) right(90) left(90) color("red") color(1,0,0) begin_fill() end_fill() circle(10) setx(100) sety(100) hideturtle() screensize( canvwidth=100, canvheight=100) speed("fastest") speed(10)

40クラスで同じ誕生日の人がいる確率

イメージ
このケースでは、40人クラスで同じ誕生日の人が全くいない確率を求め、 最後に、全体の1から引き算する方式を取ります。 #same birthday in 40 member class n=1.0 k=1.0 for i in range(40): n=n*(365-i)/365.0 k=k-n print(k)

Built-In String Methods/Functions

>>> "aaa".capitalize() 'Aaa' >>> "Hi, Mac, Hello".casefold() 'hi, mac, hello' >>> "123".center(6) ' 123 ' >>> print("123".center(6)) 123 >>> print("123".center(10,"z")) zzz123zzzz >>> str="I love Python. Python is a programming language" >>> str.count("Python") 2 >>> text="Python is easy to learn." >>> text.endswith('to learn.') True >>> str='xyz\t1234\tzzz\t45' >>> str.expandtabs() 'xyz 1234 zzz 45' >>> str="Let me test this string" >>> str.find("test") 7 >>> str.find("that") -1 >>> print("Hello {}, my fav no is {}.".format("Tom", 888)) Hello Tom, my fav no is 888.

turtle circle drawing

イメージ
from turtle import * screensize(canvwidth=200,canvheight=200) speed("fastest") hideturtle() for i in range(10): for j in range(10): if i % 2 ==0 and j%2 ==0: fillcolor("green") elif i % 2 == 0 and j%2 ==1: fillcolor("yellow") elif i % 2 == 1 and j%2 ==0: fillcolor("pink") elif i % 2 == 1 and j%2 ==1: fillcolor("blue") up() setx(i*20) sety(j*20) down() begin_fill() circle(10) end_fill()

turtle drawing 2

イメージ
from turtle import * screensize(canvwidth=100,canvheight=100) speed("fastest") up() sety(250) setx(100) down() hideturtle() def drawLine(): for i in range(9): forward(12*i) right(30) for i in range(0,20): drawLine() right(36)

turtle drawing

イメージ
from turtle import * screensize(canvwidth=100,canvheight=100) speed("fastest") up() sety(150) down() hideturtle() def drawLine(): for i in range(7): forward(15*i) right(30) for i in range(0,60): drawLine() right(36)