Skip to content

Latest commit

 

History

History
135 lines (101 loc) · 11.5 KB

File metadata and controls

135 lines (101 loc) · 11.5 KB

Variables in Python

For beginners who want to learn programming, there are two questions they may really want to know. One is, "What is a computer program?" The other is, "What can writing computer programs do?" Let me first talk about my understanding of these two questions: a program is an ordered collection of data and instructions, and writing programs means using data and instructions to control the computer and make it do what we want. Today, why do so many people choose Python to write programs? Because Python is simple enough and powerful enough. Compared with programming languages such as C, C++, and Java, Python is more friendly to beginners and non-professionals, and many problems can be solved in simple and elegant ways in Python. Next, we will start with the most basic language elements and get to know Python and learn how to use it.

A Few Basics

Before we start learning Python programming in a systematic way, let us first talk about some basic computer knowledge. A computer hardware system is usually made up of five major parts: the arithmetic unit, control unit, memory, input devices, and output devices. Among them, the arithmetic unit and control unit together are what we often call the central processing unit (CPU). Its job is to execute all kinds of arithmetic and control instructions. As we just said, a program is a collection of instructions. Writing a program means organizing a series of instructions in some way, and then using these instructions to control the computer and make it do what we want.

Memory can be divided into internal memory and external memory. The former is what we often call RAM. It is storage space that the CPU can address directly. While a program is running, the related data and instructions need to be loaded into memory. Input devices and output devices are often together called I/O devices. Keyboards, mice, microphones, and cameras are typical input devices, while monitors, printers, speakers, and so on are typical output devices. At present, most of the computers we use follow the von Neumann architecture. This kind of computer has two key points: first, memory is separated from the CPU; second, data is encoded in binary form.

Binary is a counting method that "carries one for every two". In essence, it is the same as the decimal counting method people use, which "carries one for every ten". Because humans have ten fingers, we use decimal counting. After all ten fingers are used up, we can only use carrying to represent larger numbers. Of course, there are exceptions. The Maya may have used their toes too because they often went barefoot, so they used a base-20 counting system. Because of this way of counting, the Maya calendar was different from the calendar we use in daily life. According to the Maya calendar, 2012 was the last year of the previous so-called "sun age", and 2013 was the beginning of a new "sun age". Later, this was passed from mouth to mouth and turned into the absurd claim that "2012 was the end of the world predicted by the Maya". Today, many people guess that the slow development of Maya civilization had something to do with using base 20.

For computers, binary is the easiest thing 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 conversion between decimal, binary, octal, and hexadecimal. Most of the time, we can still write programs even if we do not understand this knowledge. However, we must know that computers count in binary, and no matter what kind of data it is, once it enters computer memory, it exists in binary form.

Note: Regarding binary counting and how it is converted to and from other number systems, you can look through books such as Introduction to Computers or Computer Culture. You can find the related knowledge there, so it will not be explained in detail here. Readers who are not clear about it can study it by themselves.

Variables and Types

If we want to store data in computer memory, we first need to talk about the concept of variables. In programming languages, variables are carriers of data. Simply speaking, a variable is a piece of memory space used to save data, and the value of a variable can be read and changed. This is the basis of all computation and control. Computers can process many kinds of data. The most common kind is numbers, but besides numbers there are also text, images, audio, video, and many other kinds of data. Although all data exists in binary form inside a computer, we can use variables of different types to show the differences between data types. Python has many built-in data types, and it also allows us to define new data types ourselves. We will talk about that later. Let us first understand several of the most commonly used data types in Python.

  1. Integer (int): Python can handle integers of any size, and it supports binary (for example, 0b100, which is 4 in decimal), octal (for example, 0o100, which is 64 in decimal), decimal (100), and hexadecimal (0x100, which is 256 in decimal) notation. Run the code below and see what it outputs.

    print(0b100)  # binary integer
    print(0o100)  # octal integer
    print(100)    # decimal integer
    print(0x100)  # hexadecimal integer
  2. Floating-point (float): Floating-point numbers are decimal numbers. They are called floating-point numbers because in scientific notation, the position of the decimal point can change. Besides normal notation such as 123.456, floats also support scientific notation such as 1.23456e2, which means $\small{1.23456 \times 10^{2}}$. Run the code below and see what it outputs.

    print(123.456)    # standard decimal notation
    print(1.23456e2)  # scientific notation
  3. String (str): A string is any piece of text enclosed in single or double quotes, such as 'hello' or "hello".

  4. Boolean (bool): The Boolean type has only two values, True and False. It can be used to represent "yes" and "no" in the real world, the "true" and "false" of propositions, "good" and "bad" states, "high" and "low" levels, and so on. If a variable has only two possible states, then we can use the Boolean type.

Naming Variables

For every variable, we need to give it a name, just as each of us has our own name. In Python, variable names need to follow the rules and conventions below.

  • Rules:
    • Rule 1: Variable names are made up of letters, digits, and underscores, and they cannot start with a digit. It should be explained that the "letters" here mean Unicode characters. Unicode is a universal character set, and it includes most writing systems in the world. This means Chinese, Japanese, Greek letters, and so on can all appear in variable names. But special characters such as , @, and # cannot appear in variable names. We strongly recommend that you understand "letters" here as using only English letters as much as possible.
    • Rule 2: Python is a case-sensitive programming language. Simply speaking, uppercase A and lowercase a are two different variables. This is not really a rule, but it is something everyone needs to pay attention to.
    • Rule 3: A variable name should not have the same name as a Python keyword, and it should avoid Python reserved words as much as possible. Keywords are words with special meaning in Python programs, such as is, if, else, for, while, True, and False. Reserved words mainly mean the names of built-in functions, built-in modules, and so on in Python, such as int, print, input, str, math, and os.
  • Conventions:
    • Convention 1: Use lowercase English letters, and join multiple words with underscores.
    • Convention 2: Protected variables usually begin with a single underscore.
    • Convention 3: Private variables usually begin with two underscores.

You do not need to worry about conventions 2 and 3 for now. You will understand them naturally later. Of course, as a professional programmer, it is also very important to choose names that clearly show their meaning. This shows a programmer's professional quality, and many interviews for development positions also care a lot about this point.

Using Variables

The examples below show variable types and how to use variables.

"""
Use variables to store data and perform arithmetic

Version: 1.0
Author: Luo Hao
"""
a = 45        # define variable a and assign 45
b = 12        # define variable b and assign 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, we can use the type function to check the type of a variable. In programming, the concept of a function is very similar to the concept of a function in mathematics. I believe everyone is familiar with mathematical functions. They include a function name, independent variables, and dependent variables. If you do not understand the concept of a function for the moment, that is fine. We will explain the definition and use of functions later.

"""
Use the type function to inspect 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'>

We can change the type of a variable through Python's built-in functions. Below are some common functions related to variable types.

  • int(): convert a number or string to an integer, and you can also specify the base.
  • float(): convert a string to a floating-point number when possible.
  • str(): convert the specified object to string form, and an encoding method can also be specified.
  • chr(): convert an integer character code to a one-character string.
  • ord(): convert a one-character string to its integer character code.

The example below shows type conversion in Python.

"""
Type conversion for variables

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 100 to float -> 100.0
print(int(b))           # convert float 123.45 to int -> 123
print(int(c))           # convert string '123' to int -> 123
print(int(c, base=16))  # treat string '123' as hexadecimal -> 291
print(int(d, base=2))   # treat string '100' as binary -> 4
print(float(e))         # convert string '123.45' to float -> 123.45
print(bool(f))          # non-empty string converts to True
print(int(g))           # True converts to 1
print(chr(a))           # integer 100 converts to 'd'
print(ord('d'))         # character 'd' converts to 100

Note: When converting from str to int, you can use the base parameter to specify the number system and convert the string as an integer in that base. When converting from str to bool, as long as the string has content and is not '' or "", the resulting Boolean value is True. When converting from bool to int, True becomes 1 and False becomes 0. In both the ASCII character set and the Unicode character set, the character 'd' corresponds to the code 100.

Summary

In Python programs, we can use variables to save data, and variables have different types. Common types include int, float, str, and bool. When needed, we can use Python's built-in functions to convert the types of variables. Variables can be used in computation, and this is the condition we need before solving many problems. In the next lesson, we will introduce operations on variables in detail.