mirror of
https://github.com/LCTT/TranslateProject.git
synced 2024-12-26 21:30:55 +08:00
commit
51be753696
@ -1,166 +0,0 @@
|
||||
[#]: subject: "Variables in Python: Concepts with Examples"
|
||||
[#]: via: "https://www.debugpoint.com/python-variables/"
|
||||
[#]: author: "Arindam https://www.debugpoint.com/author/admin1/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Variables in Python: Concepts with Examples
|
||||
======
|
||||
|
||||
**This tutorial explains the concept of variables in Python, their types, and how to use them with examples in real-world projects.**
|
||||
|
||||
In Python, a variable is a reserved memory location that stores a value.
|
||||
|
||||
They are names that can be assigned a value and used to reference it throughout your code. Using a variable makes a value accessible & gives values a context/meaning concerning your code.
|
||||
|
||||
Before you start, I hope you have Python installed and set up a basic editor. If not, do refer to my below guides:
|
||||
|
||||
- [How to Install Python 3.11 on Ubuntu/Linux][1]
|
||||
- [How to install Python on Windows][2]
|
||||
- [How to set up the IDLE editor for Python][3]
|
||||
|
||||
### Variable rules
|
||||
|
||||
- Variables are case-sensitive.
|
||||
- Variable names can only contain uppercase and lowercase letters (A–Z, a–z), digits (0–9), and underscores (_).
|
||||
- They can not start with digits.
|
||||
- Python variables are [dynamically typed][4].
|
||||
- Python supports Unicode variables (e.g. decorated letters like é and ü, and even Chinese, Japanese, and Arabic symbols).
|
||||
- As per [PEP 8 standard][5], variable names can be only lowercase, and words can be separated by underscores (e.g. total_price).
|
||||
|
||||
### Python Variables: Examples
|
||||
|
||||
To create a variable in Python, we need to assign a value to it using the assignment operator (=). For example, the following line of code creates a variable named “x” and assigns it the value of 10:
|
||||
|
||||
```
|
||||
x = 10
|
||||
```
|
||||
|
||||
In Python, variables are dynamically typed, which means that the interpreter can determine the data type of a variable based on the value it is assigned. Python supports various types of variables, including integers, floats, strings, booleans, and complex numbers.
|
||||
|
||||
```
|
||||
# Integer Variable
|
||||
age = 20
|
||||
|
||||
# Float Variable
|
||||
price = 4.99
|
||||
|
||||
# String Variable
|
||||
name = "John Doe"
|
||||
|
||||
# Boolean Variable
|
||||
is_active = True
|
||||
|
||||
# Complex Variable
|
||||
z = 2 + 3j
|
||||
```
|
||||
|
||||
Variables are useful in programming because they allow us to store and manipulate data. For example, we can use variables to perform mathematical operations, concatenate strings, and make decisions based on the value of a boolean variable.
|
||||
|
||||
```
|
||||
# Mathematical Operations
|
||||
x = 5
|
||||
y = 10
|
||||
z = x + y
|
||||
print(z) # Output: 15
|
||||
|
||||
# String Concatenation
|
||||
first_name = "John"
|
||||
last_name = "Doe"
|
||||
full_name = first_name + " " + last_name
|
||||
print(full_name) # Output: John Doe
|
||||
```
|
||||
|
||||
![A simple demonstration of variables in Python][6]
|
||||
|
||||
Variables can also be used in real-world projects to store and manipulate data. For example, in a web application, we can use variables to [store user input][7], database queries, and output data to the user.
|
||||
|
||||
```
|
||||
# User Input
|
||||
name = input("What is your name? ")
|
||||
print("Hello, " + name + "!") # Output: Hello, John!
|
||||
|
||||
# Database Queries
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("example.db")
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("SELECT * FROM users WHERE id = ?", (1,))
|
||||
user = cursor.fetchone()
|
||||
|
||||
print(user) # Output: (1, 'John Doe', 'johndoe@example.com')
|
||||
|
||||
# Output Data to User
|
||||
balance = 100.00
|
||||
print("Your current balance is ₹" + str(balance)) # Output: Your current balance is ₹100.0
|
||||
```
|
||||
|
||||
### Common Errors while using variables
|
||||
|
||||
There are a few common errors you can face while dealing with variables. Here are some of them.
|
||||
|
||||
- `NameError`: This error occurs when you try to access a variable that has not been defined. For example, if you try to print the value of a variable that has not been assigned a value yet, you will get a NameError. The following code gives a NameError because the variable “Full_name” is not defined.
|
||||
|
||||
```
|
||||
# NameError demonstration
|
||||
first_name = "John"
|
||||
last_name = "Doe"
|
||||
full_name = first_name + " " + last_name
|
||||
print(Full_name) # NameError
|
||||
```
|
||||
|
||||
![NameError example][8]
|
||||
|
||||
- `TypeError`: This error occurs when you try to operate on a variable of the wrong data type. For example, if you try to concatenate a string and an integer, you will get a TypeError. The below snippet of code gives TypeError.
|
||||
|
||||
```
|
||||
# TypeError demonstration
|
||||
first_name = "John"
|
||||
age = 10
|
||||
print(first_name + age)
|
||||
```
|
||||
|
||||
![TypeError example in Python][9]
|
||||
|
||||
- `ValueError`: This error occurs when you try to convert a variable to a different data type, but the conversion is impossible. For example, if you try to convert a string that contains letters to an integer, you will get a ValueError.
|
||||
|
||||
```
|
||||
# ValueError demonstration
|
||||
first_name = "John"
|
||||
age = 10
|
||||
print(int(first_name))
|
||||
```
|
||||
|
||||
![ValueError in Python][10]
|
||||
|
||||
### Wrapping Up
|
||||
|
||||
Understanding variables is essential for any Python developer. Variables allow us to store and manipulate data, perform mathematical operations, concatenate strings, etc. I hope this guide clarifies the concept if you are a beginner in Python programming.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://www.debugpoint.com/python-variables/
|
||||
|
||||
作者:[Arindam][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://www.debugpoint.com/author/admin1/
|
||||
[b]: https://github.com/lkxed/
|
||||
[1]: https://www.debugpoint.com/install-python-3-11-ubuntu/
|
||||
[2]: https://www.debugpoint.com/install-python-windows/
|
||||
[3]: https://www.debugpoint.com/install-idle-ubuntu-linux/
|
||||
[4]: https://en.wikipedia.org/wiki/Type_system
|
||||
[5]: https://peps.python.org/pep-0008/
|
||||
[6]: https://www.debugpoint.com/wp-content/uploads/2023/03/A-simple-demonstration-of-variables-in-Python.jpg
|
||||
[7]: https://www.debugpoint.com/input-function-python/
|
||||
[8]: https://www.debugpoint.com/wp-content/uploads/2023/03/NameError-example.jpg
|
||||
[9]: https://www.debugpoint.com/wp-content/uploads/2023/03/TypeError-example-in-Python.jpg
|
||||
[10]: https://www.debugpoint.com/wp-content/uploads/2023/03/ValueError-in-Python.jpg
|
@ -0,0 +1,166 @@
|
||||
[#]: subject: "Variables in Python: Concepts with Examples"
|
||||
[#]: via: "https://www.debugpoint.com/python-variables/"
|
||||
[#]: author: "Arindam https://www.debugpoint.com/author/admin1/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Python 中的变量:概念与示例
|
||||
======
|
||||
|
||||
**本教程解释了 Python 中变量的概念、它们的类型,以及如何在实际项目中使用的示例。**
|
||||
|
||||
在 Python 中,变量是存储值的保留内存位置。
|
||||
|
||||
它们是可以分配一个值并在整个代码中引用它的名称。使用变量使值可访问并为值提供与你的代码相关的上下文/含义。
|
||||
|
||||
在开始之前,我希望你已经安装了 Python 并设置了一个基本的编辑器。如果没有,请参考我的以下指南:
|
||||
|
||||
- [如何在 Ubuntu/Linux 上安装 Python 3.11][1]
|
||||
- [如何在 Windows 上安装 Python][2]
|
||||
- [如何为 Python 设置 IDLE 编辑器][3]
|
||||
|
||||
### 变量规则
|
||||
|
||||
- 变量区分大小写。
|
||||
- 变量名称只能包含大写和小写字母(A–Z、a–z)、数字 (0–9) 和下划线 (_)。
|
||||
- 他们不能以数字开头。
|
||||
- Python 变量是[动态类型][4]。
|
||||
- Python 支持 Unicode 变量(例如 é 和 ü 等装饰字母,甚至中文、日文和阿拉伯符号)。
|
||||
- 根据 [PEP 8 标准][5],变量名只能是小写,单词可以用下划线分隔(例如 total_price)。
|
||||
|
||||
### Python 变量:示例
|
||||
|
||||
要在 Python 中创建一个变量,我们需要使用赋值运算符 (=) 为其赋值。例如,下面的代码行创建了一个名为 “x” 的变量并为其赋值 10:
|
||||
|
||||
```
|
||||
x = 10
|
||||
```
|
||||
|
||||
在 Python 中,变量是动态类型的,这意味着解释器可以根据分配给它的值来确定变量的数据类型。Python 支持各种类型的变量,包括整数、浮点数、字符串、布尔值和复数。
|
||||
|
||||
```
|
||||
# 整型变量
|
||||
age = 20
|
||||
|
||||
# 浮点变量
|
||||
price = 4.99
|
||||
|
||||
# 字符串变量
|
||||
name = "John Doe"
|
||||
|
||||
# 布尔变量
|
||||
is_active = True
|
||||
|
||||
# 复数变量
|
||||
z = 2 + 3j
|
||||
```
|
||||
|
||||
变量在编程中很有用,因为它们允许我们存储和操作数据。例如,我们可以使用变量来执行数学运算、连接字符串以及根据布尔变量的值做出决策。
|
||||
|
||||
```
|
||||
# 数学运算
|
||||
x = 5
|
||||
y = 10
|
||||
z = x + y
|
||||
print(z) # Output: 15
|
||||
|
||||
# 字符串连接
|
||||
first_name = "John"
|
||||
last_name = "Doe"
|
||||
full_name = first_name + " " + last_name
|
||||
print(full_name) # Output: John Doe
|
||||
```
|
||||
|
||||
![A simple demonstration of variables in Python][6]
|
||||
|
||||
变量也可以在现实世界的项目中用于存储和操作数据。例如,在 Web 应用中,我们可以使用变量来[存储用户输入][7]、数据库查询以及向用户输出数据。
|
||||
|
||||
```
|
||||
# 用户输入
|
||||
name = input("What is your name? ")
|
||||
print("Hello, " + name + "!") # Output: Hello, John!
|
||||
|
||||
# 数据库查询
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("example.db")
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute("SELECT * FROM users WHERE id = ?", (1,))
|
||||
user = cursor.fetchone()
|
||||
|
||||
print(user) # Output: (1, 'John Doe', 'johndoe@example.com')
|
||||
|
||||
# 输出数据给用户
|
||||
balance = 100.00
|
||||
print("Your current balance is ₹" + str(balance)) # Output: Your current balance is ₹100.0
|
||||
```
|
||||
|
||||
### 使用变量时的常见错误
|
||||
|
||||
在处理变量时,你可能会遇到一些常见错误。这里是其中的一些。
|
||||
|
||||
- `NameError`:当你尝试访问尚未定义的变量时会发生此错误。例如,如果你尝试打印一个尚未赋值的变量的值,你将得到一个 NameError。以下代码给出了 NameError,因为变量 “Full_name” 未定义。
|
||||
|
||||
```
|
||||
# NameError 演示
|
||||
first_name = "John"
|
||||
last_name = "Doe"
|
||||
full_name = first_name + " " + last_name
|
||||
print(Full_name) # NameError
|
||||
```
|
||||
|
||||
![NameError example][8]
|
||||
|
||||
- `TypeError`:当你尝试对错误数据类型的变量进行操作时会发生此错误。例如,如果你尝试连接一个字符串和一个整数,你将得到 TypeError。下面的代码片段给出了 TypeError。
|
||||
|
||||
```
|
||||
# TypeError 演示
|
||||
first_name = "John"
|
||||
age = 10
|
||||
print(first_name + age)
|
||||
```
|
||||
|
||||
![TypeError example in Python][9]
|
||||
|
||||
- `ValueError`:当你尝试将变量转换为不同的数据类型但无法进行转换时会发生此错误。例如,如果你尝试将包含字母的字符串转换为整数,你将得到 ValueError。
|
||||
|
||||
```
|
||||
# ValueError 演示
|
||||
first_name = "John"
|
||||
age = 10
|
||||
print(int(first_name))
|
||||
```
|
||||
|
||||
![ValueError in Python][10]
|
||||
|
||||
### 总结
|
||||
|
||||
了解变量对于任何 Python 开发人员来说都是必不可少的。变量允许我们存储和操作数据、执行数学运算、连接字符串等。如果你是 Python 编程的初学者,我希望本指南能够阐明这个概念。
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://www.debugpoint.com/python-variables/
|
||||
|
||||
作者:[Arindam][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[geekpi](https://github.com/geekpi)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://www.debugpoint.com/author/admin1/
|
||||
[b]: https://github.com/lkxed/
|
||||
[1]: https://www.debugpoint.com/install-python-3-11-ubuntu/
|
||||
[2]: https://www.debugpoint.com/install-python-windows/
|
||||
[3]: https://www.debugpoint.com/install-idle-ubuntu-linux/
|
||||
[4]: https://en.wikipedia.org/wiki/Type_system
|
||||
[5]: https://peps.python.org/pep-0008/
|
||||
[6]: https://www.debugpoint.com/wp-content/uploads/2023/03/A-simple-demonstration-of-variables-in-Python.jpg
|
||||
[7]: https://www.debugpoint.com/input-function-python/
|
||||
[8]: https://www.debugpoint.com/wp-content/uploads/2023/03/NameError-example.jpg
|
||||
[9]: https://www.debugpoint.com/wp-content/uploads/2023/03/TypeError-example-in-Python.jpg
|
||||
[10]: https://www.debugpoint.com/wp-content/uploads/2023/03/ValueError-in-Python.jpg
|
Loading…
Reference in New Issue
Block a user