iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐥

Intuitive Python Guide for C Programmers (Basics)

に公開

Introduction

This material is based on my experience of studying Python after learning C.
I have placed emphasis on clarity and the points where I actually got stuck, so if you find any mistakes or oddities, please let me know in the comments.


Table of Contents


Environment Setup

There are several ways to create an environment where Python can be executed:

Personally, I recommend setting up the environment locally as it is the easiest.

Local environment setup steps:

  1. Download the Python installer
    1. Python Official
  2. Run the installer
    1. Don't forget the check!
  3. After installation, type python --version in the command prompt; if no error occurs, you are good to go.

Execution method:
Enter the following command on the command line to execute the program.

python your_file.py

Python Features

  • Explicit type declarations are not required
    • You don't have to write char a = 'b'
  • Semicolons are not required
  • No main function (described later)
  • Pointers are not handled explicitly (they are used internally)
  • Compatible with C
    • Can be converted to C types
  • No compilation needed (automatically handled by python your_file.py)
  • Runs in various environments
    • windows, mac, android (Termux), linux
  • Execution speed is slow

Standard Output and Commenting Out

Syntax:
print(variable, variable, ...)
You can output variables whether they are numbers, strings, or arrays.


Example 1:
print('Hello')
----------------
Hello 

Example 2:
print('apple')
print('orange')
print('') # Newline
print('big win')
----------------
apple
orange

big win
# When outputting, a newline is added by default.

Example 3:
s1 = 'aiueo'# String
s2 = ':'# String
s3 = 5 # Number
print(s1, s2, s3)
----------------
aiueo : 5
# When outputting, items are separated by spaces.

There are two ways to comment out:

# Single-line comment

'''

Multi-line comment


'''

Arrays

Arrays include the standard list type, tuple type, and numpy using an external library (described later).
Unlike C, arrays are basically dynamic (the number of elements can be increased or decreased).

# List type
list1 = [10]
# Adding to the array
list1.append(40)
print(list1)
--------------------
[10, 40]

Control Structures

In C, it looks like this:

#include <stdio.h>
int main(void){
	// for loop
	for(int i=0; i<5; i++){
		printf("*\n")
	}

	// if statement
	a = 7;
	if(a >= 8){
		printf("a\n")
	}else if(a < 6){
		printf("b\n")
	}else{
		printf("c\n")
	}

	while(a < 10){
		print("%d\n",a);
		a++;
	}
	return 0;
}

In Python, it looks like this:
Note: Don't forget the indentation!!!

# for loop
# Looping 5 times from 0 to 4
for i in range(5):
	print('*')

a = 7

# if statement
if(a >= 8):
	print('a')
elif(a < 6):
	print('b')
else:
	print('c')

# while loop
while(a < 10):
	print(a)
	a = a + 1

Functions

def function_name(argument, argument..):
	...
	return return_value, return_value

Python does not require explicit type declarations, so you can create functions using only variable names.
Also, unlike C, you can return multiple values.

Strings

Python allows concatenation using the '+' operator.

s1 = 'spr'
s2 = 'ing'
s3 = s1 + s2
print(s3)
----------------
spring

Modules (External Libraries)

When using external functions instead of the standard functions provided by Python, you must import them.

# Importing an external library (module) called sys
import sys

Commonly used imports:

# Importing numpy as np
import numpy as np
# Importing matplotlib as plt
import matplotlib as plt

numpy

NumPy is a library that excels in numerical calculations.
When passing an array as a function argument, NumPy is often used (as there are cases where the list type cannot be used).
Please make good use of it as you can perform mutual conversions as shown below.

import numpy as np

# Declared as numpy ndarray type
a1 = np.array([1,2,3])

# Convert to list type
a2 = a1.tolist()

# Convert to numpy ndarray type
a3 = np.array(a2)

print(type(a1),a1)
print(type(a2),a2)
print(type(a3),a3)
------------------------
<class 'numpy.ndarray'> [1 2 3]
<class 'list'> [1, 2, 3]
<class 'numpy.ndarray'> [1 2 3]

How to use NumPy

matplotlib

You can output graphs.

import matplotlib as plt

# Array from 0 to 9
list1 = []
for i in range(10):
	list1 = i

# Array from 9 to 0
list2 = []

for i in range(10):
	list1 = 10 - i - 1

# You can output by providing x-axis and y-axis data
plt.scatte(list1,list2)
plt.show()

More details on matplotlib

Command Line Arguments

What used to be written like this in C:

#include<stdio.h>
#include<stdlib.h>

int main(int argc,char *argv[]){
	if(argc != 2){
		printf("Usage: %s filename",argv[0]);
		exit(1);
	}
}

becomes this in Python:

import sys

# args: Array containing elements
args = sys.argv

# ac: Number of elements
ac = len(args)

if(ac != 2):
    print('Usage:', args[0], 'filename')
    sys.exit()

Text Files

# fopen
f = open('test.txt', 'r')
data1 = f.read() # Returns all data read up to the end of the file
f.close()

# fopen
f = open('out.txt', 'w')
f.write('hello')
f.close()

# Rewriting it with a 'with' statement makes it more concise
with open('sample.txt', 'r') as f:
		print(f.read())

Detailed information on text files
Official Reference

Useful Functions and Classes

Syntax: str1 = str(variable)
Function: Converts the variable to a string and assigns it to that variable.

Syntax: int1 = int(variable)
Function: Converts the variable to an integer and assigns it to that variable.

Syntax: sort(array)
Function: Sorts the array and assigns it to that variable.

Syntax: type(variable)
Function: Returns the type of the variable.

Syntax: len(variable)
Function: Returns the length of the string.

Useful Expressions

  • Creating a Main Function
    Python doesn't have the concept of a main function, but you can make it act like one by writing it like this. Many programs you see on GitHub and elsewhere are often written in this way.
def main():
	....


if __name__ == '__main__':
	main()
  • Creating an array containing numbers from 1 to N in order
# List from 1 to N
onelist = []

for i in range(N):
	onelist.append(i+1)

Problems

  1. Create a program that randomly displays "Dada" and "Suka". If the resulting output matches "DadasukasukasukaDadasukasukasukaDadasukasukasuka", print "Love Chuu-nyuu" and terminate the program.

  2. Find an approximate value of an integral using the trapezoidal rule. Let the function be "5sin(2x)" and the number of divisions be N = 1000.

Summary

I wrote this article as a basic guide.
I plan to write an advanced edition in the future, so please look forward to it.

Discussion