0
4

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 5 years have passed since last update.

プログラミング初心者がPythonの応用までをガチで覚える軌跡

Last updated at Posted at 2018-08-26

 はじめに

pythonで必要な意識を簡単にまとめました。是非、活用してみてください。

 表記方法

pythonでは、基本、";" と "" で改行できます。

a = 200 ; b = 200 ; total = a + b
print(total)



1 + 2 + 3 + 4 + 5 \
+ 6 + 7 + 8 + 9 \
+ 10

複数行のコメント表記はダブルクォーテーション3個で囲みます。

"""
コメント
"""

文字代入で簡単に使用できるのは、.formatではないでしょうか?
pythonでは活用頻度が高いのでマスターしましょう。

total = "{:.3f}枚".format(num)
print(total)

結果(例)
10.000枚

これは".3f"で少数三桁までを表示しています。

 計算について

簡単に表記しています。出力結果から理解してください。

5 / 2 
結果 2.5


5 // 2
結果 2

2**3
結果 8
(累乗)

4 % 3
結果 1

文字列内での改行

文字列中にスペースや改行を埋め込みたいときは、バックスラッシュ(\)を使ったエスケープシークエンスを使いましょう。

aisatu = "こんにちは\nこんばんは\nさようなら"
print(aisatu)

こんにちは
こんばんは
さようなら

aisatu = "こんにちは\"こんばんは\"さようなら"
print(aisatu)

こんにちは"こんばんは"さようなら

 文字の切り出し

文字の切り出しですが、pythonはインデント番号を0からスタートします。

そのため、

id = "一緒にPythonを習いましょう"
id[3]

出力結果は、文中2番目(0、1、2)の文字となります。

-1は全ての一番後ろを表しています。

nums = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

num = nums[: : -2] # 最後から最初まで1つ飛ばした数を表記します。

結果
97531

 論理式

論理式では、Trueを1、Falseを0として扱います。

a = 4; b = 4; c = 5
print(a == b)
print(a == c)

True
False

 その他

roundは四捨五入をして丸めます。lenは後ろの桁数や文字数などのカウント数を表示します。

x = 2.7
print(min(round(x), 5))
3

x = len("1000000")
print(x)
7

*argsは、複数の引数の数を表しています。

def func(a = 1, z = 26, *args):
    return a + sum(args) + z

print(func())
print(func(1,26,2,3))
27
32

**kwargsは文字通り、複数のキーワード引数を表しています。

def func(**kwargs):
    return kwargs

print(func(a=1,b=2))
print(func())
{'a': 1, 'b': 2}

 ユーザー定義関数

def 関数名(引数1, 引数2):
処理1
処理2
return 返り値

def price(adult, child) :
    return (adult * 1200)+(child * 500)
print(price(1, 2))
2200

price1 = price(adult=1, child=2)
price2 = price(child=2, adult=1)
print(price1)
print(price2)
2200

*argsを使用したコードを書いてみました。

def route(start, end, *args) : # start, endは必須
    route_list = [start]
    route_list += list(args) # *は無くす
    route_list += [end]
    route_str = "→".join(route_list)
    print(route_str)

start  = "東京"
end = "宮崎"
route(start, end, "神戸", "長崎", "熊本")
東京→神戸→長崎→熊本→宮崎

こちらは**kwargsです。

def entry(name, gender, **kwargs) :
    data = {"name": name, "gender": gender}
    data.update(kwargs)
    print(data)

entry(name="大山坂道", gender="男性", age=27, course="E")
{'name': '大山坂道', 'gender': '男性', 'age': 27, 'course': 'E'}

hey関数を hello関数 の引数として渡す方法を見てみましょう。

def hey():
    print("hey!!")

def hello(func):
    func()

hello(hey)

結果
hey!!

とりあえず今日はここまでです。お疲れ様でした!

0
4
1

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
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?