Chapter 1: User Interaction

This article is part of the Python General Programming tutorial series, which has been fully completed. Its goal is to take you from zero to mastery of the Python programming language. This tutorial doesn’t just talk about Python in general terms; it explains things in a detailed and in-depth way, across 5 stages and 25 chapters. So you need to study patiently to really get something out of it. Although it doesn’t cover the use of any frameworks, it gives a comprehensive explanation of operating systems and network communication, and even rewrites some open-source modules and servers. After finishing it, you’ll gain not only mastery of the Python programming language, but also the ability to learn other programming languages quickly, the ability to read any Python source code without difficulty, and a comprehensive understanding of computers and networks. For complete beginners, it’s an excellent textbook for entering the field of computing and mastering a programming language. For those who already have some Python foundation, I believe this tutorial will take your skills to the next level.

I. Introduction to Programming

1. The Concept of Programming

When learning a programming language, we first need to understand clearly what programming is and why we program, and only then learn how to program.

Computers were invented to replace human labor with machines, helping humans do endless work without even being paid a salary. That’s the purpose of programming. Because computers don’t understand human language, humans have to speak the computer’s language to tell the computer how the work should be done. The process of humans speaking “machine language” is actually programming: humans convey the work we need done to the computer through certain instructions.

2. Programming Languages

The forms of expression mentioned above that can be recognized by computers are programming languages. Language is the medium of communication between people, and programming languages are the bridge of communication between programmers and computers.

3. Classification of Programming Languages

You just speak “machine language” and that’s it—surely there aren’t different kinds of “machine language”?

Yes, there are. Human language is divided into Chinese, English, Italian and other languages, and naturally “machine language” is also divided.

Programming languages have gone through three stages of development up to today: machine language, assembly language and high-level languages.

Machine language can be understood as humans speaking pure “machine talk”. First we need to know that computers work on binary, so binary is what computers can understand (binary will be explained in detail later when we get to character encoding). So let’s program in binary: for example, if I want the computer to compute 100 plus 200, I’d do this:

1100100,101011,11001000

Note: binary 1100100 represents decimal 100, binary 11001000 represents decimal 200, and binary 101011 represents the ”+” symbol. Computing 100+200 written in machine language would look roughly like the code above. I’m too young; I wasn’t born in that wonderful era. Obviously, writing programs this way is extremely painful for programmers, and development efficiency is very low. On the other hand, when a computer sees something like 100100000, it thinks, “This suits my taste, I love this stuff.” But you, as a programmer, can’t easily write stuff like this. So to sum up, with machine language humans program from the computer’s point of view: development efficiency is low, and program execution efficiency is high.

Assembly language can be understood as humans speaking “machine-human talk”: humans use abbreviated English identifiers in place of binary. This certainly improves how efficiently humans can write code, but the computer is a bit unhappy, because it’s not direct binary: these English identifiers must first be converted into binary before the code can be executed. So compared with machine language, assembly language improves development efficiency while slightly reducing program execution efficiency.

High-level languages can be understood as humans speaking “human talk” (humans: finally we can talk properly). They’re called high-level because they’re fundamentally different from the two kinds of languages above: high-level languages are built on top of an operating system, while the two programming languages above don’t need an operating system and operate the hardware directly. Operating systems were created by humans, and their purpose is to improve people’s productivity and let people use computers better. Thanks to the encapsulation provided by the operating system, it takes on the miserable job of operating the hardware itself, making programming very friendly for programmers, who can program with syntax very similar to their own language. This greatly improves programmers’ development efficiency. The computer, on the other hand, has objections to this.

# Computer: You foolish humans, what kind of junk operating system have you made? I have to translate this into binary before I can execute it, and it runs very slowly. I'm very unhappy, and the consequences will be serious.
# Programmer: I don't care whether you're happy or not, what can you do to me? "The consequences will be serious"—oh, I'm so scared. Why don't you just go fly to the sky?
# Computer: Oh, fine...... you win......

Next, let’s sum it up in one sentence: from machine language to assembly language to high-level languages, programmers’ development efficiency has increased while program execution efficiency has decreased. So is this progress or regression?

Speed isn’t the key; development efficiency is king. Because speed has a bottleneck: going from machine language to high-level languages, speed drops, but it’s still so fast that the human brain can’t perceive the difference. 0.000000001 seconds and 0.00001 seconds should make no difference to you, even though they differ by a factor of 10,000. Development efficiency, however, can be improved dramatically, so this development is naturally progress.

II. Classification of High-Level Languages

High-level languages are closer to human language. They must first be converted into binary that the computer can understand before they can be executed. According to the way they are converted, they are divided into:

Compiled languages and interpreted languages

Compiled languages need a compiler, like Google Translate. The code you write is a program, and it must be compiled before it runs (just like translating an English book into Chinese before giving it to you to read). Only after the compiled result has been converted into binary can the computer run it. This creates a problem: when the program needs to be modified, you can’t directly modify the compiled object file; instead, you modify the source file, compile it again to generate the object file, and then the computer runs it again so you can see the result of the change. Because different computers have different operating systems, the object files generated by the compiler also differ (different operating systems provide different hardware interfaces, so different hardware interfaces need different binary files to run). Compared with interpreted languages, compiled languages execute faster and depend on a compiler; the key point is that debugging is very cumbersome. Languages like C and C++ are compiled languages.

Interpreted languages need an interpreter, like an oral interpreter who translates sentence by sentence. The application’s source code is “translated” into object code (machine language) by the corresponding language’s interpreter while it is being executed, so efficiency is relatively low. Also, no standalone executable file can be generated, and the application can’t run without its interpreter (to run it, you must first install the interpreter, just like when talking to a foreigner, an interpreter must be present). But this approach is more flexible and allows the application to be adjusted and modified dynamically. Languages like Python and PHP are interpreted languages.

The execution process of compiled languages and interpreted languages

Summary: compiled languages and interpreted languages each have their own pros and cons. When the program we need to write doesn’t need frequent changes or upgrades, we generally choose a compiled language, for example when writing an operating system or other relatively low-level applications. When the program we write needs frequent changes and upgrades to meet users’ new needs, we generally choose an interpreted language, for example for application software and website projects. It’s worth mentioning that, thanks to its simplicity and high level of encapsulation, Python is still the easiest to debug and the most flexible to use among interpreted languages. So when a project needs rapid development and iteration, many new projects in companies choose Python. It can be used to write APIs for mobile apps, to build web projects, and also to perform fairly complex machine learning and data mining computations very conveniently, and so on. That’s one of the reasons Python is so popular.

III. Introduction to Python

1. About the Python Language

The creator of Python is Guido van Rossum. During Christmas 1989, Guido began writing an interpreter capable of interpreting the syntax of the Python language. The name Python comes from Guido’s beloved TV series Monty Python’s Flying Circus. He hoped this new language called Python would live up to his ideals: simple and elegant, efficient to use, and richly extensible. In the latest TIOBE ranking, Python overtook C++ to take 3rd place. Python values beauty, clarity and simplicity, and is an excellent and widely used language.

1280px-Guido_van_Rossum_OSCON_2006.jpg

2. Python’s Six Main Application Scenarios

  1. Artificial intelligence: after PyTorch and TensorFlow were open-sourced, Python has been the undisputed leader in the field of artificial intelligence.
  2. Data analysis: this includes not only quantitative financial analysis and big data analysis, but also scientific computing. In the past, people used MATLAB and Octave for scientific computing, but when it came to actual application development they still had to use C++, Java or R, and the large amount of code made the work difficult. Now we have the more efficient and concise Python, and there’s no doubt that Python has become the mainstream language in the field of data analysis.
  3. Web crawler development: Python’s Scrapy\Request\BeautifuSoup and others can quickly and conveniently crawl most information on the web, requiring at least 50% less code than Java.
  4. Website development: Python’s three mainstream web frameworks, Django, Flask and Tornado, let startups quickly build the business logic of their core products.
  5. Cloud computing development: OpenStack, the most famous open-source cloud computing framework today, is written in Python, which has also greatly promoted the development of the cloud computing industry.
  6. Automated operations: as a scripting language, Python, thanks to its flexibility and efficiency, has become a required course for almost all operations engineers.

3. Python in Companies

  • Google: Google App Engine, code.google.com, Google Earth, Google’s crawler, Google Ads and other projects make heavy use of Python
  • CIA: the website of the US Central Intelligence Agency is developed in Python
  • NASA: the US space agency (NASA) uses Python extensively for data analysis and computation
  • YouTube: YouTube, the world’s largest video website, is developed in Python
  • Dropbox: the largest online cloud storage website in the US is implemented entirely in Python, handling the upload and download of 1 billion files every day
  • Instagram: the largest photo-sharing social network in the US, where more than 30 million photos are shared every day, is developed entirely in Python
  • Facebook: a large number of its foundational libraries are implemented in Python
  • Redhat: the yum package manager in the world’s most popular Linux distribution is developed in Python
  • Douban: almost all of the company’s business is developed in Python
  • Zhihu: the largest Q&A community in China (Quora abroad) is developed in Python
  • Chunyu Doctor: a well-known Chinese online medical website, developed in Python
  • Besides those listed above, companies such as Sohu, Kingsoft, Tencent, Shanda, NetEase, Baidu, Alibaba, Taobao, Tudou, Sina and Guokr all use Python to accomplish all kinds of tasks.

4. Python 2 or Python 3

Although many companies in the industry still make heavy use of Python 2.6 or 2.7—because quickly upgrading old projects with hundreds of thousands or even millions of lines of code to 3.0 is no easy task—almost everyone uses 3.x when developing new projects. In addition, Python 3 really has made many improvements over 2.x. Intuitively speaking, it’s like the feeling of upgrading from XP to Win7: awesome. We’ll gradually dig into the specific differences between Python 2 and Python 3 in later lessons.

5. Installing the Python Interpreter

Python now supports all mainstream operating systems. Although Linux and Mac systems come with a Python environment, we still need to install a newer version of Python, namely Python 3.X.

Open the download center on the official website https://www.python.org/downloads/

image.png

Download the executable installer version for your operating system and install it.

6. Writing Hello World in Python

There are two ways to write programs:

  1. Enter the interpreter’s interactive mode: convenient for debugging, but the code can’t be saved permanently
  2. Use script files (with a code-writing tool, an IDE): the code is saved permanently

Write a Hello World program in Python

print('Hello World')

Compare how Hello World is written in other languages

# C++
#include <iostream>
 int main(void)
 {
  std::cout<<"Hello world";
 }

# C
#include <stdio.h>
int main()
{
printf("\nhello world!");
return 0;
}

# JAVA
public class HelloWorld{
  // Program entry point
  public static void main(String args[]){
    // Output a message to the console
    System.out.println("Hello World!");
  }
}

# PHP
<?php
             echo "hello world!";  
?>

# GO
package main
import "fmt"
func main(){
    fmt.Printf("Hello World!\n God Bless You!");
}
# Hello world in every language you could master

7. Installing a Python IDE

IDE stands for Integrated Development Environment, an application that provides a program development environment. It generally includes tools such as a code editor, compiler, debugger and graphical user interface. Put simply, it’s a tool for writing code, just like Word is used for editing documents on Windows, letting you write more elegant documents more efficiently.

Here we recommend three options:

  1. Use PyCharm: it has fairly friendly code hints, is suited to writing engineering-style projects, and is convenient for debugging
  2. Use Jupyter: it’s easy to install and makes data processing more convenient
  3. Use VS Code: one piece of software meets the needs of writing many languages, and it’s flexibly extensible

Open the official website https://www.jetbrains.com/pycharm/ and download PyCharm for your operating system

image.png

IV. Variables and Constants

1. The Concept of a Variable

Put plainly, the work a computer does consists of creating, deleting, updating and querying data, so data is certainly changing. To store changing data, we should use “variables”.

What is a variable

  • A variable is a quantity that varies. The core lies in the two words “vary” and “quantity”: vary means change, and quantity means measuring a state.

Why do we need variables

  • The essence of program execution is a series of state changes, and change is the direct manifestation of program execution. So we need a mechanism that can reflect, or save, the state of the program during execution as well as changes in that state. #For example: a hero’s level is 1, and after fighting monsters it levels up (changes) to 10; a zombie’s alive state is True, and when it’s killed by the plants, it changes to False; a person’s name is Albert, and it can also be changed to AlbertMa.

How Python defines variables

  • Variable name (like a house number, pointing to the space where the value is stored), equals sign, variable value; assignment goes from right to left.
name='Albert'
sex='male'
age=18
level=10

2. Rules for Defining Python Variables

  • A variable name can only be any combination of letters, digits or underscores
  • The first character of a variable name cannot be a digit
  • The following keywords cannot be used as variable names

[‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘exec’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘not’, ‘or’, ‘pass’, ‘print’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

3. Ways of Naming Python Variables:

Camel case

Camel case naming is used when a variable name or function name is made up of one or more words joined together.

There are two kinds of camel case:

1 Upper camel case: the first letter of every word is capitalized, AgeOfTeacher

2 Lower camel case: the first letter of every word except the first is capitalized, ageOfTeacher.

#Upper camel case
AgeOfAlbert = 18  
NumberOfStudents = 80
#Lower camel case
ageOfTeacher = 28

Underscores (recommended)

age_of_albert = 18  
number_of_students = 80

Bad ways to name variables

  1. Variable names in Chinese or pinyin
  2. Variable names that don’t convey their meaning
  3. Variable names in Chinese: Python actually supports Chinese variable names, which really overturned my worldview. Maybe it’s an optimization made to accommodate some of our Chinese code monkeys

It’s worth mentioning that when projects in a company are large, we often use fairly long variable names. On one hand this keeps variable names from clashing, and on the other hand it lets you know what the data means just by looking at the variable name

Here’s a saying for you: the name is the logic

A defined variable has: id (unique identifier), type (variable type), and value (variable value)

4. Constants

A constant is a quantity that doesn’t change, such as pi 3.141592653…, or a quantity that doesn’t change while the program runs. For example: the age of the Japanese prime minister is a variable, but if he suddenly died today, that age would no longer change, and then it would be a constant. Python has no dedicated syntax for constants; by convention, programmers use all-uppercase variable names to represent constants

JAPANESE_PRIME_MINISTER_AGE = 56

In C there is a dedicated syntax for defining constants, const int count = 60; once something is defined as a constant, changing it raises an error

V. Basic Data Types

1. Explanation

Python doesn’t allow different types to be added together. It is dynamic: defining a variable requires no data type declaration, and a variable’s type is determined when it is first assigned a value

2. String (str)

Just now we defined a person’s name with name = ‘Albert’. Defining something by writing content between single quotes, double quotes or triple quotes, like ’ ’ or ” ” or """ """, gives the str type, which we call the string type

print('Hello world')  # This is a string type

When defining, the right-hand side of the equals sign is assigned to the variable on the left-hand side

We need to know not only that its data type is str; when learning a data type, we also need to know whether it is a mutable or immutable type.

  • Immutable type: when the variable’s value changes, its id changes too, which is equivalent to allocating a new block of memory and reassigning the variable; the original value cannot be changed. str is an immutable type
  • Mutable type: when the variable’s value changes, its id can stay the same, which is equivalent to modifying it in place; its location doesn’t change

You can think of a mutable type as a big house that stays put, and renovating the house is making a modification. An immutable type is a house that can’t be renovated: if you want to change it, fine, build another house somewhere else and move in there.

3. Integer (int)

When we define a person’s age, we use age = 18, putting an integer directly after the equals sign. The data type of this variable is the int type, which we call integer. The integer is an immutable type

4. Floating Point (float)

When we define a person’s height, we use height = 1.83. Likewise, this is the float type, which we call floating point. Floating point is an immutable type; intuitively, it’s for variables whose values need to be precise to decimal places.

5. List (list)

When we need to store the names of all the students in a class, we’re using one variable to store multiple values. The three data types above can each store only one value; in this case we can use the list data type, which we call a list. How it’s defined: inside square brackets, multiple elements separated by commas, where each element can be of any data type. A list is a mutable type

names = ['albert','james','kebo']  # Store multiple students in a class
information = ['albert',18,1.83]  # Store one person's information
# Store information for multiple people
informations = [['albert',18,1.83],['james',34,2.03],['kebo',40,1.98]]

6. Tuple (tuple)

Another data type similar to list is tuple, which we call a tuple. It’s used very much like a list, except that a list can be modified while a tuple cannot—it can only be viewed. It’s defined with parentheses, with multiple elements separated by commas, where each element can be of any data type. Just change the square brackets in the code above to parentheses—note that these must be English parentheses (). A tuple is an immutable type

7. Dictionary (dict)

In the code above that stores multiple people’s information, you can probably tell that I’m storing each person’s name, age and height, but it isn’t explicit, and we can’t rely on guessing. The way to solve this is to state it clearly when defining it, and this is where dictionaries come in. How it’s defined: inside curly braces, multiple elements separated by commas, each element in the form key: value. Note that dictionary keys can only be immutable types; we generally use strings. A dictionary is a mutable type.

information = {'name':'albert','age':18,'height':1.83}  # Store one person's information
informations = [
        {'name':'albert','age':18,'height':1.83},
        {'name':'james','age':34,'height':2.03},
        {'name':'kebo','age':40,'height':1.98}
]  # Store information for multiple people

8. Set (set)

There are more than 400 players in the NBA. If we want to store these 400-plus players without caring about order, there certainly can’t be duplicates—each player counts only once. The lists and tuples above allow duplicates. All we need to know is that “Albert” is definitely not among them. How it’s defined: inside curly braces, multiple elements separated by commas; each element can be of any data type, but there can be no duplicates. A set is a mutable type.

NBA_players = {'James', 'Kobe', 'Jordan', }

9. Boolean (Bool)

There are many players in the NBA, but some people may never get to play in the NBA in their whole lives. If we want to determine whether a person is an NBA player, we can use the Boolean type. It has only two values, True and False.

That’s all we’ll cover about basic data types for now; later chapters will explain how to use these data types in more detail.

10. Supplement (Very Important)

Here’s a small supplement about naming variables. It’s simple, but very important.

I recommend using “Hungarian notation”, which is also the most standard way of naming variables at work. Sometimes, when you look at someone’s code, you can roughly judge their skill level just from the variable names they write.

In short, Hungarian notation means putting an abbreviation of the variable’s “type” at the very beginning of the variable name. The key is that the variable “type” here refers to types related to your code’s business logic. For example, suppose your code has two variables, students and teachers, representing a set used to store students and a list used to store teachers respectively. With “Hungarian notation”, these two names can be rewritten like this:

students -> set_students

teachers -> list_teachers

In many cases, using “Hungarian notation” is a good idea, because it can improve your code’s readability, especially when there are many variables and the same type appears many times. Just be careful not to overuse it.

VI. Comments

As your study deepens, before long you’ll be able to write complex code of thousands or even tens of thousands of lines. Some code takes you a long time to write, and when you go back to look at it a few days later, you find you can’t understand it—this is perfectly normal. In addition, you’ll find at work that a project is usually done by several or even dozens of developers together. You need to call code written by others, and others need to use yours. If the code has no comments, even you won’t understand it, let alone others—and that’s how you get beaten up. So to avoid such embarrassing situations, you must make your code more readable.

Anything after the # sign is not output when the code runs

There are three kinds of code comments:

  1. Single-line comments: the comment occupies its own line, starts with #, followed by a space, and then the content of the comment

a = 1

# a += 1 This is how the # comment is used

  1. Inline comments: at the end of the code, type two spaces, then a #, then another space, followed by the content of the comment.

a += 1 # Inline comment

  1. Multi-line comments: you can write the comment content between three pairs of double quotes """注释内容 """, or between three pairs of single quotes. Obviously, multi-line comments can span multiple lines. When your comment is fairly long, writing a very long single line is hard to read, so in that case we recommend multi-line comments.

"""

hello, world!

"""

Principles for code comments:

  • You don’t need to comment everything; just add comments to the parts you think are important or hard to understand
  • Comments can be in Chinese or English, but don’t use pinyin, and don’t mix Chinese and English

Note (very important):

You may all think you can write comments now, but in fact at work, apart from some companies with high standards, very few people write comments properly. Writing comments, and writing them properly, is the simplest indicator of a programmer’s coding literacy.

VII. File Header

Note: since it’s a file header, it naturally goes at the top of the file. This is one of the details of development standards

#!/usr/bin/env python  # Specify the interpreter
# -*- coding: utf-8 -*-  # Specify the file's character encoding

Writing this ourselves every time we write code is a bit of a waste of time. We can configure it in PyCharm first, and from then on the file header will be added automatically every time we create a new file. macOS users can click in the top-left corner of PyCharm and follow the order PyCharm—Preferences—Editor—File and Code Templates—Python Script to find a blank area, then paste the following code into it. Windows users can follow File—Settings—Editor—File and Code Templates—Python Script and do the same. Note: you can change the author line to your own name.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : ${DATE} ${TIME}
# @Author  : Albert  
# @File    : ${NAME}.py

VIII. Implementing User Interaction

Only at this point does the article formally get into the content of this chapter’s title; everything before was groundwork

A long time ago, when we went to the bank to withdraw money, a bank clerk had to wait for us to give him our account number and password, then he would verify them, and after that succeeded, we would tell him the amount to withdraw. Proud modern people provide customers with an ATM (which is a computer) and let the ATM interact with users, replacing human labor. But machines are dumb; we have to write programs for them to run. This requires our programming language to have a mechanism that can interact with users and receive the data they input.

User interaction means the program waits for the user to input data before executing the next step of the program. We use input to do this.

name = input('请输入姓名:')  # I assign the input content to the variable name
print(‘你好’ + name)  # After the user finishes entering their name, it prints 你好XXX ("Hello XXX")

Differences between Python 2 and Python 3

  • In python3, input: whatever value the user enters is stored as a string
  • In python2, input: whatever type the user enters is stored as that type
  • raw_input in Python 2: equivalent to input in python3

Note: when a number needs to be input, considering that we’ll use the number in calculations, and Python 3’s input converts it to str by default, we need to convert the user’s input data into int

age = input('请输入年龄')
age = int(age)  # Convert the string age into an int age for calculation