千葉工業大学 上田 隆一
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
hello.py
$ vi hello.py
print("hello") #文字列を出力 print(3.14) #数字を出力
#
python3
$ python3 hello.py hello 3.14
""
''
"hello", 'hello', "That's a pen."
3.14, -1, 5 1.23e+100 #1.23かける10の100乗
名前(引数, 引数, ...)
print
puts
printf
### コードの例 ### name = "上田" #「上田」という文字列にnameという名前を付ける money = 5 #5という数字にmoneyという名前をつける print("{}の所持金: {}円".format(name, money) ) #文字列に対してformatメソッドを呼び出し
var.py
$ python3 var.py 上田の所持金: 5円
### コードの例 ### fruits = ["apple", "banana", "cherry" ] #文字列3つのリストをfruitsと命名 for f in fruits: print(f + "はおいしい") # + で文字列を連結できる #↑インデントは半角空白4文字が標準(講義では厳密に守ること)
fruits.py
$ python3 fruits.py appleはおいしい bananaはおいしい cherryはおいしい
### コードの例(list.py) ### fruits = ["apple", "banana", "cherry" ] print("最初の要素: " + fruits[0]) #先頭は0番目 print("次の要素: " + fruits[1]) #次の要素は1番目 print("最後の要素: " + fruits[-1]) #最後の要素
$ python3 list.py 最初の要素: apple 次の要素: banana 最後の要素: cherry
### コードの例(list2.py) ### fruits = ["a", "b", "c", "d", "e" ] print("0番目から2番目の要素: ", fruits[0:3]) print("2番目以降の要素: ", fruits[2:]) print("ひとつ飛ばしでリストを作成: ", fruits[0::2])
$ python3 list2.py 0番目から2番目の要素: ['a', 'b', 'c'] 2番目以降の要素: ['c', 'd', 'e'] ひとつ飛ばしでリストを作成: ['a', 'c', 'e']
$ python3 hello.py
$ gcc hoge.c #gccでhoge.cをコンパイル $ ./a.out #できたa.outを実行
./a.out
$ ./hello.py
ls
ls.py
#!/usr/bin/python3 #この空行はいらないが、読みやすさのためにあける print("hello") print(3.14)
#!<インタプリタ名>
<>
which python3
#!
ls -l
x
$ ./hello.py #実行してみる bash: ./hello.py: 許可がありません #できない $ ls -l hello.py #ls -lで確認 -rw-r--r-- 1 ueda ueda 47 11月 30 06:50 hello.py $ ls -l a.out #gccで作ったa.outには最初から存在 -rwxr-xr-x 1 ueda ueda 16464 11月 30 07:16 a.out
chmod
$ chmod +x hello.py $ ./hello.py #実行できる hello 3.14 $ ls -l hello.py -rwxrwxr-x 1 ueda ueda 144 11月 30 18:31 hello.py
$ ls -l hello.py -rwxr-xr-x 1 ueda ueda 47 11月 30 06:50 hello.py
rwx
r
w
$ ./hello.py hello 3.14 ### 拡張子を除去してもよい(拡張子をつけるかどうかは場合による) ### $ mv hello.py hello $ ./hello (略)
mv
PATH
$ PATH=$PATH:/home/ueda #PATHの値に「:今いるディレクトリ」と文字列を追加 $ hello (略) $ exit #シェルを終了すると追加した文字列は消える
which