プログラミング素人のはてなブログ

プログラミングも電気回路も専門外の技術屋の末端が勉強したことや作品をアウトプットするブログ。コードに間違いなど見つけられたら、気軽にコメントください。 C#、Python3、ラズパイなど。

C#とPythonの基本文法比較

C言語から初めて、C#(VC#)、Python3と学習を進めてきたが、ここでPythonのすばらしさを基本文法を整理することで見ていこうと思う。
以下ではC#とPyhtonの比較として整理するが、ここで例示するC#の文法はほとんどCと同じである。
また、C#Windowsでしか動作しないがPythonWindowsLinuxMacなどで動作するクロスプラットフォームな言語である。


※表記上、"インデント"は"____"で表す。

変数の定義と代入

C# Python3
int a=1; a=1
int b;
b=1;
定義のみは不可
定義した型と異なる値は代入できない c=1
c="1"

C#では変数は型定義と代入が必要だが、Pythonでは代入によって型が決定される

数値から文字列への変換

C# Python3
int a=1;
string b;
b=a.ToString();
a=1
b=str(a)

文字列から数値への変換

C# Python3
string b="1";
int a;
a=(int)b;
b="1"
a=int(b)

演算子

C# Python3
c=a+b; c=a+b
c=a-b; c=a-b
c=a/b; c=a/b
c=a*b; c=a*b
c=a%b; c=a%b
c=Math.Pow(a, b); c=a**b

C#ではべき乗はMathクラスのインポートが必要

文字列の置換

C# Python3
line = line.Replace("before", "after"); line=line.replace("before","after")

置換後の文字列を””(blank)にすると削除できる。

for文

C# Python3
for (int n = 1; n < 40; n++)
____ {xxxx
________}
for i in range(40):
____xxxxx

C#はfor文を”()”でくくり、中身は”{}”でくくる
Pythonはfor文は”:”で終わり改行とインデントが必須

if文

C# Python3
if (value == 1)
____{xxxx
____}
if value == 1:
____xxxxx

forと考え方は大体同じ、whileも同様

論理演算子

C# Python3
if (a==b &&c==d) if a==b and c==d:
if (a==b || c==d) if a==b or c==d:

Python の"and" , "or" のような書き方はVBに似ている

インクリメント(デクリメント)

C# Python3
n=n+1; n=n+1
n++; なし
n+=1; n+=1

デクリメントも同様

コンソール出力

C# Python3
Console.WriteLine("Hello C#"); print("Hello Python3")

C#ではsystemクラスのインポートが必要

配列(リスト)

C# Python3
string[] array = new string[4];
array[0]="a";
array[1]="b";
array[2]="c";
array[3]="d";
array=["a","b","c","d"]
異なる型は一つの配列に代入できない array=["aa",1,"cc",3]

Pythonでは型の混在したリストが可能
C#ではサイズを変更できる”リスト”とサイズを変更できない”配列”は明確に区別されるが、Pythonではサイズを変更できない”配列”は無い

スライス

C# Python3
string sample = text.Substring(start,length); sample=text[start:length]

※スライスとは要素の部分的取得をすること

例外処理

C# Python3
try
____{ xxxx }
catch
____{ MessageBox.Show("Error!!") }
finally
____{ MessageBox.Show("Either Error or Not!") }
try:
____xxxxx
except:
____print("Error!")
finally:
____print("Either Error or Not!")

ファイル読み込み

C# Python3
using System.IO;
string[] line = System.IO.File.ReadAllLines("xxxx.txt");
//一行ごとに配列に格納
f = open('xxxx.txt', 'r', encoding='utf')
list = f.readlines()
using System.IO;
string line;
StreamReader sr = new StreamReader("xxxx.txt");
while ((line=sr.ReadLine()) != null)
____{
// ファイルの末尾まで繰り返す
________}
file = open(’xxxx.txt', 'r', encoding='utf')
line = file.readline()
while line != "":
____line = file.readline()

Pythonでは読み込みは”r”を指定

ファイル書き込み

C# Python3
using System.IO;
using (StreamWriter writer = new StreamWriter("xxxx.txt", true, System.Text.Encoding.GetEncoding("utf-8")))
____{
________writer.Write("yyyy");
____}
file = open(’xxxx.txt', 'a', encoding='utf')
file.write("yyyy")

追記指定はC#では"true"、Pythonでは”a”。新規(上書)はC#では"false"、Pythonでは"w"とする。

参考資料