Python与C语言基础对比(Python快速入门)

作者: HeoLis | 来源:发表于2018-03-16 07:54 被阅读35次

    代码较长,建议使用电脑阅读本文。

    10分钟入门Python

    本文中使用的是Python3
    如果你曾经学过C语言,阅读此文,相信你能迅速发现这两种语言的异同,达到快速入门的目的。下面将开始介绍它们的异同。

    Python与C语言基本语法对比

    Python使用空格来限制代码的作用域,相当于C语言的{ }

    第一个程序 Hello,World!

    C语言

    #include<stdio.h>
    
    int main(){
        
        printf("Hello,World!");
        
        return 0;
    }
    

    Python

    print("Hello,World!")
    

    怎么样,是不是已经感受到Python的精巧了呢。

    输入输出

    C语言

    #include<stdio.h>
    
    int main(){
        int number;
        float decimal;
        char string[20];
        scanf("%d", &number);
        scanf("%f", &decimal);
        scanf("%s", string);
        
        printf("%d\n", number);
        printf("%f\n", decimal);
        printf("%s\n", string);
        
        return 0;
    }
    

    Python

    number = int(input())
    decimal = float(input())
    string = input()
    
    print(number)
    print(decimal)
    print(string)
    

    如果你尝试自己写一个Python循环输出语句,你肯定会发现Python的输出默认的换行的,如果不想让它换行,可给end参数复制"",例如

    连续输出不换行

    for i in range(0, 10):
        print(i, end="")
    

    代码注释

    C语言

    #include<stdio.h>
    
    int main()
    {
    
    //  printf("注释一行");
    
        /**
        printf("注释多行");
        printf("注释多行");
        printf("注释多行");
        printf("注释多行");
        **/
    }
    

    Python

    # print("注释一行")
    
    # 三个单引号
    '''
    print("单引号注释多行")
    print("单引号注释多行")
    print("单引号注释多行")
    print("单引号注释多行")
    '''
    # 三个双引号
    """
    print("双引号注释多行")
    print("双引号注释多行")
    print("双引号注释多行")
    print("双引号注释多行")
    """
    

    基本运算

    C语言

    #include<stdio.h>
    
    int main()
    {
        int Result;
        int a = 10, b = 20;
    
        // 加法
        Result = a + b;
        printf("%d\n", Result);
    
        // 自加
        Result++;
        ++Result ;
        printf("%d\n", Result);
    
        // 减法
        Result = b - a;
        printf("%d\n", Result);
    
        // 自减
        Result--;
        --Result;
        printf("%d\n", Result);
    
        // 乘法
        Result = a * b;
        printf("%d\n", Result);
        Result *= a;
        printf("%d\n", Result);
        
        // 除法
        Result = b / a;
        printf("%d\n", Result);
        Result /= a;
        printf("%d\n", Result); 
        
    }
    

    Python

    a = 10
    b = 20
    
    #  加法
    result = a + b
    print(result)
    
    # 减法
    result = a - b
    print(result)
    
    # 乘法
    result = a * b
    print(result)
    result *= a
    
    # 除法
    result = b / a
    print(result)
    result /= a
    print(result)
    

    注意:Python没有自加,自减运算符,即i++++ii----i,其他运算符基本与C语言相同。

    判断语句

    C语言

    #include<stdio.h>
    
    int main()
    {
        int a = 1, b = 2, c = 1;
    
        if(a == b)
        {
            printf("a == b");
        }
        else if(a == c)
        {
            printf("a == c");
        }
        else
        {
            printf("error");
        }
    }
    

    Python

    a = 1
    b = 2
    c = 1
    
    if a == b:
        print("a == b")
    elif a == c:
        print("a == c")
    else:
        print("error")
    

    elif相当于else if,其他用法与C语言相同。

    循环语句

    while循环

    C语言
    #include<stdio.h>
    int main()
    {
        int a = 0, b = 10;
        while(a < b)
        {
            a++;
        }
        printf("%d", a);
    }
    
    Python
    a = 0
    b = 10
    while a < b:
        a+=1
    else:
        print(a)
    

    for循环

    C语言
    #include<stdio.h>
    
    int main()
    {
        for(int i = 0; i < 10; i++){
            printf("%d\n", i);
        }
    }
    
    Python
    for i in range(0, 10):
        print(i)
    

    range(0, 10)表示创建一个在[0, 10)区间的整数列表,相当于C语言for循环中的i < 10条件

    函数

    C语言

    #include<stdio.h>
    
    int function(char name[], int age, float weight)
    {
        printf("Name:%s\n", name);
        printf("Age:%d\n", age);
        printf("Weight:%f\n", weight);
        return 1;
    }
    
    int main()
    {
        char name[20];
        int age;
        float weight;
        printf("请输入名字:");
        scanf("%s", name);
        printf("请输入年龄:");
        scanf("%d", &age);
        printf("请输入体重:");
        scanf("%f", &weight);
        if(function(name, age, weight) == 1)
        {
            printf("执行完毕");
        }
    
    }
    

    Python

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    
    def function(name, age, weight):
        print("Name:" + name)
        print("Age:", age)
        print("Weight", weight)
        return 1
    
    
    if __name__ == "__main__":
        name = input("请输入名字:")s
        age = input("请输入年龄:")
        weight = input("请输入体重:")
        if (function(name=name, age=age, weight=weight) == 1):
            print("执行完毕")
    

    注意代码的作用域,缩减相同表达的意思与C语言的{ }相同。

    导入头文件

    C语言

    #include<stdio.h>
    #include<math.h>
    
    float make_sqrt(float numA, float numB, float numC)
    {
        float sum = sqrt(numA + numB + numC);
        return sum;
    }
    
    int main()
    {
        float a, b, c, result;
        scanf("%f %f %f", &a, &b, &c);
        result = make_sqrt(a, b, c);
        printf("%f", result);
    
        return 0;
    }
    

    Python

    #!/usr/bin/env python
    # _*_coding:utf-8_*_
    import cmath
    import cmath as mt
    from cmath import sqrt
    
    def make_sqrt_sum(numA, numB, numC):
        sum1 = cmath.sqrt(numA + numB + numC)
        sum2 = mt.sqrt(numA + numB + numC)
        sum3 = sqrt(numA + numB + numC)
        return sum1, sum2, sum3;
    
    if __name__ == "__main__":
        a, b, c = map(float, input().split())
        result1, result2, result3 = make_sqrt_sum(a, b, c)
        print(result1, result2, result3)
    

    导入模块
    import cmath
    import cmath as mt
    from cmath import sqrt
    第一种方法是直接导入cmath库(sqrt模块包含在该库中),
    第二种方法是导入后给它起个别名(后面使用的使用不用敲那么长的名字了),
    第三种方法是直接导入cmath库中的sqrt模块(我们只用到了这个模块)。

    数组

    Python的数组相当灵活,这里直接介绍Python类似数组的组件,及其常用操作。

    列表

    列表中每个存储的每个元素可以是不同的类型,例如整数、小数、字符串等。列表中可以实现元素的添加、修改、删除操作,元素的值可以被修改。

    peopleList = ["eye", "mouth", "nose", "brow", "ear", 1.80, 120]
    print(peopleList)               # 输出整个列表
    print(peopleList[0])            # 访问索引为0的元素
    peopleList[1] = "head"          # 修改索引为1的元素
    peopleList.append("arm")        # 在列表末尾添加元素
    peopleList.insert(1, "foot")    # 在列表中插入元素
    del peopleList[0]               # 删除索引位置的元素
    result = peopleList.pop(0)      # 删除并引用索引位置的元素,先复制给result再从列表中删除
    peopleList.remove("nose")       # 根据值来删除元素
    

    元组

    元组与列表类似,不同的是,它的元素初始化后不能再修改。但可以通过重新给变量赋值操作,达到修改元素的目的。

    # 元组
    peopleTuple = ("eye", "mouth", "nose", "brow", "ear", 1.80, 120)
    print(peopleTuple)
    peopleTuple = ("eye", "mouth", "nose", "brow", "head", 6.6, 999)  # 重新给变量赋值来达到修改元素的目的
    

    字典

    字典是由键-值对组成的集合,可通过键名对值进行操作。

    peopleDict = {"e": "eye", "m": "mouth", "n": "nose", "b": "brow", "h": 1.80, "w": 120}
    print(peopleDict)
    print(peopleDict["e"])  # 访问
    peopleDict["a"] = "arm"  # 添加键-值对
    peopleDict["w"] = 190  # 修改键-值对
    del peopleDict["a"]  # 删除键-值对
    

    最后

    Python博大精深,要想学好建议还是认真研读一本书。

    本文已在公众号:GainAnEpoch发布,转载请注明出处。


    wechatPre.jpg

    相关文章

      网友评论

        本文标题:Python与C语言基础对比(Python快速入门)

        本文链接:https://www.haomeiwen.com/subject/cbflqftx.html