Python Variables
For newcomers who want to learn programming, there are two questions they might be eager to know: first, “what is a (computer) program”, and second, “what can writing (computer) programs do”. Let me share my understanding of these two questions: a program is an ordered collection of data and instructions, and writing programs is using data and instructions to control computers to do what we want them to do. Today, why do so many people choose to use Python to write programs? Because Python is simple and powerful enough. Compared to programming languages like C, C++, and Java, Python is more friendly to beginners and non-professionals. Many problems can find simple and elegant solutions in Python. Next, we’ll start with the most basic language elements to help you understand and use Python.
Some Common Knowledge
Before systematically learning Python programming, let’s popularize some basic computer knowledge. A computer’s hardware system usually consists of five major components: arithmetic unit, control unit, memory, input devices, and output devices. Among them, the arithmetic unit and control unit together form what we commonly call the central processing unit (CPU), whose function is to execute various operations and control instructions. As mentioned earlier, a program is a collection of instructions, and writing programs means organizing a series of instructions in a certain way, then using these instructions to control the computer to do what we want it to do. Memory can be divided into internal memory and external memory. The former is what we commonly call RAM, which is the storage space that the central processing unit can directly address. During program execution, corresponding data and instructions need to be loaded into memory. Input devices and output devices are often collectively referred to as I/O devices. Keyboards, mice, microphones, and cameras are typical input devices, while monitors, printers, and speakers are typical output devices. Currently, most computers we use follow the “von Neumann architecture”, which has two key points: first, separating memory from the central processing unit; second, encoding data in binary.
Binary is a “carry-over-two” counting method, which is essentially the same as the “carry-over-ten” counting method used by humans. Humans use the decimal counting method because they have ten fingers, so when counting, after using all ten fingers, they can only use carry-over to represent larger values. Of course, there are exceptions. The Mayans, possibly because they went barefoot for many years, also used their toes, so they used a base-twenty counting method. Based on this counting method, the Mayan calendar differs from the calendar we commonly use. According to the Mayan calendar, 2012 was the last year of the previous so-called “Sun Era”, and 2013 was the beginning of a new “Sun Era”. Later, this was mistakenly spread as the absurd claim that “2012 is the end of the world predicted by the Mayans”. Today, many people speculate that the slow development of Mayan civilization is related to using base-twenty. For computers, binary is the easiest to implement in physical devices because high voltage can represent 1 and low voltage can represent 0. Not everyone who writes programs needs to be familiar with binary, or with the conversion between decimal, binary, octal, and hexadecimal. Most of the time, we can write programs without understanding this knowledge. However, we must know that computers use binary counting, and no matter what kind of data, it exists in binary form in computer memory.
Note: Regarding binary counting and how it converts to other bases, you can refer to books titled “Introduction to Computer Science” or “Computer Culture”, where you can find relevant knowledge. This won’t be elaborated here; readers who are unclear can research on their own.
Variables and Types
To save data in computer memory, we first need to talk about the concept of variables. In programming languages, a variable is a carrier of data. Simply put, it’s a piece of memory space used to save data. The value of a variable can be read and modified, which is the foundation of all operations and control. Computers can process many types of data. The most common is numerical data, but besides numbers, there are also various data types such as text, images, audio, and video. Although data exists in binary form in computers, we can use different types of variables to represent differences in data types. Python has preset multiple data types and also allows us to define new data types, which will be covered later. Let’s first understand several of the most commonly used data types in Python.
-
Integer (
int): Python can handle integers of any size and supports binary (like0b100, which is 4 in decimal), octal (like0o100, which is 64 in decimal), decimal (100), and hexadecimal (like0x100, which is 256 in decimal) representations. Run the following code to see what it outputs.print(0b100) # Binary integer print(0o100) # Octal integer print(100) # Decimal integer print(0x100) # Hexadecimal integer -
Float (
float): Floating-point numbers are decimals. They’re called floating-point numbers because when represented in scientific notation, the decimal point position of a floating-point number is variable. Besides mathematical notation (like123.456), floating-point numbers also support scientific notation (like1.23456e2, representing $\small{1.23456 \times 10^{2}}$). Run the following code to see what it outputs.print(123.456) # Mathematical notation print(1.23456e2) # Scientific notation -
String (
str): A string is any text enclosed in single or double quotes, such as'hello'and"hello". -
Boolean (
bool): Boolean type has only two values,TrueandFalse, eitherTrueorFalse. It can be used to represent “yes” and “no” in the real world, “true” and “false” of propositions, “good” and “bad” of situations, “high” and “low” of levels, etc. If a variable’s value has only two states, we can use the boolean type.
Variable Naming
For each variable, we need to give it a name, just as each of us has our own name. In Python, variable naming needs to follow the following rules and conventions.
- Rules:
- Rule 1: Variable names consist of letters, numbers, and underscores, and cannot start with a number. It should be noted that the letters here refer to Unicode characters, which encompasses most of the world’s writing systems, meaning Chinese, Japanese, Greek letters, etc. can all be used as characters in variable names, but some special characters (such as:
!,@,#, etc.) cannot appear in variable names. We strongly recommend that you understand the letters here as using only English letters as much as possible. - Rule 2: Python is case-sensitive, which simply means that uppercase
Aand lowercaseaare two different variables. This isn’t really a rule, but something everyone needs to pay attention to. - Rule 3: Variable names should not conflict with Python keywords, and should avoid Python reserved words as much as possible. Keywords here refer to words with special meanings in Python programs (such as:
is,if,else,for,while,True,False, etc.), and reserved words mainly refer to names of Python’s built-in functions, built-in modules, etc. (such as:int,print,input,str,math,os, etc.).
- Rule 1: Variable names consist of letters, numbers, and underscores, and cannot start with a number. It should be noted that the letters here refer to Unicode characters, which encompasses most of the world’s writing systems, meaning Chinese, Japanese, Greek letters, etc. can all be used as characters in variable names, but some special characters (such as:
- Conventions:
- Convention 1: Variable names usually use lowercase English letters, with multiple words connected by underscores.
- Convention 2: Protected variables start with a single underscore.
- Convention 3: Private variables start with two underscores.
You don’t need to worry about conventions 2 and 3 for now; you’ll naturally understand them later. Of course, as a professional programmer, making variable names self-explanatory when naming variables is also very important. This demonstrates a programmer’s professional demeanor, and many development position interviews also value this point.
Using Variables
Below we’ll explain variable types and variable usage through examples.
"""
Using variables to save data and perform addition, subtraction, multiplication, and division operations
Version: 1.0
Author: Luo Hao
"""
a = 45 # Define variable a, assign value 45
b = 12 # Define variable b, assign value 12
print(a, b) # 45 12
print(a + b) # 57
print(a - b) # 33
print(a * b) # 540
print(a / b) # 3.75
In Python, you can use the type function to check the type of a variable. The concept of functions in programming is very similar to the concept of functions in mathematics. I’m sure everyone is familiar with mathematical functions, which include the function name, independent variables, and dependent variables. If you don’t understand the concept of functions for now, don’t worry. We’ll specifically explain function definition and usage in subsequent content.
"""
Using the type function to check variable types
Version: 1.0
Author: Luo Hao
"""
a = 100
b = 123.45
c = 'hello, world'
d = True
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'str'>
print(type(d)) # <class 'bool'>
You can change the type of a variable through Python’s built-in functions. Below are some commonly used functions related to variable types.
int(): Converts a number or string to an integer, can specify the base.float(): Converts a string (when possible) to a floating-point number.str(): Converts a specified object to string form, can specify encoding.chr(): Converts an integer (character code) to the corresponding (single character) string.ord(): Converts a (single character) string to the corresponding integer (character code).
The following example demonstrates type conversion operations in Python.
"""
Variable type conversion operations
Version: 1.0
Author: Luo Hao
"""
a = 100
b = 123.45
c = '123'
d = '100'
e = '123.45'
f = 'hello, world'
g = True
print(float(a)) # Convert int type 100 to float, output 100.0
print(int(b)) # Convert float type 123.45 to int, output 123
print(int(c)) # Convert str type '123' to int, output 123
print(int(c, base=16)) # Convert str type '123' as hexadecimal to int, output 291
print(int(d, base=2)) # Convert str type '100' as binary to int, output 4
print(float(e)) # Convert str type '123.45' to float, output 123.45
print(bool(f)) # Convert str type 'hello, world' to bool, output True
print(int(g)) # Convert bool type True to int, output 1
print(chr(a)) # Convert int type 100 to str, output 'd'
print(ord('d')) # Convert str type 'd' to int, output 100
Note: When converting
strtype tointtype, you can specify the base through thebaseparameter, treating the string as an integer in the corresponding base for conversion. When convertingstrtype tobooltype, as long as the string has content and isn’t''or"", the corresponding boolean value isTrue. When convertingbooltype tointtype,Truebecomes1andFalsebecomes0. In both ASCII and Unicode character sets, the character'd'corresponds to code100.
Summary
In Python programs, we can use variables to save data, and variables have different types. Commonly used types are int, float, str, and bool. When necessary, variables can be type-converted through Python’s built-in functions. Variables can perform operations, which is a prerequisite for solving many problems. We’ll introduce variable operations in detail in the next lesson.