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?

Python初心者が最初に覚えるべき基本文法

Posted at

Python初心者が最初に覚えるべき基本文法

はじめに

Pythonを勉強するにあたり基本的なものをまとめました。

1,変数について

他言語では intや stringなど宣言してあげる必要がありましたが
Pythonでは宣言する必要はなく、変数に直接値を代入できます。

例)

x = 10       # 整数
name = "太郎" # 文字列
isResult = True  # ブール型

2,if文

条件によって処理を変えたい場合に使用します。
条件で例えば成人かどうかの判断をする場合は下記のように記載します。

age = 20
if age >= 18:
    print("成人です")
else:
    print("未成年です")

3,for文・while文

複数回同じ処理を繰り返したいときに利用します。
今回はそれぞれ0~4を出力する例を記載します。

for文

for i in range(5):
    print(i)  

while文

count = 0
while count < 5:
    print(count)
    count += 1

4,関数と関数の定義

関数

関数というのはPythonで用意されている機能のようなものです。
例えば下記のようなものがあります

abs()

渡した値の絶対値を返してくれる関数です。
下記のように記載するとどれでも100が返ってきます
例)

abs(100)
abs(-100)

round()

数値と有効桁数を指定するとその桁数で丸めた値が返ってきます。
例えば下記のように記載して2.21を小数第一位で丸めると2.2が返ってきます。
例)

round(2.21, 1)

max()、min()

渡した値の中から最大値のものを返してくれる関数です。
minは逆に最小の値を返してくれます。
下記のものだと12が返ってきます。
例)

numbers = [5, 9, 3, 12, 7]
max(numbers)

関数の定義

この様な関数を自身で作成することができます。
例として下記のようなものができます

def priceTotal(count1, price1, count2, price2):

    count1PriceTotal = count1 * price1
    count2PriceTotal = count2 * price2
    totalPrice = count1PriceTotal + count2PriceTotal
    return totalPrice

total = priceTotal(5, 100, 10, 130)
print("合計金額", total, "円です")

この様に金額計算を行う関数を作成することもできます。

おわりに

自身もPythonを勉強し始めたばかりではありますが
AIなどこれからの技術に役立っていく言語ではあると思うので
少しでもお役に立てれば幸い

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?