1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonの基本

Last updated at Posted at 2021-04-04
"""
Pythonの使い方まとめ
"""

# 前提
Homebrew導入済み

# インストール
$ brew install pyenv

## ~/.bash_profile に以下の追記
export PYENV_ROOT=${HOME}/.pyenv
if [ -d "${PYENV_ROOT}" ]; then
    export PATH=${PYENV_ROOT}/bin:$PATH
    eval "$(pyenv init -)"
fi

## インストール可能バージョン確認
$ pyenv install -l

## 使用バージョンのインストール
$ pyenv install 3.6.7

## インストールされているバージョン確認
$ pyenv versions

## グローバルかローカルにインストール
$ pyenv global 3.7.5
$ pyenv local 3.7.5

## 設定されているバージョン確認
$ python --version

# 文字コード設定
# coding: utf-8

# 文字列出力
print('Hello, Python')
print("Hello, Python")
print("""Hello, Python""")

# 文字列結合
print("Hello " + "Python") # Hello Python
print("Hello " * 3) # Hello Hello Hello 
print(f"1 - 2 = {1 - 2}") # 1 - 2 = -1

# 数値出力・演算
print(10) # 数値
print(10 + 5) # 足し算
print(5 - 2) # 引き算
print(10 * 2) # 掛け算
print(10 ** 2) # 自乗
print(10 / 2) # 割り算
print(10 // 2) # 割り算(切り捨て)
print(10 % 5) # 余り
print((20 - 5) // 3) # 括弧

# 型変換(キャスト)
print("Hello" + str(24)) # Hello24
print(int("100") + 50) # 150

# リスト型
array = ["Hello", "Python"]
array.append("test")
print(array, array[0])

# 辞書型
dictionary = {"head": "Hello", "body": "Python"}
dictionary["test"] = "test"
print(dictionary, dictionary["test"])

# 変数(大文字、小文字を区別)
hello_python = "Hello, Python"
print(hello_python)

# 定数
HELLO_PYTHON = "HELLO, PYTHON"
print(HELLO_PYTHON)

# 条件式
score = 90
if score > 80:
	print("Great!")
elif score > 60:
	print("Good!")
else:
	print("So So!")

# 条件演算子
print("Great!" if score > 80 else "so so! ..")

# 繰り返し処理
## while 
num = 0
while num < 10:
    print(num)
    num += 1
else:
    print("finish!")

### 無限ループ
while True:
    print("無限ループ")

## for 
for i in range(0, 10):
    print(i)
else:
    print("Finish!")

for d in [20, 40, 60, 88]:
    print(d)
else:
    print("Finish!")

continue # 1回スキップ
break # 処理を終了

for index, name in enumerate(["apple", "banana", "melon"]):
    print(index, name)

for key, value in {"tani": 21, "kazu": 22, "python": 100}.items():
    print(f"key: {key} value: {value}")

# 簡単数値リスト
print(list(range(101)))

# 標準入力
name = input()
print(name)

# 関数
## 定義
def say_hello(name = "satoshi", age = "24"):
    print(f"Hi! {name} age({age})")

## 呼び出し
say_hello("tom", 20)

### 順番は関係なく引数を与える。
say_hello(age = 18, name = "john")

## 返り値
def say_hello(name, age):
	  return f"Hi! {name} age({age})"

print(say_hello("mint", 28))

## 保留関数(あとで記述したいとき)
def through():
	  pass

# import
## function.py
def number():
    print(123)

def text():
    print("Hello world!")

## test.py
import function
function.number()

import function as func
func.number()

from function import number as num
num()

from function import *
number()
text()

from function import number, text
number()
text()

print( function.__file__ )

# class
class User:
  def __init__(self, name):
    self.name = name
    print("コンストラクタが呼ばれました")

  def hello(self):
    print("Hello " + self.name)

user = User("Sample User")
user.hello() # Hello Sample User

## 継承
class SuperUser(User):
  def __init__(self, name, age):
    super().__init__(name) # オーバーライド(継承元の変数上書き)
    self.age = age

  def hello(self): # オーバーライド(継承元の関数上書き)
    print("SuperHello" + self.name)
    super().hello() # 継承元の関数呼び出し

super_class = SuperUser("tani", 100)
super_class.hello()

## 多重継承
class SampleClassName(Base1, Base2):

# 予約語
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?