Python
print('Example program')
Output
Example program
ソースコードがそのまま上から実行される
print関数でテキストを出力
C
#include <stdio.h>
void main()
{
printf("Example program\n");
}
Output
Example program
main関数の中身から実行される
printf関数でテキストを出力
Python
def main():
print('Example program')
if __name__ == '__main__':
main()
Output
Example program
ソースコードがそのまま上から実行される
def mainは関数の定義であり,この時点では呼び出されない
if文は実行される
詳細は説明しないが,普通に実行した場合__name__は__main__である
if文の中が実行されるので,main関数が呼び出される
C
#include <stdio.h>
void main()
{
printf("Example program\n");
}
Output
Example program
Python
def main():
''' コメント1行目
コメント2行目 '''
print('Comment example') # コメント
if __name__ == '__main__':
main()
Output
Comment example
'''と'''の間にあるものがコメント
#以降の行末までがコメント
C
#include <stdio.h>
void main()
{
/* コメント 1行目
コメント2行目 */
printf("Comment example\n"); // コメント
}
Output
Comment example
/*と*/の間にあるものがコメント
//以降の行末までがコメント
Python
def main():
print('Line 1')
print('Line 2'); print('Line 3')
print( \
'Line 4' \
)
if __name__ == '__main__':
main()
Output
Line 1
Line 2
Line 3
Line 4
1つの行に1つの命令
複数の命令を1行に書くときだけセミコロンをつける
複数の行をまたぐときは行末にバックスラッシュをつける
C
#include <stdio.h>
void main()
{
printf("Line 1\n");
printf("Line 2\n"); printf("Line
3\n");
printf(
"Line 4\n"
);
}
Output
Line 1
Line 2
Line 3
Line 4
1つの命令の最後にセミコロンをつける
複数の命令を1行に書く場合も,複数の行にまたぐ場合も,いずれにせよセミコロンまでが1つの命令
Python
def main():
print('Example', end='')
print('Program')
print('')
print('Line1\nLine2')
if __name__ == '__main__':
main()
Output
ExampleProgram
Line1
Line2
改行させたくない場合はprintのendに''を指定する
改行させたい位置に\nを書く
C
#include <stdio.h>
void main()
{
printf("Example");
printf("Program\n");
printf("\n");
printf("Line1\nLine2\n");
}
Output
ExampleProgram
Line1
Line2
改行させたい位置に\nを書く
Python
import numpy as np
def main():
print('sqrt(2)=%f' % np.sqrt(2))
if __name__ == '__main__':
main()
Output
sqrt(2)=1.414214
importでsqrtが入っているライブラリを読み込む
C
#include <stdio.h>
#include <math.h>
void main()
{
printf("sqrt(2)=%f\n", sqrt(2.0));
}
Output
sqrt(2)=1.414214
#includeでsqrt関数が入っているライブラリを読み込む
printfが入っているのがstdio.hで,sqrtが入っているのがmath.h
Python
import sys
def main():
print(sys.argv[1])
if __name__ == '__main__':
main()
Command
python.exe cg2.py option
Output
option
argv[0]はプログラムの名前が入る
argv[1]は1つ目の引数が入る
C
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("%s\n", argv[1]);
return 0;
}
Command
cg2.exe option
Output
option
argv[0]はプログラムの名前が入る
argv[1]は1つ目の引数が入る
argcに引数の個数が入る
Python
def main():
print('Example', end='')
print('Program')
print('')
print('%d' % 7)
print('%f' % 2.5)
print('%s' % 'abc')
a = '%d minus %d is %s' % (5, 3, 'two')
print(a)
if __name__ == '__main__':
main()
Output
ExampleProgram
7
2.500000
abc
5 minus 3 is two
%dが整数,%fが浮動小数点数,%sが文字列
変数にそのまま代入できる
C
#include <stdio.h>
#pragma warning(disable:4996)
int main(int argc, char* argv[])
{
printf("Example");
printf("Program\n");
printf("\n");
printf("%d\n", 7);
printf("%f\n", 2.5);
printf("%s\n", "abc");
char a[256];
sprintf(a, "%d minus %d is %s\n", 5,
3, "two");
printf("%s\n", a);
return 0;
}
Output
ExampleProgram
7
2.500000
abc
5 minus 3 is two
%dが整数,%fが浮動小数点数,%sが文字列
変数に代入する場合はsprintf関数を使う
Python
def main():
a = 10
b = 2.5
c = 2.5
d = '@'
e = 'abc'
print(a)
print(type(a))
print(b)
print(type(b))
print(c)
print(type(c))
print(d)
print(type(d))
print(e)
print(type(e))
if __name__ == '__main__':
main()
Output
10
<class 'int'>
2.5
<class 'float'>
2.5
<class 'float'>
@
<class 'str'>
abc
<class 'str'>
変数の定義にデータ型を書かなくても自動的に判断される
内部ではデータ型が設定されている
int型が整数の型で,表現できる整数に限界はない
float型が浮動小数点の型で,64ビットで表現される範囲の値を表現できる
str型が文字列の型
typeを使うとデータ型が分かる
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a = 10;
float b = 2.5f;
double c = 2.5;
char d = '@';
char e[4] = "abc";
printf("%d\n", a);
printf("%d\n", sizeof(a));
printf("%f\n", b);
printf("%d\n", sizeof(b));
printf("%f\n", c);
printf("%d\n", sizeof(c));
printf("%c\n", d);
printf("%d\n", sizeof(d));
printf("%s\n", e);
printf("%d\n", sizeof(e));
return 0;
}
Output
10
4
2.500000
4
2.500000
8
@
1
abc
4
変数の定義のときに必ずデータ型を指定する
int型は32ビットで表現される範囲の整数
float型は32ビットで表現される範囲の浮動小数点数
double型は64ビットで表現される範囲の浮動小数点数
例えば,2はint型,2.0fはfloat型,2.0はdouble型
char型は文字の型(あるいは,8ビットで表現される範囲の整数)
1文字なので,複数文字を表す場合は配列で表す
1文字はシングルクォーテーションで囲み,2文字以上はダブルクォーテーションで囲む
sizeofを使うとデータ型のバイト数が分かる
Python
def main():
print(1 | 2 | 4 | 8 | 16 | 32 | 64 | 128)
if __name__ == '__main__':
main()
Output
255
ここではOR演算(ビット和)だけを紹介したが,他のビット演算も同様
C
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("%d\n", 1 | 2 | 4 | 8 | 16 | 32
| 64 | 128);
return 0;
}
Output
255
ここではOR演算(ビット和)だけを紹介したが,他のビット演算も同様
Python
import sys
def main():
print(1 + 2)
print(5 - 2)
print(3 * 4)
print(3 ** 2)
print('20 ÷ 7 の余りは', 20 % 7)
a = 10
a = a + 3
a += 2
a += 1
print(a)
if __name__ == '__main__':
main()
Output
3
3
12
9
20 ÷ 7 の余りは 6
16
累乗(べき乗)の演算子は**
C
#include <stdio.h>
void main(int argc, char* argv[])
{
printf("%d\n", 1 + 2);
printf("%d\n", 5 - 2);
printf("%d\n", 3 * 4);
printf("%d\n", 3 * 3);
printf("20 ÷ 7 の余りは %d\n", 20 % 7);
int a = 10;
a = a + 3;
a += 2;
a++;
printf("%d\n", a);
}
Output
3
3
12
9
20 ÷ 7 の余りは 6
16
C言語はa=a+1の代わりとしてa++という表現ができる
C言語には累乗(べき乗)の演算子はないのでpow関数を使う
Python
def main():
a = 5
b = 2
print(a / b)
print(a // b)
if __name__ == '__main__':
main()
Output
2.5
2
a/bは浮動小数点同士の割り算として計算される
a//bは整数同士の割り算として計算される
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a = 5;
int b = 2;
double c = a / b;
printf("%f\n", c);
double d = 5.0;
double e = 2.0;
printf("%f\n", d / e);
return 0;
}
Output
2.000000
2.500000
a/bは,aとbが整数なので,整数同士の割り算として計算される
d/eは,dとeが浮動小数点なので,浮動小数点同士の割り算として計算される
Python
def main():
a = 1.5
b = 2.5
c = int(a) + int(b)
print(c)
d = 5
e = 2
f = float(d) / float(e)
print(f)
g = d / e
print(g)
h = d // e
print(h)
if __name__ == '__main__':
main()
Output
3
2.5
2.5
2
意図した計算結果にするためには,データ型が適切かよく考えて,必要に応じてデータ型を変換する
C
#include <stdio.h>
int main(int argc, char* argv[])
{
double a = 1.5;
double b = 2.5;
int c = (int)a + (int)b;
printf("%d\n", c);
int d = 5;
int e = 2;
double f = (double)d / (double)e;
printf("%f\n", f);
double g = d / e;
printf("%f\n", g);
double h = (int)d / (int)e;
printf("%f\n", h);
return 0;
}
Output
3
2.500000
2.000000
2.000000
意図した計算結果にするためには,データ型が適切かよく考えて,必要に応じてデータ型を変換する
Python
def main():
a = [1, 2, 3]
print(a[0])
print(a[1])
print(a[2])
a[2] = a[1] + 8
print(a[2])
b = []
b.append(100)
b.append(200)
b.append(300)
print(b)
c = [[1, 2], [3, 4]]
print(c[1][0])
if __name__ == '__main__':
main()
Output
1
2
3
10
[100, 200, 300]
3
リスト
添え字は0から始まる
リストなので,途中で要素を追加できる
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a[3] = { 1, 2, 3 };
printf("%d\n%d\n%d\n", a[0], a[1], a[2]);
a[2] = a[1] + 8;
printf("%d\n", a[2]);
int b[3];
b[0] = 100;
b[1] = 200;
b[2] = 300;
printf("%d %d %d\n", b[0], b[1], b[2]);
int c[2][2] = { {1, 2}, {3, 4} };
printf("%d\n", c[1][0]);
return 0;
}
Output
1
2
3
10
100 200 300
3
配列
添え字は0から始まる
(静的)配列なので,途中で要素を追加できない
Python
def main():
a = 'abc'
print(ord(a[0]))
print(ord(a[1]))
print(ord(a[2]))
if __name__ == '__main__':
main()
Output
97
98
99
ordでASCIIコードに変換できる
C
#include <stdio.h>
int main(int argc, char* argv[])
{
char s[10] = "abc";
printf("%d\n", s[0]);
printf("%d\n", s[1]);
printf("%d\n", s[2]);
printf("%d\n", s[3]);
return 0;
}
Output
97
98
99
0
文字列の最後にヌル文字が入っている
それによって,どこまでが文字列か分かるようになっている
ヌル文字は0という数値(のASCIIコード)で'\0'と書くこともある
Python
def main():
a=[0]
p=a
p[0]=1
print(a)
if __name__ == '__main__':
main()
Output
[1]
Pythonにポインタはない
リストやオブジェクトは参照が代入される
pはaへの参照
pが指し示す先の実体の内容を変えることと
aが指し示す先の実体の内容を変えることは同じ
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a;
int* p;
p = &a;
*p = 1;
printf("%d\n", a);
return 0;
}
Output
1
データ型の定義に*を付けると,それはポインタ型を表す
変数に&を付けると,その変数へのポインタになる
ポインタ変数に*を付けると,その中身にアクセスできる
pはaへのポインタ
*pはポインタが指し示す先の実体
つまり*pはaのこと
*pの内容を変えることと
aの内容を変えることは同じ
Python
def main():
a=[[0],[0],[0]]
i=iter(a)
p=next(i)
p[0]=1
p=next(i)
p[0]=2
p=next(i)
p[0]=3
print(a)
if __name__=='__main__':
main()
Output
[[1], [2], [3]]
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a[3];
int* p;
p = a;
*p = 1;
p++;
*p = 2;
p++;
*p = 3;
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}
Output
1 2 3
Python
def main():
a = 2
if a == 1:
print('a is 1')
if a == 2:
print('a is 2')
if __name__ == '__main__':
main()
Output
a is 2
if文の効いている範囲はインデントであらわす
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a = 2;
if (a == 1) printf("a is 1\n");
if (a == 2) printf("a is 2\n");
return 0;
}
Output
a is 2
この例の場合,1つ分の命令がif文の効いている範囲
Python
def main():
a = 5
if a < 5:
print('a < 5')
else:
print('a >= 5')
if __name__ == '__main__':
main()
Output
a >= 5
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a = 5;
if (a < 5) printf("a < 5\n");
else printf("a >= 5\n");
return 0;
}
Output
a >= 5
Python
import sys
def main():
a = 5
if a >= 0 and a <= 10:
print('0 <= a <=
10')
if a != 0:
print('a is not zero')
b = -15
if -20 <= b <= -10:
print('correct')
else:
print('wrong')
if __name__ == '__main__':
main()
Output
0 <= a <= 10
a is not zero
correct
C
#include <stdio.h>
void main(int argc, char* argv[])
{
int a = 5;
if (a >= 0 && a <= 10) printf("0
<= a <= 10\n");
if (a != 0) printf("a is not zero\n");
int b = -15;
if (-20 <= b <= -10) printf("correct\n");
else printf("wrong\n");
}
Output
0 <= a <= 10
a is not zero
wrong
&はビット演算で,&&がブール演算
比較演算子を複数つなげることはできない
Python
def main():
s = 0
for i in range(0, 10):
s += i + 1
print(s)
if __name__ == '__main__':
main()
Output
55
for文の効いている範囲はインデントであらわす
iは0, 1, 2, 3, 4, 5, 6, 7, 8, 9の10回ループする
range(0, 10)は0以上10未満の整数の範囲
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
int s = 0;
for (i = 0; i < 10; i++) {
s += i + 1;
}
printf("%d\n", s);
return 0;
}
Output
55
この例の場合,{}で囲まれた範囲がfor文の効いている範囲
iは0, 1, 2, 3, 4, 5, 6, 7, 8, 9の10回ループする
for(式1;式2;式3)の式1は最初に実行される処理,式2は終了条件,式3はループごとに実行される処理
まず,i=0が実行される
i<10ならfor文の中身を実行し,i>=10ならfor文を抜ける
for文の中身(s+=i+1)の実行が終了したあと,i++する
Python
def main():
a = 0
while a < 10:
print('continue')
a += 1
if __name__ == '__main__':
main()
Output
continue
continue
continue
continue
continue
continue
continue
continue
continue
continue
while文の効いている範囲はインデントであらわす
C
#include <stdio.h>
int main(int argc, char* argv[])
{
int a = 0;
while (a < 10) {
printf("continue\n");
a++;
}
return 0;
}
Output
continue
continue
continue
continue
continue
continue
continue
continue
continue
continue
この例の場合,{}で囲まれた範囲がwhile文の効いている範囲
Python
import random
def main():
while True:
a = random.randint(0, 99)
print(a, '', end='')
if a == 77:
break
if __name__ == '__main__':
main()
Output
14 53 81 48 38 97 42 17 61 6 35 7 70 18 39 99 14 61 68 84 14 34 4 23 34 42 88 83 3 2 37 0 5 68 43 70 77
C
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int a;
while (true) {
a = rand() % 100;
printf("%d ",
a);
if (a == 77) break;
}
return 0;
}
Output
41 67 34 0 69 24 78 58 62 64 5 45 81 27 61 91 95 42 27 36 91 4 2 53 92 82 21 16 18 95 47 26 71 38 69 12 67 99 35 94 3 11 22 33 73 64 41 11 53 68 47 44 62 57 37 59 23 41 29 78 16 35 90 42 88 6 40 42 64 48 46 5 90 29 70 50 6 1 93 48 29 23 84 54 56 40 66 76 31 8 44 39 26 23 37 38 18 82 29 41 33 15 39 58 4 30 77
Python
def myfunc():
print('My function')
def main():
myfunc()
if __name__ == '__main__':
main()
Output
My function
関数の中身の範囲はインデントであらわす
C
#include <stdio.h>
void myfunc()
{
printf("My function\n");
}
int main(int argc, char* argv[])
{
myfunc();
return 0;
}
Output
My function
{}で囲まれた範囲が関数の中身の範囲
Python
def myfunc(a):
print(a)
def main():
myfunc(1)
if __name__ == '__main__':
main()
Output
1
C
#include <stdio.h>
void myfunc(int a)
{
printf("%d\n", a);
}
int main(int argc, char* argv[])
{
myfunc(1);
return 0;
}
Output
1
Python
def myfunc():
return 2
def main():
print(myfunc())
if __name__ == '__main__':
main()
Output
2
C
#include <stdio.h>
int myfunc()
{
return 2;
}
int main(int argc, char* argv[])
{
printf("%d\n", myfunc());
return 0;
}
Output
2
関数の型は戻り値(返り値)の型にする
戻り値がない関数の型はvoid型にする
Python
def myfunc(a):
a = 2
def main():
a = 1
myfunc(a)
print(a)
if __name__ == '__main__':
main()
Output
1
関数内の値は呼び出し元の引数に影響しない
C
#include <stdio.h>
void myfunc(int a)
{
a = 2;
}
int main(int argc, char* argv[])
{
int a = 1;
myfunc(a);
printf("%d\n", a);
return 0;
}
Output
1
関数内の値は呼び出し元の引数に影響しない
Python
def myfunc1(a):
a[0] = 2
def myfunc2(b):
b[0] = 3
b[1] = 4
def main():
a = [1]
myfunc1(a)
print(a[0])
b = [1,1]
myfunc2(b)
print(b)
if __name__ == '__main__':
main()
Output
2
[3, 4]
関数の中から,呼び出し元の引数の値を変えることができる
C
#include <stdio.h>
#include <stdlib.h>
void myfunc1(int* a)
{
*a = 2;
}
void myfunc2(int b[2])
{
b[0] = 3;
b[1] = 4;
}
int main(int argc, char* argv[])
{
int a = 1;
myfunc1(&a);
printf("%d\n", a);
int b[2] = { 1,1 };
myfunc2(b);
printf("%d %d\n", b[0], b[1]);
return 0;
}
Output
2
3 4
関数の中から,呼び出し元の引数の値を変えることができる
Python
a = 1
def myfunc1():
global a
a = 2
def myfunc2():
a = 3
def main():
print(a)
myfunc1()
print(a)
myfunc2()
print(a)
if __name__ == '__main__':
main()
Output
1
2
2
その関数内でグローバル変数として使うグローバル変数にはglobalを付ける
C
#include <stdio.h>
int a = 1;
void myfunc1()
{
a = 2;
}
void myfunc2()
{
int a = 3;
}
int main(int argc, char* argv[])
{
printf("%d\n", a);
myfunc1();
printf("%d\n", a);
myfunc2();
printf("%d\n", a);
return 0;
}
Output
1
2
2
その関数内で定義されていない変数はグローバル変数を使う
Python
import sys
import random
def myfunc():
a = random.randint(0, 99)
print(a, ' ', end='')
if a == 77:
sys.exit(0)
def main():
while True:
myfunc()
if __name__ == '__main__':
main()
Output
27 69 73 53 4 60 5 6 73 24 51 14 10 9 78 35 95 16 27 19 40 52 50 23 42 0 5 80 16 9 59 8 5 53 59 39 0 25 84 34 7 54 92 77
C
#include <stdio.h>
#include <stdlib.h>
void myfunc()
{
int a = rand() % 100;
printf("%d ", a);
if (a == 77) exit(0);
}
int main(int argc, char* argv[])
{
while(true) {
myfunc();
}
return 0;
}
Output
41 67 34 0 69 24 78 58 62 64 5 45 81 27 61 91 95 42 27 36 91 4 2 53 92 82 21 16 18 95 47 26 71 38 69 12 67 99 35 94 3 11 22 33 73 64 41 11 53 68 47 44 62 57 37 59 23 41 29 78 16 35 90 42 88 6 40 42 64 48 46 5 90 29 70 50 6 1 93 48 29 23 84 54 56 40 66 76 31 8 44 39 26 23 37 38 18 82 29 41 33 15 39 58 4 30 77
Python
import numpy as np
def main():
print('cos 30 degree is', np.cos(30.0 / 180.0 *
np.pi))
print('sin 30 degree is', np.sin(30.0 / 180.0 *
np.pi))
print('absolute value of', -2, 'is', abs(-2))
if __name__ == '__main__':
main()
Output
cos 30 degree is 0.8660254037844387
sin 30 degree is 0.49999999999999994
absolute value of -2 is 2
C
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
int main(int argc, char* argv[])
{
printf("cos 30 degree is %f\n", cos(30.0
/ 180.0 * M_PI));
printf("sin 30 degree is %f\n", sin(30.0
/ 180.0 * M_PI));
printf("absolute value of %d is %d\n",
-2, abs(-2));
return 0;
}
Output
cos 30 degree is 0.866025
sin 30 degree is 0.500000
absolute value of -2 is 2
Python
def main():
with open('text.txt', mode='w') as f:
f.write('Text file\n')
with open('text.txt', mode='r') as f:
s = f.readline()
print(s)
a = bytes([97, 98, 99])
with open('binary.bin', mode='wb') as f:
f.write(a)
with open('binary.bin', mode='rb') as f:
b = f.read(3)
print(int(b[0]), int(b[1]), int(b[2]))
if __name__ == '__main__':
main()
Output
Text file
97 98 99
Output text.txt
Text file
と書かれた11バイトのテキストファイル
16進数で54,65,78,74,20,66,69,6C,65,0D,0Aと書かれた11バイトのバイナリファイル
なお,0DはCR(キャリッジリターン)のASCIIコードであり,0AはLF(ラインフィード)のASCIIコードである
この場合,この2つのASCIIコードで改行を表している
Output binary.bin
abc
1バイト目に97,2バイト目に98,3バイト目に99と書かれた3バイトのバイナリファイル
C
#include <stdio.h>
#pragma warning(disable:4996)
int main(int argc, char* argv[])
{
FILE* fp;
char s[256];
unsigned char a[3] = { 97, 98, 99 };
unsigned char b[3];
fp = fopen("text.txt", "w");
fprintf(fp, "Text file\n");
fclose(fp);
fp = fopen("text.txt", "r");
fgets(s, 255, fp);
fclose(fp);
printf("%s", s);
fp = fopen("binary.bin", "wb");
fwrite(a, sizeof(unsigned char), 3, fp);
fclose(fp);
fp = fopen("binary.bin", "rb");
fread(b, sizeof(unsigned char), 3, fp);
fclose(fp);
printf("%d %d %d\n", b[0], b[1], b[2]);
return 0;
}
Output
Text file
97 98 99
Output text.txt
Text file
と書かれた11バイトのテキストファイル
16進数で54,65,78,74,20,66,69,6C,65,0D,0Aと書かれた11バイトのバイナリファイル
なお,0DはCR(キャリッジリターン)のASCIIコードであり,0AはLF(ラインフィード)のASCIIコードである
この場合,この2つのASCIIコードで改行を表している
Output binary.bin
abc
1バイト目に97,2バイト目に98,3バイト目に99と書かれた3バイトのバイナリファイル