Python
print('Python program')
File name
myprogram.py
Output
Python program
ファイル名はなんでもいい
Java
public class myprogram{
public static void main(String [] args){
System.out.println("Java
program");
}
}
File name
myprogram.java
Output
Java program
ファイル名とクラス名は同じでなければいけない
Python
def main():
print('Python program')
if __name__ == '__main__':
main()
Output
Python program
上から順番に実行される
この場合,if文が実行され,main関数が呼び出される
Java
public class myprogram{
public static void main(String [] args){
System.out.println("Java
program");
}
}
Output
Java program
Python
def main():
''' Comment 1st line
Comment 2nd line '''
print('Python program') # Comment
if __name__ == '__main__':
main()
Output
Python program
'''と'''の間にあるものがコメント
#以降の行末までがコメント
Java
public class myprogram{
public static void main(String [] args){
/* Comment 1st line
Comment 2nd line */
System.out.println("Java
program"); // Comment
}
}
Output
Java program
/*と*/の間にあるものがコメント
//以降の行末までがコメント
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行に複数の命令を書く場合はセミコロンで区切る
1つの命令が行をまたぐ場合は行末にバックスラッシュをつける
Java
public class myprogram{
public static void main(String [] args){
System.out.println("Line
1");
System.out.println("Line
2"); System.out.println("Line 3");
System.out.println(
"Line
4"
);
}
}
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で改行を表す
Java
public class myprogram{
public static void main(String [] args){
System.out.print("Example");
System.out.println("Program");
System.out.println();
System.out.println("Line1\nLine2");
}
}
Output
ExampleProgram
Line1
Line2
println関数は文字を出力して改行する
改行しない場合はprint関数を使う
\nで改行を表す
Python
def main():
a=10
b=2.5
c=2.5
d="abc"
e=True
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'>
abc
<class 'str'>
True
<class 'bool'>
変数を定義するとき,データ型を書く必要はない
整数のデータ型はint型で,表現できる数値に制限はない
浮動小数点数のデータ型はfloat型で,64ビット浮動小数点数
文字列のデータ型はstr型
ブール値のデータはbool型
Pythonのデータ型はすべてクラス型
Java
public class myprogram{
public static void main(String [] args){
int a=10;
float b=2.5f;
double c=2.5;
String d="abc";
boolean e=true;
System.out.println(a);
System.out.println(((Object)a).getClass().getSimpleName());
System.out.println(b);
System.out.println(((Object)b).getClass().getSimpleName());
System.out.println(c);
System.out.println(((Object)c).getClass().getSimpleName());
System.out.println(d);
System.out.println(((Object)d).getClass().getSimpleName());
System.out.println(e);
System.out.println(((Object)e).getClass().getSimpleName());
}
}
Output
10
Integer
2.5
Float
2.5
Double
abc
String
true
Boolean
変数を定義するとき,データ型を必ず書く
int型は32ビット整数のデータ型
float型は32ビット浮動小数点数のデータ型
double型は64ビット浮動小数点数のデータ型
String型は文字列のデータ型
booleanはブール値のデータ型
プリミティブ型:int型,float型,double型,boolean型
にはそれぞれに対応する
クラス型:Integer型,Float型,Double型,Boolean型
が用意されている
プリミティブ型はクラスではなく,そのデータだけが格納されたデータ型
例えばint型は整数をあらわす32ビット分のデータがあるだけであり,クラスとしてのメソッドやフィールドは存在しない
Python
def main():
print(1|2|4|8|16|32|64|128)
if __name__ == '__main__':
main()
Output
255
ビットのOR演算は|
ビットのAND演算は&
Java
public class myprogram{
public static void main(String [] args){
System.out.println(1|2|4|8|16|32|64|128);
}
}
Output
255
ビットのOR演算は|
ビットのAND演算は&
Python
def main():
print(20%7)
print(3**2)
a=10
a+=1
print(a)
if __name__ == '__main__':
main()
Output
6
9
11
四則演算の演算子は+-*/
割り算の余りは%
累乗(べき乗)は**
++という演算子はない
Java
public class myprogram{
public static void main(String [] args){
System.out.println(20%7);
System.out.println(Math.pow(3,2));
int a=10;
a++;
System.out.println(a);
}
}
Output
6
9.0
11
四則演算の演算子は+-*/
割り算の余りは%
累乗(べき乗)はMath.pow関数を使う
++という演算子は1増やす演算子
Python
def main():
print(5//2)
print(5/2)
if __name__ == '__main__':
main()
Output
2
2.5
整数の割り算は//
浮動小数点数の割り算は/
Java
public class myprogram{
public static void main(String [] args){
System.out.println(5/2);
System.out.println(5.0/2.0);
}
}
Output
2
2.5
5も2も整数なので5/2は整数の割り算
5.0も2.0も浮動小数点数なので5.0/2.0は浮動小数点数の割り算
Python
def main():
a=[0,0]
a[0]=1
a[1]=2
print(a[0])
print(a[1])
if __name__ == '__main__':
main()
Output
1
2
リスト
Java
public class myprogram{
public static void main(String [] args){
int[] a=new int[2];
a[0]=1;
a[1]=2;
System.out.println(a[0]);
System.out.println(a[1]);
}
}
Output
1
2
配列
new演算子でメモリを確保する
Python
def main():
a=5
b=2
print(float(a)/float(b))
c=[0,0]
c[0]=1
c[1]=2
d=1.01
print(c[int(d)])
if __name__ == '__main__':
main()
Output
2.5
2
intやfloatなどを使ってデータ型を変換できる
Java
public class myprogram{
public static void main(String [] args){
int a=5;
int b=2;
System.out.println((double)a/(double)b);
int[] c=new int[2];
c[0]=1;
c[1]=2;
double d=1.01;
System.out.println(c[(int)d]);
}
}
Output
2.5
2
intやdoubleなどを使ってデータ型を変換できる
Python
def main():
a='a'
b='b'
c=0
print(a+b)
print(a+str(c))
if __name__ == '__main__':
main()
Output
ab
a0
文字列同士を+で連結できる
数値はstr型に変換してから連結する
Java
public class myprogram{
public static void main(String [] args){
String a="a";
String b="b";
int c=0;
System.out.println(a+b);
System.out.println(a+c);
}
}
Output
ab
a0
文字列同士を+で連結できる
数値もそのまま連結できる
Python
def main():
a=15
print('a%03d'%a)
b='a% 3d'%a
print(b)
if __name__ == '__main__':
main()
Output
a015
a 15
文字列の中に%dを書いて,そのあとで%を書き,そのあとで整数を書けば,その数値が文字列になる
Java
public class myprogram{
public static void main(String [] args){
int a=15;
System.out.printf("a%03d\n",a);
String b=String.format("a%
3d",a);
System.out.println(b);
}
}
Output
a015
a 15
printf関数を使い,文字列の中に%dを書いて,2つ目の引数に整数を書けば,その数値が文字列になって出力される
変数に代入する場合はString.format関数を使う
Python
def main():
a=[1,2]
print(a[0])
print(a[1])
if __name__ == '__main__':
main()
Output
1
2
リストを作成して変数に代入
Java
public class myprogram{
public static void main(String [] args){
int[] a=new int[]{1,2};
System.out.println(a[0]);
System.out.println(a[1]);
}
}
Output
1
2
new演算子のあとに配列に代入する値を書く
Python
def main():
a=[[1,2],[3,4]]
print(a[0][1])
b=[['' for _ in range(2)] for _ in range(2)]
b[0][0]='a'
b[0][1]='b'
b[1][0]='c'
b[1][1]='d'
print(b)
if __name__ == '__main__':
main()
Output
2
[['a', 'b'], ['c', 'd']]
2×2のリストの例
Java
import java.util.*;
public class myprogram{
public static void main(String [] args){
int[][] a=new int[][]{{1,2},{3,4}};
System.out.println(a[0][1]);
String[][] b=new String[2][2];
b[0][0]="a";
b[0][1]="b";
b[1][0]="c";
b[1][1]="d";
System.out.println(Arrays.deepToString(b));
}
}
Output
2
[[a, b], [c, d]]
2×2の配列の例
Python
def main():
a=[1,2]
print(len(a))
if __name__ == '__main__':
main()
Output
2
len関数でリストの長さが分かる
Java
public class myprogram{
public static void main(String [] args){
int[] a=new int[]{1,2};
System.out.println(a.length);
}
}
Output
2
配列もクラスで,lengthフィールドを持っていて,それを使えば配列の長さが分かる
Python
def main():
a=[1,2][0]
print(a)
if __name__ == '__main__':
main()
Output
1
作成したオブジェクトはコードの途中でも使用することができる
Java
public class myprogram{
public static void main(String [] args){
int a=(new int[]{1,2})[0];
System.out.println(a);
}
}
Output
1
作成したオブジェクトはコードの途中でも使用することができる
Python
import numpy as np
def main():
print(np.random.randint(10))
if __name__ == '__main__':
main()
Output
1
ライブラリはimportで読み込む
Java
import java.util.*;
public class myprogram{
public static void main(String [] args){
Random rnd=new Random();
System.out.println(rnd.nextInt(10));
}
}
Output
5
ライブラリはimportで読み込む
Python
import numpy as np
def main():
a=np.ndarray((2,2))
b=np.empty((2,2))
c=np.zeros((2,2))
d=np.array([[1,2],[3,4]])
print(type(a))
print(type(b))
print(type(c))
print(type(d))
if __name__ == '__main__':
main()
Output
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
オブジェクト作成時にコンストラクタが呼び出される
データ型のあとの()に,コンストラクタに渡す引数を指定する
Pythonのライブラリはコンストラクタを呼び出してのオブジェクト作成が推奨されていないライブラリが多い
例えば,numpy行列を作成する際,そのクラス名はndarrayだが,ndarrayを使って行列を作成することは推奨されていない
numpy行列を作成する際はemptyやzerosやarrayなどを使うことが推奨されている
Java
import java.util.*;
public class myprogram{
public static void main(String [] args){
String a=new String();
String b=new String("b");
System.out.println(a);
System.out.println(b);
}
}
Output
b
オブジェクト作成時にコンストラクタが呼び出される
データ型のあとの()に,コンストラクタに渡す引数を指定する
Python
def main():
a=1
b=2
c=3
if a==1 and b==2:
print('a1b2')
if a==2:
print('a2')
elif a==1 or b==1:
print('a1')
else:
print('a?')
if c>b>a: print('correct')
else: print('wrong')
if __name__ == '__main__':
main()
Output
a1b2
a1
correct
if文の範囲はインデントで表す
elifはelse ifの略
論理演算子はandやorなど
c>b>aのように比較演算子を複数つなげてもよい
Java
public class myprogram{
public static void main(String [] args){
int a=1;
int b=2;
int c=3;
if(a==1&&b==2)System.out.println("a1b2");
if(a==2)System.out.println("a2");
else if(a==1||b==1)System.out.println("a1");
else System.out.println("a?");
if(c>b&&b>a)System.out.println("correct");
else System.out.println("wrong");
}
}
Output
a1b2
a1
correct
if文の範囲は,命令1つ,または,{}で囲んだ範囲
else ifでelifを表す
論理演算子は&&や||など
c>b>aのように比較演算子を複数つなげることはできない
Python
def main():
a = 7
b = 'even' if a % 2 == 0 else 'odd'
print(b)
if __name__ == '__main__':
main()
Output
odd
命令文の途中のif文
(真の場合) if (条件) else (偽の場合)
Java
public class myprogram{
public static void main(String [] args){
int a=7;
String b = (a%2==0) ? "even"
: "odd";
System.out.println(b);
}
}
Output
odd
3項演算子
(条件) ? (真の場合) : (偽の場合)
Python
def main():
a=0
while True:
print(a)
a+=1
if a>=10:
break
if __name__=='__main__':
main()
Output
0
1
2
3
4
5
6
7
8
9
while文の範囲はインデントで表す
Java
public class myprogram{
public static void main(String [] args){
int a=0;
while(true){
System.out.println(a);
a++;
if(a>=10)break;
}
}
}
Output
0
1
2
3
4
5
6
7
8
9
while文の範囲は,命令1つ,または,{}で囲んだ範囲
Python
def main():
for i in range(0,10):
print(i)
if __name__ == '__main__':
main()
Output
0
1
2
3
4
5
6
7
8
9
for文の範囲はインデントで表す
Pythonのfor文はすべてrange-based for文(foreach文)
range(0,10)は0以上,10未満,1ずつの範囲
Java
public class myprogram{
public static void main(String [] args){
for(int i=0;i<10;i++){
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5
6
7
8
9
for文の範囲は,命令1つ,または,{}で囲んだ範囲
for(○;△;×)
○はループに入る前の初回に呼び出される文
×はそれぞれのループの終了時に呼び出される文
△はループの最初で調べる条件式
この条件を満たす場合はループ継続
満たさない場合はループを抜ける
Python
def myfunc(a,b,c):
a+=1
b+=1
c[0]+=1
c[1]+=1
return str(a)+"+"+str(b)+"="+str(a+b)
def main():
x=1
y=2
z=[3,4]
w=myfunc(x,y,z)
print(x)
print(y)
print(z[0])
print(z[1])
print(w)
if __name__ == '__main__':
main()
Output
1
2
4
5
2+3=5
関数の使い方や性質は一般的なプログラミング言語とほぼ同じ
aとbは関数の外まで影響しない
cの中身は関数の外まで影響する
Java
public class myprogram{
private static String myfunc(int a,int b,int[]
c){
a++;
b++;
c[0]++;
c[1]++;
return new String(a+"+"+b+"="+(a+b));
}
public static void main(String [] args){
int x=1;
int y=2;
int[] z=new int[]{3,4};
String w=myfunc(x,y,z);
System.out.println(x);
System.out.println(y);
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(w);
}
}
Output
1
2
4
5
2+3=5
関数の使い方や性質は一般的なプログラミング言語とほぼ同じ
aとbは関数の外まで影響しない
cの中身は関数の外まで影響する
Python
a=1
def myfunc1(a):
a=2
def myfunc2():
a=3
def myfunc3():
global a
a=4
def main():
global a
print(a)
a=5
print(a)
myfunc1(a)
print(a)
myfunc2()
print(a)
myfunc3()
print(a)
while True:a=6;break
print(a)
if __name__ == '__main__':
main()
Output
1
5
5
5
4
6
a=1のaはグローバル変数としてmyfunc3とmainで使われている
myfunc1のaは値渡しのようなものなので,関数の呼び出し元には影響しない
myfunc2のaはローカル変数で,そのスコープはmyfunc2の中だけなので,myfunc2の外には影響しない
Java
public class myprogram{
private static int a=1;
private static void myfunc1(int a){
a=2;
}
private static void myfunc2(){
int a=3;
}
private static void myfunc3(){
a=4;
}
public static void main(String [] args){
System.out.println(a);
a=5;
System.out.println(a);
myfunc1(a);
System.out.println(a);
myfunc2();
System.out.println(a);
myfunc3();
System.out.println(a);
while(true){a=6;break;}
System.out.println(a);
while(true){int a=7;break;}
System.out.println(a);
}
}
Output
1
5
5
5
4
6
6
a=1のaはグローバル変数(正しくはフィールド(メンバ変数))としてmyfunc3とmainで使われている
myfunc1のaは値渡しなので,関数の呼び出し元には影響しない
myfunc2のaはローカル変数で,そのスコープはmyfunc2の中だけなので,myfunc2の外には影響しない
{と}で囲まれた範囲が変数のスコープ
{と}の外で定義された変数より,
{と}の中で定義された変数のほうが
優先される
Python
def main():
a=[]
a.append(1)
a.append(2)
b=[]
b.append('x')
b.append('y')
print(a)
print(b)
if __name__=='__main__':
main()
Output
[1, 2]
['x', 'y']
append関数でリストへ要素を追加する
リストの要素の型は指定しない
Java
import java.util.*;
public class myprogram{
public static void main(String [] args){
ArrayList<Integer>
a=new ArrayList<Integer>();
a.add(1);
a.add(2);
ArrayList<String>
b=new ArrayList<String>();
b.add("x");
b.add("y");
System.out.println(a.toString());
System.out.println(b.toString());
}
}
Output
[1, 2]
[x, y]
add関数でリストへ要素を追加する
リストの要素の型は<>で指定する
Python
def main():
a=[]
a.append(30)
a.append(40)
a.append(20)
a.append(10)
a.append(50)
print(a)
a.sort()
print(a)
if __name__ == '__main__':
main()
Output
[30, 40, 20, 10, 50]
[10, 20, 30, 40, 50]
sort関数でソート
Java
import java.util.*;
public class myprogram{
public static void main(String [] args){
ArrayList<Integer>
a=new ArrayList<Integer>();
a.add(30);
a.add(40);
a.add(20);
a.add(10);
a.add(50);
System.out.println(a.toString());
a.sort(null);
System.out.println(a.toString());
}
}
Output
[30, 40, 20, 10, 50]
[10, 20, 30, 40, 50]
sort関数でソート
Python
class animal:
def isanimal(self):
return True
def cry(self):
print('undefined')
class cat(animal):
def cry(self):
print('meow')
class dog(animal):
def cry(self):
print('bowwow')
class pig(animal):
def cry(self):
print('oink')
def main():
a=cat()
b=dog()
c=pig()
a.name='calico cat'
b.name='shiba inu'
c.name='iberian pig'
d=[a,b,c]
for e in d:
print(type(e))
print(e.isanimal())
print(e.name)
e.cry()
if __name__=='__main__':
main()
Output
<class '__main__.cat'>
True
calico cat
meow
<class '__main__.dog'>
True
shiba inu
bowwow
<class '__main__.pig'>
True
iberian pig
oink
catクラスとdogクラスとpigクラスがanimalクラスを継承している例
Java
public class myprogram{
private static class animal{
public String name;
public boolean isanimal(){
return
true;
}
public void cry(){
System.out.println("undefined");
}
}
private static class cat extends animal{
public void cry(){
System.out.println("meow");
}
}
private static class dog extends animal{
public void cry(){
System.out.println("bowwow");
}
}
private static class pig extends animal{
public void cry(){
System.out.println("oink");
}
}
public static void main(String [] args){
cat a=new cat();
dog b=new dog();
pig c=new pig();
a.name="calico cat";
b.name="shiba inu";
c.name="iberian pig";
animal[] d=new animal[]{a,b,c};
for(animal e:d){
System.out.println(e.getClass().getSimpleName());
System.out.println(e.isanimal());
System.out.println(e.name);
e.cry();
}
}
}
Output
cat
true
calico cat
meow
dog
true
shiba inu
bowwow
pig
true
iberian pig
oink
catクラスとdogクラスとpigクラスがanimalクラスを継承している例