Startup Data scientist Blog

データ分析系のテック情報を発信します

pythonサンプルコード append

pythonサンプルコード

append listに要素を追加する。

x = [1, 2, 3]
y = [4, 5, 6]
z = y
y = x
x = z

x = [1, 2, 3]
y = x
x.append(4)
y.append(5)
z = [1, 2, 3, 4, 5, 6]
x.append(6)
y.append(7)
y = "hello"

def foo(lst):
    lst.append("hello")
    bar(lst)
   
def bar(myLst):
    print(myLst)
   
foo(x)
foo(z)

 

Output

>>

[1, 2, 3, 4, 5, 6, 7, 'hello']
[1, 2, 3, 4, 5, 6, 'hello']

pythonのflaskコード

flask用の作業フォルダの作成

## macOS or Linux
mkdir flask

 

作業フォルダに移動

cd flask

 

python仮想環境の設定

python -m venv venv

 

アプリファイルの作成

touch app.py

 

app.py

from flask import Flask, redirect, url_for, request, render_template, session

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

 

templeteフォルダを用意する。

mkdir templete

 

templateフォルダに移動する

cd templete

 

htmlファイルの作成

touch index.html

 

Jinja のテンプレート ファイルの作成

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <title>Translator</title>
</head>
<body>
    <div class="container">
        <h1>Translation service</h1>
        <div>Enter the text you wish to translate, choose the language, and click Translate!</div>
        <div>
            <form method="POST">
                <div class="form-group">
                    <textarea name="text" cols="20" rows="10" class="form-control"></textarea>
                </div>
                <div class="form-group">
                    <label for="language">Language:</label>
                    <select name="language" class="form-control">
                        <option value="en">English</option>
                        <option value="it">Italian</option>
                        <option value="ja">Japanese</option>
                        <option value="ru">Russian</option>
                        <option value="de">German</option>
                    </select>
                </div>
                <div>
                    <button type="submit" class="btn btn-success">Translate!</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

 

Visual Studio Code 内の統合ターミナルのcmdを開きます

set FLASK_ENV=development

export FLASK_ENV=development

 

ブラウザーで http://localhost:5000を開きます。

 

 

 

 

じゃんけんゲームをつくれるpythonコード

ターミナルを使用してファイル rock-paper-scissor.py を作成

touch rock-paper-scissor.py

 

作成したファイルにコードを記載する

code .

 

class Participant:
    def __init__(self):
        self.points = 0
        self.choice = ""
       
class GameRound:

class Game:
    def __init__(self):
        self.endGame = False
        self.participant = Participant()
        self.secondParticipant = Participant()

 

class Participant:
  def __init__(self, name):
    self.name = name
    self.points = 0
    self.choice = ""
  def choose(self):
    self.choice = input("{name}, select rock, paper or scissor: ".format(name= self.name))
    print("{name} selects {choice}".format(name=self.name, choice = self.choice))

class GameRound:
  def __init__(self, p1, p2):
    p1.choose()
    p2.choose()
  def compareChoices(self):
    print("implement")
  def awardPoints(self):
    print("implement")

class Game:
  def __init__(self):
    self.endGame = False
    self.participant = Participant("Spock")
    self.secondParticipant = Participant("Kirk")
  def start(self):
    game_round = GameRound(self.participant, self.secondParticipant)

  def checkEndCondition(self):
    print("implement")
  def determineWinner(self):
    print("implement")

game = Game()
game.start()

 

 

 

pythonを使ったclassサンプルコード

classの作成

class Car:

 

クラスからオブジェクトを作成

car = Car()

 

class Elevator:
    def __init__(self, starting_floor):
        self.make = "The evevator company"
        self.floor = starting_floor

#オブジェクトの作成

elevator = Elevator(99)
print(elevator.make)
print(elevator.floor)

2 つの変数 (make と floor) を持つクラス Elevator を説明したものです。 このコードで重要な点は、 __init__() が暗黙的に呼び出されているという点です。 __init__() メソッドは名前で呼び出すのではなく、オブジェクトの作成時に (次のコード行で) 呼び出されます。

 

>>>

The evevator company
99

 

 

BMIを算出するサンプルコード

#クラスの定義
class Human:
    #コンストラクト 身長(cm)と体重(kg)からBMIを計算
    #インスタントが作成されると実行
    def __init__(self, height, weight):
        self.BMI = weight / (height**2)
       
    #メソッド value:BMIを四捨五入して計算
    def value(self):
        return round(self.BMI, 2) #
    #self.BMIをコンストラクトから受け取る。round()で四捨五入
   
    #適正体重を判定
    def is_fat(self):
        if self.BMI < 18.5:
            print("Under")
        elif self.BMI >= 30:
            print("Over")
        else:
            print('OK')

#実行
if __name__ == '__main__':
    Jo = Human(1.9, 82)
    Tarou = Human(1.5, 88)
   
print(Jo.value())
print(Tarou.value())
print('\n') #改行
Jo.is_fat()
Tarou.is_fat()

>>>

22.71
39.11


OK
Over