C quick guide for Python user

Tweet


Simple program

Python

print('Example program')

Output

Example program

Source code is executed directly from above.
Output text with print function

C

#include <stdio.h>

void main()
{
    printf("Example program\n");
}

Output

Example program

Executed from the contents of the main function
Output text with printf function


main function

Python

def main():
    print('Example program')

if __name__ == '__main__':
    main()

Output

Example program

Source code is executed directly from above.
def main is a function definition and is not called at this point
if statement is executed
I won't go into details, but __name__ is __main__ in a normal execution
The main function is called because the if statement is executed

C

#include <stdio.h>

void main()
{
    printf("Example program\n");
}

Output

Example program


Comment

Python

def main():
    ''' Comment line 1
    Comment line 2 '''
    print('Comment example') # Comment

if __name__ == '__main__':
    main()

Output

Comment example

Comments between ''''and'''''
# and onwards to the end of the line is the comment

C

#include <stdio.h>

void main()
{
    /* Comment line 1
    Comment line 2 */
    printf("Comment example\n"); // Comment
}

Output

Comment example

Anything between /* and */ is a comment
// and onwards to the end of the line is the comment


Semicolon

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

One instruction per line
Add a semicolon only when writing multiple instructions on a single line.
Backslash at the end of a line when spanning multiple lines

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

A semicolon at the end of one instruction
Whether multiple instructions are written on a single line or across multiple lines, each instruction up to a semicolon is a single instruction


Output text with newlines

Python

def main():
    print('Example', end='')
    print('Program')
    print('')
    print('Line1\nLine2')

if __name__ == '__main__':
    main()

Output

ExampleProgram

Line1
Line2

If you do not want line breaks, specify '' for end of print
Write \n at the position where you want the line to break.

C

#include <stdio.h>

void main()
{
    printf("Example");
    printf("Program\n");
    printf("\n");
    printf("Line1\nLine2\n");
}

Output

ExampleProgram

Line1
Line2

Write \n at the position where you want the line to break.


Using the Library

Python

import numpy as np

def main():
    print('sqrt(2)=%f' % np.sqrt(2))

if __name__ == '__main__':
    main()

Output

sqrt(2)=1.414214

Load a library with sqrt in it with import.

C

#include <stdio.h>
#include <math.h>

void main()
{
    printf("sqrt(2)=%f\n", sqrt(2.0));
}

Output

sqrt(2)=1.414214

Load libraries with sqrt functions in #include
stdio.h contains printf and math.h contains sqrt


command line argument

Python

import sys

def main():
    print(sys.argv[1])

if __name__ == '__main__':
    main()

Command

python.exe cg2.py option

Output

option

argv[0] contains the name of the program
argv[1] contains the first argument

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] contains the name of the program
argv[1] contains the first argument
argc contains the number of arguments


printf statement

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 is an integer, %f is a floating-point number, and %s is a string
Variables can be assigned as is.

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 is an integer, %f is a floating-point number, and %s is a string
Use the sprintf function to assign to a variable


Data type

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'>

The data type is automatically determined even if you do not write the data type in the variable definition.
The data type is set internally.
int is the type of integers, and there is no limit to the number of integers that can be represented
The float type is a floating-point type and can represent a range of values expressed in 64 bits.
type str is the type of string
type can be used to determine the data 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

Always specify the data type when defining variables
type int is an integer in the range represented by 32 bits
The float type is a floating-point number in the range represented by 32 bits
double type is a floating-point number in the range represented by 64 bits
For example, 2 is int, 2.0f is float, and 2.0 is double
char type is a character type (or an integer in the range represented by 8 bits)
    Since it is a single character, multiple characters are represented by an array.
    Enclose one character in single quotation marks and two or more characters in double quotation marks.
Use sizeof to find the number of bytes of the data type.


bit operation

Python

def main():
    print(1 | 2 | 4 | 8 | 16 | 32 | 64 | 128)

if __name__ == '__main__':
    main()

Output

255

Although only the OR operation (bitwise OR) is introduced here, other bitwise operations are similar.

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

Although only the OR operation (bitwise OR) is introduced here, other bitwise operations are similar.


basic arithmetic operations

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

The operator on powers (powers of) is **.

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 language can be expressed as a++ instead of a=a+1
Use the pow function since C does not have a power (power of) operator


Division

Python

def main():
    a = 5
    b = 2
    print(a / b)
    print(a // b)

if __name__ == '__main__':
    main()

Output

2.5
2

a/b is calculated as a division between two floating-point numbers
a//b is calculated as division between integers

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 is calculated as division between integers since a and b are integers
d/e is computed as a division between floating points, since d and e are floating points


type conversion

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

To achieve the intended calculation results, carefully consider whether the data type is appropriate and convert the data type if necessary.

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

To achieve the intended calculation results, carefully consider whether the data type is appropriate and convert the data type if necessary.


Array

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

List
Index starts from 0
Because it is a list, elements can be added in the middle of the list.

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

Array
Index starts from 0
Since it is a (static) array, no elements can be added in the middle of the array.


Null character

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

Can be converted to ASCII code by ord.

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

Null character at the end of the string.
It allows you to know how far the string goes.
The null character is a number 0 (ASCII code for 0) and is sometimes written as '\0'.


Pointer example 1

Python

def main():
    a=[0]
    p=a
    p[0]=1
    print(a)

if __name__ == '__main__':
    main()

Output

[1]

There are no pointers in Python.
Lists and objects are assigned by reference
p is a reference to a
Changing the content of the entity to which p points is the same as changing the content of the entity to which a points.

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

A * in the data type definition indicates a pointer type
Adding & to a variable makes it a pointer to that variable.
Appending * to a pointer variable allows access to its contents.
p is a pointer to a
*p is the entity to which the pointer points
So *p means a.
Changing the content of *p is the same as changing the content of a


Pointer example 2

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


if statement

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

Indentation is used to indicate the range in which the if statement is in effect.

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

In this example, one instruction is the extent to which the if statement is in effect


else statement

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


logic operation

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

& is a bitwise operation, && is a Boolean operation
Multiple comparison operators cannot be connected.


for statement

Python

def main():
    s = 0
    for i in range(0, 10):
        s += i + 1
    print(s)

if __name__ == '__main__':
    main()

Output

55

Indentation is used to indicate the range where the for statement is in effect.
i loops 10 times with 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(0, 10) is a range of integers between 0 and 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

In this example, the range enclosed by {} is the range where the for statement is effective
i loops 10 times with 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Expression 1 in for(expression1;expression2;expression3) is the first process executed, expression 2 is the termination condition, and expression 3 is the process executed for each loop
First, i=0 is executed
If i<10, execute the contents of the for statement, and if i>=10, exit the for statement
After the content of the for statement (s+=i+1) has been executed, do i++.


while statement

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

The range where the while statement is in effect is indicated by indentation.

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

In this example, the range enclosed by {} is the range where the while statement is active


break statement

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


Function

Python

def myfunc():
    print('My function')

def main():
    myfunc()

if __name__ == '__main__':
    main()

Output

My function

Indentation is used to indicate the range of function contents.

C

#include <stdio.h>

void myfunc()
{
    printf("My function\n");
}

int main(int argc, char* argv[])
{
    myfunc();
    return 0;
}

Output

My function

The range enclosed by {} is the range of the function's contents.


Argument

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


Return value

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

The type of the function should be the return (return) type.
The type of a function with no return value should be void type.


By val

Python

def myfunc(a):
    a = 2

def main():
    a = 1
    myfunc(a)
    print(a)

if __name__ == '__main__':
    main()

Output

1

The value in the function does not affect the caller's arguments.

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

The value in the function does not affect the caller's arguments.


By ref

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]

From within a function, the value of the caller argument can be changed

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

From within a function, the value of the caller argument can be changed


Global variable

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

Put global on a global variable to use it as a global variable within that function.

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

Use global variables for variables not defined within that function.


exit function

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


Math function

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


File input/output

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 byte text file
11-byte binary file with hexadecimal numbers 54,65,78,74,20,66,69,6C,65,0D,0A
Note that 0D is the ASCII code for CR (carriage return) and 0A is the ASCII code for LF (line feed).
In this case, these two ASCII codes represent line breaks

Output binary.bin

abc

3-byte binary file with 97 in the first byte, 98 in the second byte, and 99 in the third byte

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 byte text file
11-byte binary file with hexadecimal numbers 54,65,78,74,20,66,69,6C,65,0D,0A
Note that 0D is the ASCII code for CR (carriage return) and 0A is the ASCII code for LF (line feed).
In this case, these two ASCII codes represent line breaks

Output binary.bin

abc

3-byte binary file with 97 in the first byte, 98 in the second byte, and 99 in the third byte


Back