さつまろぐ

CAEとかプログラムとか、出来たことの記録など、誰かのお役に立てれば幸い。

Pythonで遊ぶ 変数、入力、文字列

Python文法メモ

変数

変数 = 値 の形で代入

>>> x=5
>>> x
5

何も入っていない変数を出力しようとするとエラー

>>> y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

整数だけではなく、少数、文字列も代入することができる。

>>> x = 2.0
>>> x
2.0
>>> x = 'aaa'
>>> x
'aaa'

変数の型は代入するものによって変わる。type( )で変数の型を調べることができる。

>>> x = 5
>>> type(x)
<class 'int'>
>>> x = 2.0
>>> type(x)
<class 'float'>
>>> x = 'aaa'
>>> type(x)
<class 'str'>

型を宣言しないで使えるのは楽だけど、混乱やバグの元にならないように注意。

値の入力

input( )関数で入力を取得することができる。

>>> input("西暦?")
西暦?2023
'2023'

取得した値をそのまま変数に代入することができる。型は文字列なので、計算に使う場合はint( )などで数値に変換してから使う。

>>> x = input("x = ")
x = 5
>>> y = input("y = ")
y = 3
>>> x + y
'53'
>>> int(x) + int(y)
8
>>> type(x)
<class 'str'>
>>> type(int(x))
<class 'int'>

文字列

" "' 'で囲ってつかう。"' の違いは特にない? +演算子で文字列の連結。-,*,/ではエラーとなる。

>>> x = "aaa"
>>> x
'aaa'
>>> y = 'bbb'
>>> y
'bbb' 
>>> x + y
'aaabbb'
>>> x - y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

数値を連結しようとするとエラーになる。str( )関数で文字列に直すと連結できる。

>>> x = "aaa" ; z = 4
>>> x + z
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> x + str(z)
'aaa4'

文字列操作はもっと奥が深いので、また調べて書く。

広告