banner
苍术

苍术

不探索,无进步 [email protected]

From C++ to Python

Environment Installation#

  1. Go to 'https://www.jetbrains.com/pycharm/' to download and install PyCharm.
  2. Follow the prompts to install the application and log in, then create your first Python code.

Differences#

  • Undoubtedly, Python is simpler than C++, and the coding style reflects this. The main differences are as follows:
      1. No need for header files
      1. The main function has no name
      1. No need for {}
      1. No need for ;

Next, let's start with the simplest output;

Basic Knowledge#

Input and Output#

The syntax for the output function print() is:

print()

The input function is input(), which receives user input. The syntax is:

input(what to output)

Example: Receive user input for a password and print it:

n = input("Please enter your password:")	# Assign the input to n
print(n)	# Print n

In Python, “#” indicates a comment; anything after “#” will not be executed.

Prompt information
Please enter your password: 123
123

Variables#

  • Valid identifiers: uppercase and lowercase letters, numbers (cannot start with a number), underscores.
  • No length limit.

It is recommended to name functions, variables, etc., meaningfully:

  1. Package name: all lowercase, e.g., time;
  2. Class name: first letter of each word capitalized, others lowercase, known as CamelCase, e.g., HelloWorld;
  3. Variable name/function name: first word lowercase, subsequent words capitalized, known as camelCase, e.g., helloWorld;
  4. Constant: all uppercase, e.g., HELLO.
  5. Other naming conventions, such as hello_world.

Data Types#

Unlike C++, Python does not require type specifiers; types are assigned automatically. (Not absent!!!)

  1. Integer
  2. Float
  3. String
  4. Bool
  5. None is a separate data type
  6. List, tuple, dictionary, and set are also common data types
  • Type conversion:
int() # The value to be converted must be a string of all digits
str()
float() # The value to be converted must be a string of all digits
  • Get type information
type() # Returns the type of the object
type().__name__

isinstance(,)  # Commonly used to check data types, returns bool

Example:

f = 30
print(type(f))
print(type(f).__name__) 
print(isinstance(f,int))

Output:

f = 30
print(type(f))
print(type(f).__name__)
print(isinstance(f,float))

Operators#

Operators can be divided into four categories

  1. General operators

+, -, *, / (true division), // (floor division, discarding the decimal part), % (modulus), ** (exponentiation)

  1. Assignment operators

=, +=, -=, *=, /=, %=, **=

Chained assignment: a = b = c = d = 10

  1. Boolean operators

== (equal), != (not equal), >=, <=, >, <

  1. Logical operators

Mainly not, and, and or, also known as negation, conjunction, and disjunction

and: true if both sides are true
or: true if at least one side is true
not: negation, not true

Example:

a = 10
b = 20
c = 30
d = 40
n1 = a > b and a < c    # a > b is false, a < c is true, false and true is false
n2 = not a < c   # a < c is true, negation of true is false
n3 = a > b or a < c     # a > b is false, a < c is true, false or true is true
print(n1,n2,n3)

Output:

False False True

Flow Control#

Conditional Branching (if elif else)#

Example:

s = int(input("Please enter the score:"))
if 80 >= s >= 60:
    print("Passed")
elif 80 < s <= 90:
    print("Excellent")
elif 90 < s <= 100:
    print("Very Excellent")
else:
    print("Failed")
    if s > 50:
        print("Your score is around 60")
    else:
        print("Your score is below 50")

Output:

Please enter the score:55
Failed
Your score is around 60

Loop Flow#

  1. While Loop

Syntax:

while Boolean expression: 
    Code block

As long as the condition (Boolean expression) is true, the code block inside will execute.

Example: For instance, input an integer and calculate the sum of its digits, for example, input 321, then the sum of the digits is 6.

# Please enter an integer and calculate the sum of its digits, e.g., 321=6

n = int(input("Please enter an integer:"))  # Convert string to integer

# sums accumulator: m=10 m=10+5

sums = 0

while n != 0:  # 32 #3
    sums = sums + n % 10  # sums=1+2=3+3=6
    n = n // 10  # 32
print(sums)

Output:

Please enter an integer:2345
14
  1. For Loop

Syntax:

for variable in iterable object:
    Code block

Example:

l=[3,2,1]
for n in l:
    print("1")

Output:

1
1
1
  1. Range

The for loop is often used with range, which is an iterable object. The syntax for range is as follows:

range(start=0, stop, step=1)

The Range object returns an object that generates a sequence of integers from start (inclusive) to stop (exclusive) in steps. Range(i, j) produces i, i+1, i+2,…j - 1. Start defaults to 0, stop is optional!

Range(4) produces 0,1,2,3. These are valid indices for a list containing 4 elements.

When a step is given, it specifies the increment (or decrement).

  1. Continue Break

Continue skips the current loop iteration, and the subsequent loops continue executing.

Break terminates the loop.

List#

A list can simultaneously store any data, including integers, floats, strings, booleans, etc., and is one of the commonly used data types.

Creating a List#

A list is also an iterable object
1. Normal form
        l = [1,2,3,4,5] --- integer list
        l = ["a","b","c"] --- string list
        l = [True,False,1>2,5<6]--- boolean list
2. Mixed list
        l = [1,2.5,"a",True]
3. Empty list
        l = []

Accessing Data from a List#

Lists have indices, starting from 0, and the access method is similar to arrays.

However, the list indices start from 0 in ascending order and from -1 in descending order

print(List) outputs the entire list in order.

Data Exchange in a List#

Example:

l = [1, 2, 3, 4, 5]  # Index: starts from 0
l[2], l[3] = l[3], l[2]
print(l)

Output:

[1, 2, 4, 3, 5]

Adding Elements to a List#

append(project) # Append object to the end of the list (as a whole)
extend(project) # Append iterable object to the end of the list, e.g., connect two lists
insert(num, project) # Add object at a specified index (as a whole)

Deleting Elements from a List#

clear() # Clear the list (the list still exists, not deleted)
pop() # Delete the element at the specified index; if no index is provided, delete the last element
remove() # Remove the specified object (the first one in order)
del() # Delete a variable (the entire list) or the value of the element at the specified index in the list (placeholder)

Example:

l = [1, 2, 3, 4, 5]
l2=[6, 7, 8, 9, 10]
l.extend(l2)
print(l)
l.append(l2)
print(l)
l.insert(3,l2)
print(l)
l.pop(1)
print(l)
l.remove(l2)
print(l)
del l[-1]
print(l)
del l

print(l2)
l2.clear()
print(l2)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [6, 7, 8, 9, 10]]
[1, 2, 3, [6, 7, 8, 9, 10], 4, 5, 6, 7, 8, 9, 10, [6, 7, 8, 9, 10]]
[1, 3, [6, 7, 8, 9, 10], 4, 5, 6, 7, 8, 9, 10, [6, 7, 8, 9, 10]]
[1, 3, 4, 5, 6, 7, 8, 9, 10, [6, 7, 8, 9, 10]]
[1, 3, 4, 5, 6, 7, 8, 9, 10]
[6, 7, 8, 9, 10]
[]

Modifying Elements#

Same as arrays.

Advanced Features of Lists#

Slicing#

Slicing, as the name suggests, is splitting one list into multiple lists. The syntax is as follows:

variable[start index:end index] 	# The end index is not included

When performing slicing operations, pay attention to the following points:

  1. If the index starts from 0, it can be omitted, e.g., n = l[:4].
  2. If the end index refers to the last element, it can be omitted, e.g., n = l[3:].
  3. If all elements in the list are needed, both start and end indices can be omitted, e.g., n = l[:].
  4. n = l[:-1] means from 0 to the second last element.
    Example:
l = [1, 2, 3, 4, 5]
print(l[0:4])

Output:

[1, 2, 3, 4]

Equidistant Extraction#

The method is n = l[start:end], which can operate on the list in both forward and reverse directions, for example:

l = [1, 2, 3, 4, 5]
n = l[-1:-3:-1]
print(n)

Output:

[5, 4]

Some Operators for Lists#

Comparison Operators#

Lists are compared element by element, starting from the same index, comparing from smallest to largest. If the values are the same, the next group of elements is compared; if different, the result is returned directly, for example:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # Index: starts from 0
l2 = [2, 3, 4, 6]
print(l < l2)  # True

Output:

True

Logical Operators#

Logical operators and, not, or are similar to comparison operators, returning results as boolean values (True/False).

Concatenation Operator#

The concatenation operator is +, commonly used to concatenate two lists.

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # Index: starts from 0
l2 = [2, 3, 4, 6]
print(l + l2)

Repetition Operator#

The repetition operator is *, usually followed by a number, indicating how many times to repeat the elements in the list.

l2 = [2, 3, 4, 6]
print(l2*2)

Membership Operators#

Membership operators mainly include in and not in, used to check whether an element is in the list, returning results as boolean values.

l = [2, 3, 4, 6]
print(5 not in l)	# Outputs the truth value of "5 is not in list l"

Execution result:

True

Other Methods of Lists#

copy() # Shallow copy
count(project) # Returns the number of times an object appears in the list
index(value, start index, end index) # The index of the first occurrence of an element, can also specify a range
reverse() # In-place reversal
sort(key=None, reverse=False) # Quick sort, defaults to sorting from smallest to largest, key: algorithm
len() # Get the length of the list

Two-Dimensional List#

# variable[outer list index][inner list index]
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in l:
    for j in i:
        print(j)

Output:

1
2
3
4
5
6
7
8
9

Tuple (tuple)#

Creating and Accessing Tuples#

Tuples are in the form of (), are iterable objects, ordered, support index operations, and support slicing operations [:]

Same as lists, no need to elaborate.

Modifying and Deleting#

Tuples are immutable types and cannot be modified. However, they can be modified and deleted by converting the tuple into a list, and then converting it back to a tuple to complete the modification and deletion.

For example: Modifying an element in a tuple:

t = (1, 2, 3, 4, 5)
l = list(t) # Convert tuple to list
print(l)    # Output the list
l[2] = 6    # Modify the specified element in the list
print(l)    # Output the new list
t = tuple(l)    # Convert list back to tuple
print(t)

Output:

[1, 2, 3, 4, 5]
[1, 2, 6, 4, 5]
(1, 2, 6, 4, 5)

Operators for Tuples#

Tuples also have operators, and the methods are the same as those for lists, no need to elaborate.

Methods for Tuples#

For operations, first convert to a list and then perform operations, no need to elaborate.

Additionally, there are two methods to add:

1. count(value)
# Count the number of times a specific value appears, value is the specified value

2. index(value, [start], [stop])
# Return the index of the first occurrence of value in the tuple (between start and stop)

Strings#

In Python, characters and strings are indistinguishable. They can be enclosed in ' or " ".

Characteristics of Strings#

1. Strings are immutable types
2. Strings are iterable objects
3. Strings support indexing and slicing operations
4. Support operators;
        Concatenation: +
        Repetition operator: *
        Comparison operators: > < <= >= == !=
        Logical operators: not and or
        Membership: in    not in		

Methods for Strings#

capitalize() # Capitalizes the first character of the string, the rest lowercase
casefold() # Converts the entire string to lowercase
encode() # Encodes str--bytes (binary string)
decode() # Decodes
count(sub, start, stop) # Returns the number of times the character (sub) appears, start: start index, stop: end index
find(sub, start, stop) # Returns the index of the first occurrence of sub, returns -1 if not found
index(sub, start, stop) # Returns the index of the first occurrence of sub, raises an error if not found
upper() # Converts the string to uppercase
lower() # Converts the string to lowercase

Formatted Output#

  1. Format syntax 1: Using numbers as placeholders (indices)
"{0} hey".format("Python")
a = 100
s = "{0}{1}{2} hey"
s2 = s.format(a, "JAVA", "C++")
print(s2)
  1. Format syntax 2: {} as placeholders
a = 100
s = "{}{}{} hey"
s2 = s.format(a, "JAVA", "C++", "C# ")
print(s2)
#Output
100JAVAC++ hey
  1. Format syntax 3: {} as placeholders using letters
s = "{a}{b}{c} hey"
s2 = s.format(b="JAVA", a="C++", c="C# ")
print(s2)
#Output:
C++JAVAC#  hey

s.format(s2) can be understood as using s to format s2.

  1. %s

The syntax is “%s” % (value), the most commonly used parameter can be any value.
Example:

for i in range(1, 10):
    for j in range(1, i + 1):
        print("%s * %s = %s" % (i, j, i * j), end="\t")
    print()

#Output:
1 * 1 = 1	
2 * 1 = 2	2 * 2 = 4	
3 * 1 = 3	3 * 2 = 6	3 * 3 = 9	
4 * 1 = 4	4 * 2 = 8	4 * 3 = 12	4 * 4 = 16	
5 * 1 = 5	5 * 2 = 10	5 * 3 = 15	5 * 4 = 20	5 * 5 = 25	
6 * 1 = 6	6 * 2 = 12	6 * 3 = 18	6 * 4 = 24	6 * 5 = 30	6 * 6 = 36	
7 * 1 = 7	7 * 2 = 14	7 * 3 = 21	7 * 4 = 28	7 * 5 = 35	7 * 6 = 42	7 * 7 = 49	
8 * 1 = 8	8 * 2 = 16	8 * 3 = 24	8 * 4 = 32	8 * 5 = 40	8 * 6 = 48	8 * 7 = 56	8 * 8 = 64	
9 * 1 = 9	9 * 2 = 18	9 * 3 = 27	9 * 4 = 36	9 * 5 = 45	9 * 6 = 54	9 * 7 = 63	9 * 8 = 72	9 * 9 = 81	

Escape Characters#

1. “\n” : newline character
2. “\'”: single quote
3. “\"”: double quote
4. "\\" : \

It is worth noting that \ has many clever uses, for example, it can achieve line breaks in code.

a = "sxsxsxsxsxsxsxs\
        xsxsxsxs\
        xsx"
print(a)

a = 1 + 2 + 3 \
    + 4
print(a)

#Output:
sxsxsxsxsxsxsxs        xsxsxsxs        xsx
10

Dictionary (dict)#

Dictionaries are used to store data, and the data in a dictionary is stored in a mapping relationship.

Characteristics of Dictionaries#

  1. Dictionaries are the only mapping type in Python
    2. Dictionaries are unordered
    3. Dictionaries are iterable objects
    4. The structure of a dictionary:

    Key: key
    Value: value
    Mapping: key maps to value
    Key-Value: key-value pair, also called an item

Creating a Dictionary#

1. Direct creation
		Syntax: d = {} 	# empty dictionary
		Example: d = {"name":"Bad Person","apple":"Apple"}
2. dict()
		Example: d = dict()	# empty dictionary
3. dict(iterable object)

Example:

d3 = dict([("one",1),("two",2)])
print(d3)
#Output:
{'one': 1, 'two': 2}

This is a tuple, where one is the key and 1 is the value, ‘one’ : 1 is a key-value pair.

4. dict(**kwargs)

Example:

d4 = dict(a=3, b=4)
print(d4)
#Output:
{'a': 3, 'b': 4}    

Accessing a Dictionary#

  1. Basic form:

    variable name[key name] # The value corresponding to the key
  2. Adding a key-value pair

    variable name[key name] = value
  3. Modifying the value of a key-value pair

    variable name[key name] = value

Example

d = {"name": "Little Black"}
print(d["name"])
#Output:
Little Black

Methods for Dictionaries#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.