初学者如何准备开始学习Python-1 (中/英原版)

0.1 Python 2 or Python 3 (Python 2 与 Python 3 的区别) (序一)

The print statement has become the print function. What this means is that this line in Python 2: print "hello world"

is as follows in Python 3: print("hello world”)

The raw_input function has also changed to input, so instead of: raw_input('What is your name?’)

you will see: input('What is your name?’)

The only other significant change is how Python handles various character sets.

You might find that your job still wants to use Python 2. We believe that going from Python 3 to Python 2 is pretty easy - so don't worry too much about the version of Python that you learn when you are first starting out.

主要区别在一些命令的拼写上, 不过不需要太过于担心, 版本不是什么大问题.

1.1 Why Program (为什么要编程)

Maker of technology.

Being a user to Being a programmer.

Different side of Applications (Back/ Front).

Computers are good at counting stuff or calculating numbers, but humans are not good at that. 

通过计算机来实现大量计算,或者是对人类繁琐的事情.

1.2 Hardware Overview (硬件简介)

Input and Output Devices: Access/display outside/inside the world/computer such as mouse, keyboard, screen, etc.

Software

  • Central Processing Unit: Millions Circuit.
  • Main Memory: Program file loaded into here.
  • Secondary Memory: Permanent program file. (disk)

Using Input Devices to write a code in Secondary Memory, run the script in Main Memory, calculate in Central Processing Unit, return the result via Output Devices. That is how these components works.

输入输出设备/CPU/内存/磁盘

用户在磁盘上编写脚本, 运行时由内存提取, 并提供给CPU进行计算, 计算结果通过输出设备给用户.

1.3 Introduction of Python (Python 简介)

  • Weird Languages.
  • Python was named for was Monty Python's Flying Circus.
  • Py is powerful and useful.
  • Python is a powerhouse language. It is by far the most popular programming language for data science.
  • You can do many of the things you are used to doing in other programming languages but with Python you can do it with less code.
  • If you want to learn to program, it’s also a great starter language because of the huge global community and wealth of documentation.
  • Python is useful for many situations, including data science, AI and machine learning, web development, and IoT devices like the Raspberry Pi.
  • Large organisations that use Python heavily include IBM, Wikipedia, Google, Yahoo!, CERN, NASA, Facebook, Amazon, Instagram, Spotify, and Reddit. 
  • Python is a high-level general-purpose programming language that can be applied to many different classes of problems.
  • It has a large, standard library that provides tools suited to many different tasks, including but not limited to databases, automation, web scraping, text processing, image processing, machine learning, and data analytics.
  • For data science, you can use Python's scientific computing libraries such as Pandas, NumPy, SciPy, and Matplotlib.
  • For artificial intelligence, it has TensorFlow, PyTorch, Keras, and Scikit-learn.
  • Python can also be used for Natural Language Processing (NLP) using the Natural Language Toolkit (NLTK).
  • Another great selling point is the Python community, which has a well documented history of paving the way for diversity and inclusion efforts in the tech industry as a whole.

Don’t feel frustrated when something wrong (Syntax) in Python. People make mistakes. 

Python非常的强大且有用, 但是记住一点, 语法错误是学习的必经之路, 不需要为此感到难受.

0.2 Installing Python (安装Python)

(序二)

Install Python and text editor on computer.

Atom, IDE, PyCharm, etc.

I recommend that Atom is good for all systems.

Help your self!

Try to print “hello world” in Terminal or Command line.

1.4 Writing Paragraph of Code (尝试去编写一段代码)

Type Python statement in Python.

Name x using value 1.

>>> x = 1

Show the value of x

>>> print(x)
1

Add new value 1, which becomes 2.

>>> x = x + 1
>>> print(x)
>>> 2

Vocabulary (Reserved Words): False, class, if, return, for, assert, while, pass, etc.

You cannot use Reserved Words as a variable. These words have a specific meaning in Python.

保留字: Python会保留一些词, 这些词在Python中有特殊作用.

Sentences or Lines

x = 2 #Assignment statement
x = x + 2 #Assignment with expression
print(x) #Print function

x: Variable 

=: Operator

2: Constant

print (): Function 

Interactive: Directly using Python one line at a time and it responds. (通过Python进行交互式编写)

Script: Writing in a file using a text editor. (使用第三方编辑器进行编写)

Sequential Steps (顺序语句): When a program is running, it flows from one step to the next.

x = 2
print(x)
x = x + 2
print(x)

Conditional Steps (条件语句): It depends on the conditions to execute the statements.

x = 5
if x < 10:
    print('Smaller')
if x > 20:
    print('Bigger')
print('Finis')

Repeated Steps (重复语句): Loops have iteration variables that change each time through a loop.

n = 5
while n > 0:
    print(n)
    n = n -1
print('done!')

2.1 Expressions Part 1 (表达式)

Constants: Fixed values such as numbers, letters and strings. Because their value does not change. 

Numeric constants are as you expect: 

>>> print(123)
>>> 123

String constants use single quotes (‘) or double quotes (“)

>>> print('Hello world')
>>> Hello world

Variables (变量): A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “name”. Programmer can choose the names of variable except Reserved Words. Also the variable can be change in a later statement.

>>> x = 5
>>> y = 10
>>> x = 100

Choose a sensible variable name for human beings! 

变量的选择将会直接影响一个程序, 以人的角度与习惯去选择变量. 

2.2 Expressions Part 2 (表达式)

Numeric Expressions: we use “computer-speak” to express the classic math operations.

+ Addition

- Subtraction

* Multiplication

/ Division

** Power (倍数)

% Remainder (余数)

>>> x = 1 + 2 * 3 / 4

Parenthesis > Power > Multiplication/Division > Addition/Sub > Left to Right.

Type: Python knows the difference between an integer number and a string.

>>>  x = 1 + 1
>>> x = 'hello ' + 'world'
>>> print(x)
>>> hello world

Notice that you cannot add 1 to a string.

Using type() to ask Python what is the type is.

Integers: are whole numbers: 1, 2, 10, 999, -8

Floating Point Numbers: have decimal parts: 1.5, 2.8, 100.12, -12.85

Integer division produces a floating point result in Python 3, in Python 2, it only gives a whole number.

String Conversions: you can also use int() and float to convert between strings and integers.

You will get an error if the string does not contain numeric characters.

>>> x = '123'
>>> type(x)
<class 'str'>
>>> x = int(x)
>>> print( x + 1 )
124

User Input: We can instruct Python to pause and read data from user using the input() function. The input() returns a string whatever you typed in.

name = input('Who are you?')
print('Welcome', name)

Who are you?
>>> Cooper
Welcome Cooper

2.3 Expressions Part 3 (表达式)

Comment in Python:

Anything after a # is ignored by Python.

Why comment?

  • Describe what is going to happen.
  • Document who wrote the code or other information.
  • Turn of a line of code

Documentations are very important.

Try using Python: Calculate 35Hours, Rate 2.75 to gross pay. Using input() and float().

Try using Python: Covert elevator floors (UK - US). Ground Floor(UK) = 1 Floor(US).

3.1 Conditional Statements (条件语句)

Make a choice based on present conditions. It helps computer to be more intelligence.

基于当前的一个情况去进行选择.

Conditional Steps: 

x = 5
if x < 10:
    print('Smaller')
if x > 20:
    print('Bigger')
print('Done')

Comparison Operators (比较符): to compare the variables and will not affect the values.

Boolean expressions ask a question and produce a Yes or No result which we use to control program flow. It also using comparison expressions evaluate to True / False or Yes / No.

< Less than

<= Less than or Equal to

= = Equal to

>= Greater than or Equal to

> Greater than

!= Not equal

Tips: “=” is used for assignment.

Tips: Space in Python is important.

Tips: 4 Space or Tab may not equivalent in Python.

Tips: De-indenting and indenting.

等于号用作变量赋值. 空格键和Tab键是不一样的, 如果要进行缩紧, 建议手敲四下空格.

Two-way Decisions (else): sometimes we want to do one thing if a logical expression is true and something else if the expression is false.

x = 4
if x > 2:
    print('Bigger')
else:
    print('Smaller') 
print('Done')

3.2 More Conditional Statements (更多的条件语句)

Multi-way (elif): if if is false, elif still make choices.

if x < 2:
    print('Below 2')
elif x < 20:
    print('Below 20')
else:
    print('Something else')

The try / expect Structure (try语句): preventing errors or traceback in advance.

If the code in the TRY works - the EXCEPT is skipped.

If the code in the TRY fails - it jumps to the EXCEPT.

astr = 'Bob'
try:
    istr = int(astr)
except:
    istr = -1
print('Done', istr)

其作用是为了防止Python异常终止, 导致后续程序无法执行.

Try的内容执行成功Execpt内的内容不执行.

Try的内容报错后执行Execpt内的内容.

Exercise: pay rate is 10.50, 40 hours and below 40 hours is normal rate, if over 40 hours that every single hour is 1.5 times rate. Use python to calculate 45 hours of the pay.

4.1 Using Functions (使用函数)

Forth pattern of code. Sequential, conditional, iterations, and store and reuse.

Stored and Reuse Steps: repeat itself.

def thing():
    print('Hello')
    print('Fun')

>>> thing()
Hello
Fun
>>> print('Zip')
Zip
>>> thing()
Hello
Fun

If a function appears in code line, Python will run the function first, then return a result to the code line, maybe a value. Then, code continues to running use the result returned by the function. 

  • print() :输出
  • input() :输入
  • str(): 转换为字符串
  • int(): 转换为整数
  • float(): 转换为浮点数(小数)
  • len(): 返回字符串长度
  • .lower(): 转换小写
  • .upper(): 转换大写
>>> x = ABC
>>> y = x.lower()
>>> print(y)
abc

4.2 Building Functions (创建函数)

  • We create a new function using  the def keyword followed by optional parameters in parentheses.
  • We indent the body of the function.
  • This defines the function but does not execute the body of the function.
  • 用def关键词来定义一个函数和他的选项.
  • 函数本身内容需要进行缩进.
  • 函数在未引用的情况下是不会做任何操作的.

Arguments (参数)

  • An argument is a value we pass into the function as its input when we call the function.
  • We use arguments so we can direct the function to do different kinds of work when we call it at different times. 
  • We put the arguments in parentheses after the name of the function.
  • 参数是指在使用函数时获取的用户输入的内容.
  • 我们可以通过参数来实现函数的多个功能.
  • 我们将参数放入函数的括号中.

Parameters (传入参数): A parameter is a variable which we use in the function definition.

def greet(lang):
    if lang == 'es':
        print('Hola')
    elif lang == 'fr':
        print('Bonjour')
    elif lang == 'en':
        print('Hello')

>>> greet('en')
Hello
>>>greet('fr')
Bonjour

Return Value (返回值): A ‘fruitful’ function is one that produces a result or return a value.

It ends the function election and “send back” the result of the function.

我们称一种函数为“富饶的”函数因为它最终会返回一个值.

def greet():
    return "Hello"
print(greet(), "Cooper")

Multiple parameter / argument (多参数): we can define more than one parameter in the function definition. And we can match the number and order of arguments and parameters.

函数可以定义多个参数, 用户按照顺序进行传参.

Using function to achieve last Exercise!

5.1 Loops and Iteration (循环与迭代)

Repeated Steps: loops have iteration variables that change each time through a loop. Often these iteration variables go through a sequence of numbers.

循环通常会有一个变量作为开始与结束, 而这个变量通常会是一个区间的数字.

We need to make sure that the iteration variables correct, and it will change every time, otherwise, the loop will run forever. An Infinite Loop

我们需要确保迭代变量内容与逻辑正确, 避免死循环/无限循环的情况发生. 

n = 5
while n > 0:
    print(n)
    n = n -1
print('Blastoff')
print(n)

Break Out of a Loop (退出循环): the break statement ends the current loop and jumps to the statement immediately following the loop.

while True:
    line = input('>')
    if line == 'done':
        break
    print(line)
print('Done!')

Finishing an Iteration with Continue (使用Continue去完成迭代): The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration.

while True:
    line = input('>')
    if line[0] == '£':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')

5.2 Definite Loops (定义循环)

A simple Definite Loop (简单的定义循环): Define loops (for) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set.

for i in [5, 4, 3, 2, 1]:
    print(i)

For 循环有精确的迭代变量, 而这个迭代变量可以是一个列表或一个数组等内容.

5.3 Finding the Largest Value (通过循环寻找最大值)

Making “Smart” Loops

largest_so_far = -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74 ,15]:
    if largest_so_far > the_num:
        largest_so_far = the_num
    print(largest_so_far, the_num)

print('After', largest_so_far)

Computer does the different way like human beings. Computer is more complex than human beings however it more efficient than human beings. 

计算机与人在处理上是不一样的, 计算机的处理会更加的复杂与高效.

5.4 Loop Idioms (循环语法)

do Count/do Sum/do Average/do Filtering/using Boolean Variable/Find Smallest

通过使用循环可以去实现很多内容, 比如计数/求和/求均/条件等.

None: Using None to indicate a value didn’t exist yet. 

if var is None :

then…

Is None is a stronger equality than double equals.

Double equals (= =) is mathematically equal to with potential conversion. 

is None 是一个强相等, 其必须在格式上与形式上完全一样.

而双等于则是数学意义上的相等.

更多内容请访问: https://www.c-kli.com/index.php/2020/05/15/umc-101-getting-started-with-python/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值