Python language learning day 3_Variables and basic data types

I. Introduction

Review the learning content of the previous day

Day 2 of Python language learning_First introduction to Python . Yesterday, this article introduced the history, characteristics, application fields of Python and compiled and ran the first Python program.

Understand the importance of variables and data types

  • Variables and data types are the basis for processing data in programming languages. Variables allow us to store data and use it when needed, while data types define the properties of the variable and the kind of data it can store.
  • Reasonable and correct use of data types can avoid errors in programs, improve program efficiency, and make code more readable and easier to maintain.

2. Concept and use of variables

Definition of variables: What are variables and why are they needed?

what is a variable

In programming, a variable is an identifier used to store a data value. It can be regarded as a storage unit in memory, which stores data that can be accessed and modified at any time. Variables allow us to give data a name so that we can reference the data multiple times in the program without having to write it repeatedly.

Why variables are needed

  • Data Reuse : Variables allow us to store a data value and use it multiple times in different parts of the program. This avoids writing the same data repeatedly and makes the code more concise and easier to manage.
  • Code readability : By giving meaningful variable names to your data, you can increase the readability of your code. Other developers (or future you) can more easily understand what the code does.
  • Easy to modify : If you need to use the same data value in the program, using variables can be easily modified. Simply modify the value of a variable and all references to that variable will be automatically updated.
  • Flexibility and scalability : Variables provide a flexible way to work with data. You can modify the value of a variable at any time, or pass a reference to a variable to functions and modules, which makes the code more flexible and extensible.
  • Memory Management : Variables help programmers manage memory efficiently. Programs can release memory for variables when the data is no longer needed, or dynamically allocate and reallocate memory as needed.
  • Function implementation : Variables are the basis for realizing complex functions. For example, variables are essential when performing mathematical calculations, controlling program flow, processing user input, etc.

Variable naming rules: a combination of letters, numbers, and underscores, and the first character cannot be a number, etc.

In Python, variable naming needs to follow some rules:

  • Case Sensitivity : Python is case sensitive, which means variable and Variable are two different variables.
  • Can only start with letters (az, AZ) or underscore (_) : variable names cannot start with numbers. For example, 123abc is an invalid variable name, but _123abc is valid.
  • Can contain letters, numbers (0-9) and underscores (_) : variable names cannot contain spaces or special characters, such as %, $, #, etc. For example, my_variable and variable2 are both valid variable names.
  • It cannot be a Python keyword : the variable name cannot be a Python reserved word, such as if, while, class, etc. These keywords (see Outline 6 for details) have specific language meanings and cannot be used as ordinary variable names.
  • No limit on length : In theory, there is no limit on the length of Python variable names, but for the readability and ease of use of the code, it is recommended to use concise and clear variable names.
  • Be as descriptive as possible : A good variable name should clearly describe what it represents. For example, total_score is easier to understand than simple ts.
  • Avoid capital letters and underscores : Although technically allowed, capital letters and underscores are generally reserved for class names. For example, MyClass is a class name, but my_variable is a better choice for a variable name.

Variable assignment: how to declare and initialize variables

In Python, declaring and initializing variables is very simple, and you don't need to explicitly declare the data type. Python is a dynamically typed language, which means that you assign values ​​to variables directly and the Python interpreter automatically infers the variable's type at runtime. Here are the basic steps for declaring and initializing variables:

Choose a variable name that conforms to the naming rules: variable names can contain letters, numbers, and underscores, but they cannot start with a number or be a Python keyword. Assign a value to a variable using the assignment operator (=): assign the data value you want to store to the variable. Here are some examples of declaring and initializing variables:

# 声明一个整型变量
number = 10

# 声明一个浮点型变量
pi = 3.14159

# 声明一个字符串变量
greeting = "Hello, World!"

# 声明一个布尔型变量
is_valid = True

# 声明一个列表变量
fruits = ["apple", "banana", "cherry"]

# 声明一个字典变量
person = {"name": "Alice", "age": 25}

In the above example, we created several different types of variables, including integers, floats, strings, booleans, lists, and dictionaries. The Python interpreter automatically determines the data type of a variable based on the value assigned to it.

You can also declare multiple variables in a single statement, as shown below:

x, y, z = 1, 2, 3

Here, we declare three variables x, y, and z at the same time, and assign them the values ​​1, 2, and 3 respectively.

Remember, variables in Python are like labels, you can assign new values ​​to them at any time, even a different type of value, since Python is dynamically typed. For example:

x = 100  # x是一个整型
x = "text"  # 现在x是一个字符串

In this example, we first assign an integer value to x and then assign it a string value. The Python interpreter will process variable x according to the latest assignment.

3. Basic data types

In Python, basic data types can be divided into several categories, including numbers, sequences, maps, sets, and Boolean values. Here is an overview of these basic data types:

  1. number :
    • Integer (int) : positive integer, 0, negative integer, such as 1, 0, -10.
    • Float : Numbers with decimals, such as 3.14, -0.001.
    • Complex number (complex) : a number composed of real part and imaginary part, such as 1j, 2 + 3j.
  2. sequence :
    • String (str) : text data, such as "Hello, World!", 'Python'.
    • List : An ordered collection of elements. The elements can be of different types, such as [1, 2, 3], ["a", "b", "c"].
    • Tuple : An immutable ordered collection of elements, such as (1, 2, 3), ("a", "b", "c").
  3. Mapping :
    • Dictionary (dict) : A collection of key-value pairs, such as {"name": "Alice", "age": 25}.
  4. gather :
    • Set : An unordered set with unique elements, such as {1, 2, 3}.{1.1, 2.2, 3.3}
  5. Boolean value :
    • Boolean : logical value with only two possible values: Trueand False.

In Python, you can use type()functions to check the data type of a variable. For example:

x = 100
print(type(x))  # 输出:<class 'int'>

y = 3.14
print(type(y))  # 输出:<class 'float'>

z = "Hello"
print(type(z))  # 输出:<class 'str'>

Understanding these basic data types is important for writing Python code because they determine what types of data you can store in variables and what operations you can perform on that data.

4. Data type detection and conversion

Data type detection

In Python, you can use type()functions to check the data type of a variable. You can also use isinstance()functions to check whether a variable is of a specific type or is derived from a class. Furthermore, if you need to convert a variable from one data type to another, Python provides some built-in functions for this purpose.

  • type() function : returns the type of variable.
  • isinstance() function : checks whether the variable is an instance of a certain type.
x = 100
print(type(x))  # 输出:<class 'int'>
print(isinstance(x, int))  # 输出:True
print(isinstance(x, float))  # 输出:False

Data type conversion

Python provides a variety of built-in functions to convert variables from one data type to another. These functions are usually named after the target data type and can be called as functions.

  • int() : Convert a variable to an integer.
  • float() : Convert a variable to a floating point number.
  • str() : Convert a variable to a string.
  • list() : Convert variables to lists.
  • tuple() : Convert variables to tuples.
  • set() : Convert variables to sets.
  • dict() : Convert a variable into a dictionary.
  • bool() : Convert a variable to a Boolean value.
x = "123"
y = int(x)  # 将字符串转换为整数
print(type(y))  # 输出:<class 'int'>

z = float(x)  # 将字符串转换为浮点数
print(type(z))  # 输出:<class 'float'>

a = [1, 2, 3]
b = tuple(a)  # 将列表转换为元组
print(type(b))  # 输出:<class 'tuple'>

Precautions

When performing type conversion, an error may be thrown if the source data cannot be directly converted to the target type. For example, trying to convert a non-numeric string to an integer will raise ValueError.

x = "abc"
y = int(x)  # 尝试将非数字字符串转换为整数,将引发ValueError

Therefore, before performing type conversion, it is a good idea to verify that the data can be safely converted to the required type.

5. Exercise and Practice

Exercise 1: Create variables of different types and perform simple operations

# 创建整数变量
number = 10
number += 5  # 加法操作
print(number)  # 输出:15

# 创建浮点数变量
pi = 3.14159
pi *= 2  # 乘法操作
print(pi)  # 输出:6.28318

# 创建字符串变量
greeting = "Hello, "
name = "World"
full_greeting = greeting + name  # 字符串拼接
print(full_greeting)  # 输出:Hello, World

# 创建布尔变量
is_valid = True
is_valid = not is_valid  # 逻辑非操作
print(is_valid)  # 输出:False

Exercise 2: Demonstrate conversion between different types of data

# 字符串转换为整数
str_number = "123"
int_number = int(str_number)
print(type(int_number))  # 输出:<class 'int'>

# 整数转换为字符串
int_number = 456
str_number = str(int_number)
print(type(str_number))  # 输出:<class 'str'>

# 列表转换为元组
list_of_numbers = [1, 2, 3]
tuple_of_numbers = tuple(list_of_numbers)
print(type(tuple_of_numbers))  # 输出:<class 'tuple'>

# 元组转换为集合
tuple_of_numbers = (4, 5, 6)
set_of_numbers = set(tuple_of_numbers)
print(type(set_of_numbers))  # 输出:<class 'set'>

Exercise 3: Solve simple practical problems

Practical Question 1: Calculate the area of ​​a circle

# 给定半径
radius = 5.0

# 计算面积
area = 3.14159 * radius ** 2
print("圆的面积是:", area)  # 输出:圆的面积是: 78.53975

Practical question 2: Determine whether a number is even or odd

# 给定一个数
num = 7

# 判断偶数或奇数
if num % 2 == 0:
    print(num, "是偶数")
else:
    print(num, "是奇数")  # 输出:7 是奇数

Through these exercises, you can better understand variables and data types in Python, and how to convert between different types. These are the basis for writing more complex programs.

6. Python keywords

False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, 
except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield

These keywords play specific roles in Python’s syntax, for example:

if, elif, else are used for conditional judgment. for, while, break, and continue are used for loop control. def is used to define functions. class is used to define classes. try, except, finally, raise are used for exception handling. import, from are used for module import. return is used to return a value from a function. yield is used for value production in generator functions. True, False, and None are built-in constants in Python. To view the keyword list for the current version of the Python interpreter, you can use the keyword module:

import keyword
print(keyword.kwlist)

7. Summary and Outlook

1. Review and summary of the knowledge points in this chapter

This chapter mainly focuses on the basic knowledge of Python language learning, especially topics such as variables, data types, variable naming rules, Python keywords, data type detection and conversion, etc. The following is a review and summary of the knowledge points in this chapter:

  1. variable :
    • Variables are identifiers used to store data values.
    • Variables allow us to give data a name so that it can be referenced multiple times in a program.
  2. type of data :
    • Python's basic data types include numbers (integers, floating point numbers, complex numbers), sequences (strings, lists, tuples), maps (dictionaries), sets, and Boolean values.
    • Each data type has its specific purpose and operating rules.
  3. Variable naming rules :
    • Variable names must start with a letter (az, AZ) or an underscore (_).
    • Variable names can contain letters, numbers, and underscores, but they cannot begin with a number.
    • Variable names cannot be Python keywords.
  4. Python keywords :
    • Keywords are reserved words with special meaning in the Python language.
    • Keywords cannot be used as variable names or other identifiers.
  5. Data type detection and conversion :
    • Use type()a function to detect the data type of a variable.
    • Use isinstance()functions to check whether a variable is of a specific type or derived from a class.
    • Python provides a variety of built-in functions to convert variables from one data type to another, such as int(), float(), str(), list(), tuple(), set(), dict()and bool().
  6. Exercises and Practice :
    • Practice by creating different types of variables and performing simple operations.
    • Write code snippets to demonstrate conversion between different types of data.
    • Solve some simple practical problems to solidify your understanding of variables and data types.

Understanding these basics is crucial to learning Python in depth. They form the basis for writing effective, efficient, and maintainable code.

2, outlook

Python language learning day 4_Control structure: conditional statements and loops

This article is a reprint of the article Heng Xiaopai , and the copyright belongs to the original author. It is recommended to visit the original text. To reprint this article, please contact the original author.

Linus took matters into his own hands to prevent kernel developers from replacing tabs with spaces. His father is one of the few leaders who can write code, his second son is the director of the open source technology department, and his youngest son is a core contributor to open source. Huawei: It took 1 year to convert 5,000 commonly used mobile applications Comprehensive migration to Hongmeng Java is the language most prone to third-party vulnerabilities. Wang Chenglu, the father of Hongmeng: open source Hongmeng is the only architectural innovation in the field of basic software in China. Ma Huateng and Zhou Hongyi shake hands to "remove grudges." Former Microsoft developer: Windows 11 performance is "ridiculously bad " " Although what Laoxiangji is open source is not the code, the reasons behind it are very heartwarming. Meta Llama 3 is officially released. Google announces a large-scale restructuring
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/6851747/blog/11048992