IT×MYTHING

IT関連技術や自分の好きなテーマについて紹介するブログです!

【Python基礎文法2】まとめました

こんにちは。

再び自分用にPythonの基礎的な文法をまとめました。よければご利用ください。

第一弾はこちら↓

www.it-crossover.com

内容としては以下になります。

・関数

・文字の加工

・文字の検索

・小数点の表示

・論理演算子

### 関数の基本的な書き方
def add(x):
  retrun x +1

print(add(10)) # 11

### 文字の加工
## タプル
sake = ('sake', 'head', 'body', 'hire') #値は変更できない
man = ('man', 'head', 'body', 'foot') #値は変更できない
dic = {
  sake: 'fish',
  man: 'mammal'
}
for name, spiecies in dic.items():
        parts_1, parts_2, parts_3, parts_4 = name
        print(parts_1, 'は', spiecies, 'で、',parts_4, 'がある')

# sake は fish で、 hire がある
# man は mammal で、 foot がある

## 結合(join)
message = ['Happy!', 'sad?']
question = ' or '.join(message) #結合
print(question) # Happy! or sad?

## 置換(replace)
positive = question.replace('sad?', 'interest?')
print(positive) # Happy! or interest?

## 文字の長さ(len)
print(len(positive)) # 19 #文字の長さ

### 文字の検索(startswith, find)
str = 'yamame'
str2 = 'meyama'
## startswith(文頭の検索)
result_startswith1 = str.startswith('yama')
result_startswith2 = str2.startswith('yama')
print( result_startswith1, result_startswith2) # True False
## find(検索対象の位置indexを返す)
result_find1 = str.find('yama')
result_find2 = str2.find('yama')
print(result_find1, result_find2) # 0 2
## in(文字が含まれているか)
result_in1 = 'yama' in str
result_in2 = 'yama' in str2
print(result_in1, result_in2) #True True

### 小数点の表示
score = 30
print('テストの平均点は{:d}点'.format(score)) #テストの平均点は30点
print('テストの平均点は{:f}点'.format(score/3)) #テストの平均点は10.000000点
print('テストの平均点は{:.2f}点'.format(score/3)) #テストの平均点は10.00点

### 論理演算子
kabu = 5
nasu = 6
if kabu > 4 and nasu > 4:
     print('在庫は十分') #在庫は十分
if kabu > 5 or nasu > 5:
     print('在庫は足りています') #在庫は足りています
if not kabu == 0:
     print('カブは0個ではない') #カブは0個ではない
if (not kabu == 0 and not nasu == 0) or (kabu < 10 and nasu < 10):
     print('在庫はあるみたいです') # 在庫はあるみたいです

以上です!