(*´ω`)数学的な処理はimport math を使う
【実行結果】
【解説】
まず数学的な処理をするのでimport mathをします。
円周率を表示するのでmath.piをします。
小数点切り捨てはmath.flootです。
小数点切り下げはmath.ceilです。
【コード】
print('円周率は{}です'.format(math.pi))
print('小数点以下を切り捨てれば{}です'.format(math.floor(math.pi)))
print('小数点以下を切り上げれば{}です'.format(math.ceil(math.pi)))
print(' ∧ ∧ 日々努力')
print('( ゚Д゚)')
print('海と猫が好き')
(*´ω`)withを使い処理が終了したらすぐにファイルを閉じる
【実行結果】
【解説】
withを使うことにより処理が終了したらすぐにファイルを閉じるようにする
【コード】
text =input('何を記録しますか?>>')
with open('diary.txt','a') as file:
file.write(text + '\n')
print(' ∧ ∧ GWは何をするかなあ')
print('( ゚Д゚)')
print('海と猫が好き')
(*´ω`)一行日記を作る
【実行結果】
text =input('何を記録しますか?>>')
file = open('nikki.txt','a')
file.write(text + '\n')
file.close()
print('( ゚Д゚)')
print('海と猫が好き')
(*´ω`)str型は不変なので新しくidentityができあがる
【実行結果】
【解説】
まずはリストを空にしておき、そこに松田を追加する。
その前後のidentityは同じ。つまり変更がかかるということ。
次に文字列を松田からスーパー松田にすると
その前後のidentityは異なる。つまり新しい物ができたということ。
従ってリスト型は中身が変更できてしまうため変更前の状態が
変更後の状態になってしまう。たとえば変更前はさんがついていないのに
変更後は変更前のものもさんが付いているなど。
str型の場合は、中身が不変型なので新しい物ができる。そのため
変更前の物は残っており、きちんとさんがつかない状態で表示される。
【コード】
names = list()
print('変更前のリストの内容:{}'.format(names))
print('変更前のlistのidentity:{}'.format(id(names)))
print('変更後のリストの内容:{}'.format(names))
print('変更後のlistのidentity:{}'.format(id(names)))
#文字列の場合
name = '松田'
print('変更前の文字列の内容:{}'.format(name))
print('変更前のstrのidentity:{}'.format(id(name)))
print('変更後の文字列の内容:{}'.format(name))
print('変更後のstrのidentity:{}'.format(id(name)))
print('( ゚Д゚)')
print('海と猫が好き')
(*´ω`)一度、コピーで退避すれば大丈夫なんだよ
【実行結果】
【解説】
一度, before_namesを copies_nameにコピーしておいて copies_nameを
関数に投入することでbefore_namesを手つかずのままにする。
そうすることによってbefore_nameはさんがつかない状態になる。
【コード】
def add_suffix(names):
names[i] = names[i] + 'さん'
return names
before_names = ['松田','浅木','工藤']
copied_names = list()
#copied_namesへbefore_namesを追加してゆく
copied_names.append(n)
#名前を関数に投入
after_names = add_suffix(copied_names)
#after_names表示
print('さん付け後:' + after_names[0])
#before_names表示
print('さん付け前:' + before_names[0])
print('( ゚Д゚)')
print('海と猫が好き')
(*´ω`)returnですでに変わっている。
【実行結果】
【解説】
def add_suffix(names):
names[i] = names[i] + 'さん'
return names
before_names = ['松田','浅木','工藤']
after_names = add_suffix(before_names)
#after_names表示
print('さん付け後:' + after_names[0])
#before_names表示
print('さん付け前:' + before_names[0])
print('( ゚Д゚)')
print('海と猫が好き')
(*´ω`)コピーはidentityをひとつにしてしまうため・・・
【実行結果】
【解説】
scores1とscores2があってこの時点ではそれぞれのidentityは異なっている。
ところがscores1 = scores2 とすることによってidentityは同じになってしまう。
そしてscores1[0]に90を代入する。ところがscores2もscores1と同じidentityに
なっているため、指し示すデータはひとつのみ。しったがってscores2[0]も
90になるということだ。
【コード】
scores1 = [80, 40, 50]
scores2 = [80, 40, 50]
print('scores2の先頭要素は{}'.format(scores2[0]))
print('変数scores2の中身をscores1に代入(コピー)します')
scores1 = scores2
print('scores1の先頭要素を90に書き換えます')
scores1[0] = 90
#実際2つに見えるが同じidentityを見にいっているので当然同じ内容になってくる
print('90を代入した scores1の先頭要素は{}'.format(scores1[0]))
print('90を代入していない scores2の先頭要素は{}'.format(scores2[0]))
print(' ∧ ∧ モナーはシステム解析家')
print('( ゚Д゚)')
print('海と猫が好き')