Skip to content

Variables

Variable Definition and Assignment

Basic Concepts

In Python, variables are containers for storing data. Unlike JavaScript, Python variables do not require a type declaration.

Variable Assignment

python
# Python - Direct assignment
name = "Alice"
age = 25
is_student = True
height = 1.75
javascript
// JavaScript - Requires a declaration keyword
const name = "Alice";
let age = 25;
const is_student = true;
const height = 1.75;

Multiple Assignment

Python supports assigning values to multiple variables simultaneously:

python
# Python - Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
javascript
// JavaScript - Requires separate assignment
const x = 1,
  y = 2,
  z = 3;
const a = (b = c = 0);

Swapping Variables

Python allows for elegant variable swapping:

python
# Python - Elegant swapping
a, b = 1, 2
a, b = b, a  # Swap values
print(a, b)  # Output: 2 1
javascript
// JavaScript - Requires a temporary variable or destructuring
let a = 1,
  b = 2;
[a, b] = [b, a]; // Using destructuring assignment
console.log(a, b); // Output: 2 1

Variable Naming Rules

Python Naming Conventions

  1. Can only contain: letters, numbers, and underscores
  2. Must start with: a letter or an underscore
  3. Case-sensitive
  4. Cannot be a keyword
python
# Correct naming
user_name = "Alice"
age2 = 25
_private_var = "private"
MAX_SIZE = 100

# Incorrect naming
# 2name = "Bob"      # Cannot start with a number
# user-name = "Bob"  # Cannot contain hyphens
# class = "Python"   # Cannot be a keyword

JavaScript Naming Conventions

javascript
// JavaScript naming rules are similar
const userName = "Alice";
const age2 = 25;
const _privateVar = "private";
const MAX_SIZE = 100;

Naming Convention Comparison

ConventionPythonJavaScript
Variable Namesnake_casecamelCase
ConstantUPPER_SNAKE_CASEUPPER_SNAKE_CASE
Class NamePascalCasePascalCase
Private Variable_leading_underscore_leadingUnderscore

Keyword Comparison

Python Keywords

python
# Python keywords (partial)
False, None, True, and, as, assert, 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

JavaScript Keywords

javascript
// JavaScript keywords (partial)
break, case, catch, class, const, continue, debugger,
default, delete, do, else, export, extends, finally,
for, function, if, import, in, instanceof, let, new,
return, switch, this, throw, try, typeof, var, void,
while, with, yield

Variable Scope

Python Scope

python
# Python - Scope rules
global_var = "I'm global"

def my_function():
    local_var = "I'm local"
    print(global_var)  # Can access global variables
    print(local_var)   # Can access local variables

def another_function():
    global global_var  # Declare use of a global variable
    global_var = "Modified global"

JavaScript Scope

javascript
// JavaScript - Scope rules
let globalVar = "I'm global";

function myFunction() {
  const localVar = "I'm local";
  console.log(globalVar); // 可以访问全局变量
  console.log(localVar); // 可以访问局部变量
}

function anotherFunction() {
  globalVar = "Modified global"; // 直接修改全局变量
}

动态类型

Python 动态类型

python
# Python - 变量类型可以改变
x = 10        # 整数
print(type(x))  # <class 'int'>

x = "Hello"   # 字符串
print(type(x))  # <class 'str'>

x = [1, 2, 3] # 列表
print(type(x))  # <class 'list'>

JavaScript 动态类型

javascript
// JavaScript - 变量类型也可以改变
let x = 10; // 数字
console.log(typeof x); // "number"

x = "Hello"; // 字符串
console.log(typeof x); // "string"

x = [1, 2, 3]; // 数组
console.log(typeof x); // "object"

练习

  1. 创建不同类型的变量并打印它们的类型

参考答案:

python
# Python
num = 10
flt = 3.14
text = "hello"
b = True
print(type(num), type(flt), type(text), type(b))
javascript
// JavaScript
let num = 10;
let flt = 3.14;
let text = "hello";
let b = true;
console.log(typeof num, typeof flt, typeof text, typeof b);
  1. 练习多重赋值和变量交换

参考答案:

python
# Python
a, b = 1, 2
a, b = b, a
print(a, b)
javascript
// JavaScript
let a = 1,
  b = 2;
[a, b] = [b, a];
console.log(a, b);
  1. 比较 Python 和 JavaScript 的变量命名约定

参考答案:

  • Python 推荐使用小写字母和下划线(snake_case),如 my_variable。
  • JavaScript 推荐使用小驼峰(camelCase),如 myVariable。
  • 常量:Python 用全大写,JS 也常用全大写。
  1. 测试变量作用域规则

参考答案:

python
# Python
def foo():
    x = 10  # 局部变量
    print(x)
x = 5  # 全局变量
foo()
print(x)
javascript
// JavaScript
let x = 5; // 全局变量
function foo() {
  let x = 10; // 局部变量
  console.log(x);
}
foo();
console.log(x);

下一步

现在你已经了解了 Python 的变量系统,接下来我们将深入学习 Python 的数据类型。