Python Basics Guide: Basic concepts and examples of expressions, statements, and functions

Preface

Several basic concepts in python

expression

An expression is something similar to a mathematical formula.
For example: 10 + 5 8 - 4.
Expressions are generally only used to calculate some results and will not have a substantial impact on the program.
If you enter an expression in interactive mode, the interpreter will Automatically output the result of an expression

statement

Statements in programs generally need to complete certain functions, such as printing information, obtaining information, assigning values ​​to variables...
for example:

print()
input()
a = 10

The execution of a statement will generally have a certain impact on the program.
In interactive mode, the execution result of the statement may not be output.

program

A program is composed of statements one by one and expressions one by one.

summary

In computer programming, a program consists of statements one by one and expressions one by one. Expressions are used to calculate and generate results, while statements are used to implement specific functions and operations.

Here are some examples to help you understand the concepts of expressions, statements, and procedures:

  1. Expression example:
# 定义两个变量
a = 10
b = 5

# 计算表达式的结果
result = a + b

print(result)  # 输出:15

In the above example, a + bit's an expression. It adds the variables asum bto produce the result 15. Functions can be used print()to output results to the console.

  1. Statement example:
# 获取用户输入
name = input("请输入您的姓名:")

# 打印欢迎信息
print("欢迎您," + name + "!")

# 判断条件并执行不同的语句
if name == "Alice":
    print("您是管理员用户!")
else:
    print("您是普通用户!")

In the above example, input()the function is used to get the user input and assign the value entered by the user to the variable name. print()Function is used to print the welcome message. if...elseThe statement judges the identity of the user based on the name entered by the user and outputs different results.

  1. Program example:
# 定义一个函数
def square(num):
    return num ** 2

# 调用函数并打印结果
result = square(5)
print(result)  # 输出:25

# 循环执行语句
for i in range(1, 6):
    print("当前数字:" + str(i))

In the above example, we defined a square()function named to calculate the square of a number. Then, we call the function and assign the result to a variable result, and print()output the result through the function. Next, use fora loop statement to print the current value of the numbers 1 to 5.

To sum up, the program is composed of statements one by one and expressions one by one. Expressions are used to calculate and generate results, while statements are used to implement specific functions and operations. By writing different statements and expressions, we can build a fully functional program.

function

A function is a kind of statement, which is specially used to complete a specific function.
The function length is in the form: xxx()
Classification of functions:

  • Built-in functions: functions provided by the Python interpreter and can be used directly in Python
  • Custom function: a function created by programmers.
    When we need to complete a certain function, we can call a built-in function or a custom function. The
    two elements of a function:
  • Parameters: The content in () is the parameters of the function. The function can have no parameters or multiple parameters. Use separate parameters between multiple parameters.
  • Return value: The return value is the return result of the function. Not all functions have return values.

basic grammar

  1. Strict case sensitivity in Python
  2. Each line in Python is a statement, and each statement ends with a newline
  3. Each line of statements in Python should not be too long (the specification recommends that each line should not exceed 80 characters)
    "rulers":[80],
  4. A statement can be written in multiple lines. When writing multiple lines, the statement ends with \
  5. Python is a language with strict indentation, so don't write indentation casually in Python
  6. # is used in Python to represent comments. The content after # is a comment. The content of the comment will be ignored by the interpreter.
    We can explain the program through comments. We must develop a good habit of writing comments.
    Comment requirements Simple and clear, generally # will be followed by a space

Function examples explained

Functions in Python are very important, it can help us encapsulate some code, making the code more concise, readable and maintainable. Let's introduce the basic syntax and usage of functions in Python.

  1. define function
def function_name(parameters):
    statement_1
    statement_2
    ...
    statement_n
    return result
  • defThe keyword indicates defining a function.
  • function_nameIs the function name, the naming rules are the same as variable names, follow the identifier rules.
  • parametersIt is the parameter list of the function, which can be 0 or more parameters, and multiple parameters are separated by commas.
  • :Indicates the end of the function definition, and the following indented block is the function body.
  • statement_1Here statement_nare the specific operation steps in the function body.
  • returnStatement is optional and used to specify the return value of the function.
  1. Call functions
result = function_name(arguments)
  • function_nameis the function name, and the following brackets argumentsare the parameter values ​​passed when calling the function. It can be 0 or more parameters. Multiple parameters are separated by commas.
  • resultIt is the return value of the function. You can assign the return value to a variable, or you can use the return value of the function directly.
  1. Parameter passing
  • Positional parameters
def greet(name, age):
    print("Hello, %s! You are %d years old." % (name, age))

greet("Tom", 18)

In the function definition, the parameters nameand ageare positional parameters. When calling the function, the actual parameters need to be passed in the order of the parameters, such as "Tom"corresponding name, 18corresponding age.

  • keyword arguments
greet(age=18, name="Tom")

In function calls, you can also use keyword arguments to explicitly specify parameters and their values, so that the order can be changed at will.

  • default parameters
def greet(name, age=18):
    print("Hello, %s! You are %d years old." % (name, age))

greet("Tom")

When defining a function, you can specify a default value for a parameter. When the function is called without passing the parameter, the default value will be used. Note that the default parameters should be written after the positional parameters.

  • variable parameter
def add_numbers(*numbers):
    sum = 0
    for num in numbers:
        sum += num
    return sum

result = add_numbers(1, 2, 3, 4)
print(result)

When defining a function, you can use the asterisk *to turn arguments into variadic arguments, which means that any number of arguments can be passed. Within the function body, variadic arguments are treated as tuple types.

  • Keyword variadic parameters
def print_info(**info):
    for key, value in info.items():
        print("%s: %s" % (key, value))

print_info(name="Tom", age=18, gender="male")

When defining a function, you can use double asterisks **to turn arguments into keyword variadic arguments, which means that any number of keyword arguments can be passed. In the function body, keyword varargs are treated as dictionary types.

  1. return value
  • single value
def add(a, b):
    return a + b

result = add(1, 2)
print(result)

In the function body, you returncan specify the return value of the function, which can be any type of data.

  • multiple values
def get_name_and_age():
    name = input("Please enter your name: ")
    age = int(input("Please enter your age: "))
    return name, age

name, age = get_name_and_age()
print(name, age)

In the function body, you returncan specify multiple return values ​​of the function, and these values ​​will be encapsulated into a tuple type return.

In short, functions are an important concept in Python programming. Understanding the syntax and usage of functions is very helpful for beginners in Python programming.

Literals and variables

Literals are values ​​one by one, such as: 1, 2, 3, 4, 5, 6.
The meaning of the 'HELLO' literal is its literal value. Literals can be used directly in the program.

Variables can be used to save literals, and the literals saved in variables are variable. The variables
themselves have no meaning. They will express different meanings based on different literals.
Generally, we rarely use literals directly when developing. , both save the literal into a variable and reference the literal through the variable

In Python, literals can be saved into variables using the assignment operator (=). Here's a simple example:

# 定义一个变量并赋值
num = 10

# 打印变量的值
print(num)

In the above code, we define a numvariable named and assign the literal 10value to it. Then, use printthe function to output numthe value of the variable, and the result is 10.

By using variables, we can manipulate and reference literals. For example:

# 定义两个变量并进行加法运算
a = 5
b = 3
sum = a + b

# 打印变量的值
print(sum)  # 输出:8

In this example, we define two variables asum band assign them to literals respectively . We then add these two variables and save the result into another variable . Finally, use the function to output the value of the variable, and the result is .53sumprintsum8

It should be noted that the variable name can be named according to actual needs, but it must follow the rules of identifiers, that is, it starts with a letter or an underscore, and can be followed by letters, numbers, or underscores. Additionally, variable names are case-sensitive, so numand Numare different variables.

variables and identifiers

When we write programs, we often need to use variables to store and manipulate data. A variable can be seen as a container for storing data. We can give the variable a name and refer to the value stored in the variable through this name.

In Python, the naming of variables needs to follow some rules, and these rules also apply to the naming of identifiers. Identifiers refer to the names used to name variables, functions, classes and other elements in a program.

First, identifiers can only consist of letters, numbers, and underscores, and cannot start with a number. For example, age, student_name, MAX_VALUEare all valid identifiers.

Second, identifiers are case-sensitive, so ageand Ageare different identifiers.

In addition, identifiers cannot use Python keywords as names. For example, if, for, whileetc. are keywords and cannot be used as identifiers.

Another thing to note is that good naming habits can increase the readability of your code. We should give variables a descriptive name so that we can understand the meaning of the code. For example, use ageto represent age and use student_nameto represent student name.

Here is a sample code that demonstrates how to define variables and use identifiers:

# 定义一个整型变量age,赋值为18
age = 18

# 打印变量age的值
print(age)  # 输出:18

# 定义一个字符串变量student_name,赋值为"Alice"
student_name = "Alice"

# 打印变量student_name的值
print(student_name)  # 输出:"Alice"

In the above code, we defined two variables agesum student_nameand assigned initial values ​​to them respectively. Then use print()the function to output the values ​​of these two variables.

By using variables, we can process and manipulate data more conveniently, making the program more flexible and scalable. At the same time, reasonably named identifiers can improve the readability and maintainability of the code, making our code easier to understand and modify.

Summarize

This article introduces some basic concepts and syntax in programming, including programs, functions, basic syntax, literals and variables, and identifiers. These are briefly summarized below:

  1. A program is a collection of codes that is composed of a series of instructions to accomplish a specific task.
  2. Functions are reusable blocks of code that perform specific functions. By defining functions, the code can be modularized and organized to improve the maintainability of the code.
  3. Basic syntax is the rules and conventions in programming languages, including comments, statements, expressions, conditional statements, loop statements, etc., used to control the execution flow of the code.
  4. A literal is a symbol or text that directly represents a specific value. Variables are containers for storing data and are referenced through identifiers.

I hope that by studying this article, you can lay a solid foundation for further study and practice.

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132719802