在学习了C和python之后或者更多语言之后,可能一段时间不使用,就会对基本的流程控制语句混淆, 但是本质都是一样的,只是形式的差别,这里总结一下几种语言基本流程控制的写法差异 .
1 条件判断
重点是为了区分写法差异,我们使用最简单的例子说明。
1.1 if else
C
int x = 5;
if(x>0){
x = 1;
}else if(x<0){
x = -1;
}else{
x = 0;
};
printf("%d",x);
python
x = 5
if x>0:
x = 1
elif x<0:
x=-1
else :
x = 0
print(x)
R和C一致
x = 5
if(x>0){
x = 1;
}else if(x<0){
x = -1;
}else{
x = 0;
};
print(x)
1.2 switch case
C , case 是定位到当前语句,并不是像if else 那样选择一条,所以后面不需要执行需要加break 。
int i = 14;
switch(i){
case 1:
printf("yi");
break;
case 2 :
printf("er");
break;
default:
printf("what?");
break;
}
python不支持switch case, 因为一直用elif也可以实现,用字典也可以
i = 1
def switch_case(value):
switcher = {
1: "yi",
2: "er"
}
return switcher.get(value,"what?")
print(switch_case(1))
R 中switch将i 强制转化为整数, 与之后的未位置匹配, 没有default可用, 感觉不太好用, 不如直接if else .
i <-1
print(switch(i , "yi","er" ))
"yi"
2 循环
2.1 for
C
int i;
for(i=0;i<5;i++){
printf("%d\n",i);
}
return 0;
python
for i in range(5):
print(i)
R
for( i in seq(1:5)){
print(i);
}
2.2 while
int i;
while(i<5){
printf("%d\n",i);
i++;
};
i = 0
while i<5:
print(i);
i = i + 1
R
i <- 0
while (i < 5) {
print(i);
i = i + 1;
}
2.3 do while
C
int i = 0;
do{
printf("%d\n",i);
i++;
}while(i<5); // 不满足条件退出
python 不支持do while ,可用 break替代 ,注意终止条件不同
i = 0
while True: #无限循环...
print(i);
i = i+1;
if i>4:
break
R 也没有do while ,支持 repeat break;
i <- 0
repeat {
print(i);
i = i+1;
if(i>4) {
break;
}
}
3 定义函数
c是有类型的语言, 定义函数严格一点, 声明输入,输出类型。
int testfunc(int x){
x = x+1 ;
return x ;
}
printf("%d",testfunc(1));
python 比较简便
def testfunc(x):
x = x+1;
return x;
print(testfunc(1))
r 中return要加括号
testfunc<-function(x){
x <- x+1;
return(x)
}
print(testfunc(1));