python 入门程序

This article is for people who already have experience in programming and want to learn Python quickly.

本文适用于已经有编程经验并希望快速学习Python的人们。

I created this resource out of frustration when I couldn't find an online course or any other resource that taught Python to programmers who already knew other programming languages.

当我找不到在线课程或其他任何可以向已经了解其他编程语言的程序员教授Python的资源时,我无奈地创建了该资源。

In this course, I will be covering all the basics of Python (in-depth lessons will be added later on) so that you can get started with the language very quickly.

在本课程中,我将介绍Python的所有基础知识(稍后将添加深入的课程),以便您可以快速入门该语言。

目录 (Table of contents)

  • Setting up the environment搭建环境
  • Hello World你好,世界
  • Strings弦乐
  • Numbers号码
  • Float浮动
  • Bool布尔
  • List清单
  • Tuple元组
  • Sets套装
  • Dictionary字典
  • if..else如果别的
  • Loops循环
  • Functions功能
  • Classes班级
  • Modules模组
  • Truthy and Falsy values真实和虚假的价值观
  • Exception handling异常处理

搭建环境 (Setting up the environment)

To get started, install Python 3. I recommend using VSCode as your editor. It has lots of extensions to configure so that you can setup your environment in just a few minutes.

首先,安装Python3。我建议使用VSCode作为编辑器。 它具有许多可配置的扩展,因此您可以在几分钟内设置您的环境。

你好,世界 (Hello world)

print("Hello world")

If you already know programming basics, you'll probably know how to run this program :P. Save the program with the .py extension. Then run python hello.py or python3 hello.py.

如果您已经了解编程基础知识,则可能会知道如何运行此程序:P。 使用.py扩展名保存程序。 然后运行python hello.pypython3 hello.py

In this whole tutorial, we will follow python3. python2 will be discontinued by 2020. So I think it’s good to go with the latest version.

在整个教程中,我们将遵循python3python2将于2020年停产。因此,我认为最好使用最新版本。

变量和数据类型 (Variables and data types)

Variables can contain letters, numbers, and underscores.

变量可以包含字母,数字和下划线。

弦乐 (Strings)

# This is comment in Python
msg_from_computer = "Hello" # String
another_msg ='Hello in single quote' # This is also a String.print(msg_from_computer + " World..!")# Type will return the data type.
print(type(msg_from_computer)) # <type 'str'>. We will see the explanation of this later.

号码 (Numbers)

2
2 * 3
2 ** 7
(2 + 3) * 4

浮点数 (Floats)

2.70.1 + 0.2 # 0.3
2 * 0.1 # 0.2

Be careful in Concatenation:

串联时要小心:

count = 5print("I need" + count + "chocolates") # This line will throw error. As count is a integer, you have to type cast it.print("I need" + str(count) + "chocolates") # This will work

布尔 (Bool)

True # First letter is capsFalsebool("some value") # Returns Truebool("") # Returns Falsebool(1) # Returns True

清单 (List)

Lists are basically like arrays. In the Python world, they call them List. And they are ordered.

列表基本上就像数组。 在Python世界中,他们称它们为List 。 他们被命令。

numbers = ["one", "two", "three"]numbers[0] # onenumbers[-1] # three. This is awesome. If we pass negative value Python will start from the end.numbers[-2] # twolen(numbers) # 3. It just returns the lengthnumbers.append("four") # Append will add the element to the last. ["one", "two", "three", "four"]numbers.insert(1, "wrong_one") # Insert will insert the particular value to the appropiate position. ["one", "wrong_one", "two", "three", "four"]# Deleting a value is somewhat weird
del numbers[1] # Will delete the value in the appropiate position. "one", "two", "three", "four"]# Pop will help you to remove the last element of an array
popped_element = numbers.pop()print(popped_element) # four
print(numbers) # ["one", "two", "three"]# Remove elements by value
numbers.remove("two") # ["one", "three"]. This will remove only the first occurence of an array.# Sorting
alpha = ["z", "c", "a"]
alpha.sort()
print(alpha) # ["a", "c", "z"] Sorting is permanent. now `alpha` is sorted permanentlyalpha.sort(reverse=True)
print(alpha) #["z", "c" , "a"] Reverse sorting.alpha = ["z", "c", "a"]
print(sorted(alpha)) # ["a", "c", "z"] This will just return the sorted array. It wont save the sorted array to the variable itself.print(alpha) # ["z", "c", "a"] As you can see, it's not sorted# Reversing an array
nums = [10, 1, 5]
nums.reverse()
print(nums) # [5, 1, 10] It just reverses an array. It means it reads from last. It's not sorting it. It's just changing the chronological order.# Slicing elements
alpha = ['a', 'b', 'c', 'd', 'e']
alpha[1:3] # ['b', 'c']. The first element is the starting index. And Python stops in the item before the second index.
alpha[2:5] # ['c', 'd', 'e']alpha[:4] # [ 'a', 'b', 'c', 'd'] In this case, the first index is not present, so Python startes from the beginning.alpha[:3] # ['a', 'b', 'c']alpha[3:] # ['d', 'e'] In this case, last index is not present. So it travels till the end of the list.alpha[:] # ['a', 'b', 'c', 'd', 'e'] There is no starting or ending index. So you know what happens. And this helps you in copying the entire array. I think I don't have to explain that if you copy the array, then any changes in the original array won't affect the copied array.another_alpha = alpha # This is not copying the array. Any changes in alpha will affect another_alpha too.

元组 (Tuples)

Tuples are just like lists but they are immutable. This means you can’t add or update them. You can just read elements. And remember, like lists, Tuples are also sequential.

元组就像列表一样,但是它们是不可变的。 这意味着您无法添加或更新它们。 您可以阅读元素。 记住,像列表一样,元组也是顺序的。

nums = (1, 2, 3)print(nums) # (1, 2, 3)print(nums[0]) # 1print(len(nums)) # 3empty_tuple = () # empty tuple. Length is zero.num = (1, ) # Note the trailing comma. When defining a single element in the tuple, consider adding a trailing comma.num = (1)
print(type(num)) # <type 'int'> It won't return a tuple. Because there is no trailing comma.# Creating a new tuple from the existing tuple
nums = (1, 2, 3)
char = ('a', )
new_tuple = nums + char
print(new_tuple) # (1, 2, 3, 'a')

套装 (Sets)

Sets are unordered collections with no duplicate elements.

集是无序集合,没有重复的元素。

alpha = {'a', 'b', 'c', 'a'}print(alpha) # set(['a', 'c', 'b']) As you can see, duplicates are removed in sets. And also the output is not ordered.# Accessing items in set
# You can't access by index because Sets are unordered. You can access it only by loop. Don't worry about the for loop, we will get that in-depth in the following section.
for ele in alpha:print(ele)# To add element into the set
alpha.add('s')# add can be used to insert only one element. If you want multiple elements, then update will be handy
alpha.update(['a', 'x', 'z']) # set(['a', 'c', 'b', 'x', 'z']) Remember duplicated are removed.# Length of the alpha
len(alpha) # 5# Remove the element from the set
alpha.remove('a')
alpha.discard('a') # It's safer to use discard than remove. Discard will never throw an error even if the element is not present in the set but remove will do.

辞典 (Dictionaries)

Dictionaries are key-value maps in Python. They're unordered.

字典是Python中的键值映射。 他们是无序的。

user = {'id': 1, 'name': 'John wick', 'email': 'john@gmail.com'}user['id'] # 1
user['name'] # John wick# Length of the dict
len(user) # 3# Add new key-value pair
user['age'] = 35# To get all the keys
keys = user.keys() # ['id', 'name', 'email', 'age']. This will return a list.# To get all the values
values = user.values() # [1, 'John wick', 'john@gmail.com']# To delete a key
del user['age']# Example of nested dict.
user = {'id': 1,'name': 'John wick','cars': ['audi', 'bmw', 'tesla'],'projects': [{'id': 10,'name': 'Project 1'},{'id': 11,'name': 'Project 2'}]
}# We will see, how to loop through the dict in for loop section.

如果别的 (if..else)

You likely already know how the if..else statement works. But let's see an example here:

您可能已经知道if..else语句如何工作。 但是让我们在这里看一个例子:

a = 5
b = 10# See for the indentation. Indentations are very important in Python. Python will throw error if indentations are proper.
if a == 5:print('Awesome')# and is equivalent to &&
if a == 5 and b == 10:print('A is five and b is ten')# if else statement. This is same as most of the languages.
if a == 5:print('A is five')
elif a == 6:print('A is six')
elif a == 7:print('A is seven')
else:print('A is some number')# or is equivalent to ||
if a < 6 or a == 10:print('A should be less than 6 or should be equal to ten')# not is equivalent to !
if not a == 10:print('A is not equal to 10')# This is the short-hand notation of if statement.
if a == 5: print('A is five')# Short-hand for if-else statement.
print('A is five') if a == 5 else print('A is not five')

循环 (Loops)

Python has two types of loops:

Python有两种类型的循环:

  1. For对于
  2. While而

while循环 (while loops)

# The following while print till 5. Remember the indentation.
i = 0
while i <= 5:print(i)i += 1# Using brake or continue in while loop
i = 0
while i <= 5:print(i)i += 1if i == 2:break # You can try using continue here# Here comes the interesting part. While loop has else part. Else part will execute once the entire loop is completed.
i = 10
while i <= 15:print(i)i += 1
else:print('Completed')# Output
10
11
12
13
14
15
Completed# But if you are using break in the loop, then Python will break out of the entire loop and it won't execute else part.
i = 10
while i <= 15:print(i)i += 1if i == 13:break
else:print('Completed')# Output
10
11
12

对于循环 (For loops)

# For loops like for(i=0; i<5; i++) are not mostly used in Python. Instead, Python insists on iterating over itemsarr = ['a', 'b', 'c', 'd', 'e']
for ele in arr: # Prints every element in an arrayprint(ele)word = "python"
for char in word: # Prints every char in the wordprint(char)# You can use break, continue and else part in for-loop also.# When talking about for loops, I noticed that most resources have also mentioned about range() function. (We will deal with functions later part of this article.)# range() function will generates a sequence of numbers.# range(start, stop, step)
# start - optional, the starting number. Default is 0. This number is included in the sequence
# stop - mandatory, the ending number. This number is excluded in the sequence
# step - optional, increments by. Default is 1.range(3) # This code generates a sequences from 0 to 2.
range(1, 4) # This code generates a sequence from 1 to 3.
range(1, 8, 2) # This code generates a sequence with 1, 3, 5, 7for ele in range(3): # Prints from 0 to 2. print(ele)# In the below example, you can see I have used range to iterate through an array with index.
for index in range(0, len(arr)):print(arr[index])dict = {'name': 'John wick'}# You can iterate through a dictionary. items() will return both keys and values. You can also use keys() and values() if needed.
for key, value in dict.items():print(key + " is " + value)# You can also use a built-in function enumerate(). enumurate() will return a tuple with index. It is mostly used to add a counter to the iterable objects in Python.
for index, value in enumerate(arr):print(value + " is present in " + str(index))

功能 (Functions)

def prints_hello_world():print('Hello world from Python')prints_hello_world()# Return statement
def prints_something(something):return something + ' from Python'print(prints_something('Hello world'))# If you pass wrong number of arguments like two or three arguments to this function then Python will throw an error.
print(prints_something())# Default parameter. I think its common in most languages now.
def prints_something(something = 'Hello world'):print(something + ' from Python')# keyword arguments. You can pass explicitly which parameter should be matched. In this way, you don't have to send the arguments in order just explicitly mention the parameter name.
def movie_info(title, director_name, ratings):print(title + " - " + director_name + " - " + ratings)movie_info(ratings='9/10', director_name='David Fincher', title='Fight Club')# Arbitrary number of arguments
# Sometimes, you dont know how many arguments are passed. In that case, you have ask Python to accept as many arguments as possible.def languages(*names):print(names) # ('Python', 'Ruby', 'JavaScript', 'Go'). This is a tuple.return 'You have mentioned '+ str(len(names))+ ' languages'print(languages('Python', 'Ruby', 'JavaScript', 'Go')) # You have mentioned 4 languagesdef languages(fav_language, *names):print(names) # ('Ruby', 'JavaScript', 'Go')return 'My favorite language is ' + fav_language+ '. And Im planning to learn other '+ str(len(names))+ ' languages too'print(languages('Python', 'Ruby', 'JavaScript', 'Go')) # My favorite language is Python. And Im planning to learn other 3 languages too# Arbitrary keyword arguments
# These types of arguments are useful when you don't know what kind of parameters are passed. In the previous case, it's useful when you don't know how many number of parameters are passed but in this case, you don't know what type of information will be passed.def user_info(**info):print(info) # {'id': 1, 'name': 'Srebalaji', 'fav_language': ['Python', 'Ruby']} This is a dictionary# Arbitrary keyword args will always expect to mention the parameters explicitly
user_info(id=1, name='Srebalaji', fav_language=['Python', 'Ruby'])# The below code will throw error. There is no keyword arguments.
user_info(1, 'Srebalaji')def user_info(id, name, **info):print(info) # {'fav_language': ['Python', 'Ruby'], 'twitter_handle': '@srebalaji'}user_info(1, 'Srebalaji', fav_language=['Python', 'Ruby'], twitter_handle='@srebalaji')

班级 (Classes)

# Python is general purpose and also object oriented language.# It's a convention that the class name starts with caps. But Python doesn't throw any error if you are not following it.
class Animal():# This is the constructor.# As you can see in every method of the class I have passed 'self' as the first parameter. The first parameter is always expected to be the current instance of the class and it is mandatory to pass the instance in the first parameter. And you can name that variable whatever you like.def __init__(self, name): self.name = namedef eat(self):print(self.name +' eats')def sleep(self):print(self.name+' sleeps')# Initiating a class
dog = Animal('harry')
dog.eat()print(dog.name) # As you can see, 'name' attribute is also avaiable in public. # It can even be modified.
dog.name = 'Rosie'
print(dog.name) # 'Rosie'# Technically there is no way to make private attrbiutes in Python. But there are some techniques Python devs are using it. I will try to list out some.# Protected attributes.
# These attributes can only be accessed within the class and also by the sub-class.class Person():# You can see that I have used different name for the first parameter.def __init__(my_instance, name):# 'name' attribute is protected.my_instance._name = namedef reads(my_instance):print(my_instance._name + ' reads')def writes(my_object):print(my_object._name + ' writes')person1 = Person('Ram')person1.reads()# But the worst part is that instance of the class can still access and change it :Pprint(person1._name) # 'Ram'person1._name = 'I can still change.'
print(person1._name) # I can still change# Protected can useful sometimes. Let's see how private attributes works. That can be a life saver sometimes.class Person():def __init__(self, name):# 'name' attribute is private.self.__name = namedef reads(self):print(self.__name + ' reads')def writes(self):print(self.__name + ' writes')# This is a private method. This can't be accessed outside the class.def __some_helper_method():print('Some helper method.')person1 = Person('Ram')
person1.reads() # Ram readsprint(person1.name) # Will throw an error. 'Person' object has no attribute 'name'print(person1.__name) # Will throw an error. 'Person' object has no attribute '__name'# Private attributes can only be accessed within the class. So it's safe. But still there is a catch :Pprint(person1._Person__name) # Ram.# You can even change the value
person1._Person__name = 'Hari'print(person1._Person__name) # Hari.# But every dev know that accessing and modifying the private attributes is a bad practice. And Python doesn't really have a clear restriction to avoid it. So you got to trust your peers on this.# Inheritanceclass Animal():def __init__(self, name):self.name = namedef eat(self):print('Animal eats')def sleep(self):print('Animal sleeps')# Dog is a sub class of Animal
class Dog(Animal):def __init__(self, name):self.name = namedef eat(self):print('Dog eats')dog1 = Dog('harry')
dog1.eat() # Dog eats
dog1.sleep() # Animal sleeps

模组 (Modules)

# Modules helps us to organise code in Python. You can split code in different files and in folders and can access them when you wanted.# Consider the below file. It has two functions.
# calculations.pydef add(a, b):return a + bdef substract(a, b):return a - b# consider another file which we consider as a main file.
# main.py
import calculationscalculations.add(5, 10) # 15
calculations.substract(10, 3) # 7# In the above example, you have imported the file and have accessed the functions in that.# There are other ways of importing.# You can change the method name if you want
import calculations as calc
calc.add(5, 10) # 15# You can import specific functions you need.
# You can access the function directly. You don't want to mention the module.
from calculations import add
add(5, 10) # 15# You can also import multiple functions
from calculations import add, multiple, divide# You can import all the functions
from calculations import *
add(10, 15)
multiple(4, 5)
divide(10, 3)# These will work for classes and variables too.

真实和虚假的价值观 (Truthy and Falsy values)

# According to Python docs, any object can be tested truthy or falsy.# Below are the Truthy values
True
2 # Any numeric values other than 0
[1] # non-empty list
{'a': 1} # non-empty dict
'a' # non-empty string
{'a'} # non-empty Set# Below are the Falsy values
False
None
0
0.0
[] # empty list
{} # empty dict
() # empty tuple
"" # empty string
range(0) # empty set# You can evaluate any object to bool using
bool(any_object) # returns True or False

异常处理 (Exception handling)

# The code which can raise exceptions can be wrapped in 'try' statement. 'except' will handle that exception.
try:some_error_raised
except:print('Exception handled')# Every exception in Python will inherit from 'exception' class. # In the below example, you can see that the 'NameError' is the exception class derived from the main 'Exception' class.
try:some_error_raised
except Exception as e:print('Exception raised')print(e.__class__) # <class 'NameError'># 'else' block will execute if the code in the 'try' block has raised no exception. This will be useful in many situations.try:some_error_raised
except:print('Exception handled')
else:print('No error raised. You can resume your operation here') # this code will execute if no error is raised in the 'try' block# final block
# Code in 'finally' block will execute no matter whether the exception is raised or not.
try:some_error_raised
except Exception as e:print('Exception raised')
else:print('This will execute if no error is raised in try')
finally:print('This code will run whether the code has error or not.')# Raise your own exception. You can also create your own exception class inherited from Exception class.
try:raise ZeroDivisionError # Python built-in exception class
except Exception as e:print(e.__class__) # <class 'ZeroDivisionError'># Catch a specific exception.
try:raise ZeroDivisionError # Python built-in exception class
except TypeError as e:print('Only type error exception is captured')
except ZeroDivisionError as e:print('Only zero division exception is captured')
except Exception as e:print('Other execeptions')

Thank you for reading :)

谢谢您的阅读:)

Originally posted in this Github repo: Python crash course

最初发布在此Github存储库中: Python崩溃课程

翻译自: https://www.freecodecamp.org/news/python-crash-course/

python 入门程序

python 入门程序_非Python程序员的Python速成课程-如何快速入门相关推荐

  1. Python灰帽子_黑客与逆向工程师的Python编程之道

    收藏自用 链接:Python灰帽子_黑客与逆向工程师的Python编程之道

  2. python新手程序_推荐:一个适合于Python新手的入门练手项目

    随着人工智能的兴起,国内掀起了一股Python学习热潮,入门级编程语言,大多选择Python,有经验的程序员,也开始学习Python,正所谓是人生苦短,我用Python 有个Python入门练手项目, ...

  3. 知道经纬度用python画路线图_神级程序员教你用Python如何画一个中国地图!(好好玩)...

    为什么是Python 先来聊聊为什么做数据分析一定要用 Python 或 R 语言.编程语言这么多种, Java , PHP 都很成熟,但是为什么在最近热火的数据分析领域,很多人选择用 Python ...

  4. python zope 工作流_使用C语言来扩展Python程序和Zope服务器的教程

    有几个原因使您可能想用 C 扩展 Zope.最可能的是您有一个已能帮您做些事的现成的 C 库,但是您对把它转换成 Python 却不感兴趣.此外,由于 Python 是解释性语言,所以任何被大量调用的 ...

  5. python eel 多线程_利用Eel使JavaScript调用Python程序

    利用Eel使JavaScript调用Python程序 Eel简介 Eel是一个轻量的python桌面GUI开发第三方库, 它使用HTML/JS作为界面开发语言, 但是能够访问所有的python功能, ...

  6. php调用python绘图程序_如何在matlab中调用python程序

    现在python很火,很多代码都是python写的,如果你和我一样,习惯了使用matlab,还想在matlab中调用Python的代码,应该怎么办呢?其中一条思路:首先在matlab中调用系统脚本命令 ...

  7. python四则运算程序_四则运算小程序(Python)

    二. 题目要求 写一个能自动生成小学四则运算题目的程序,然后在此基础上扩展: 1)除了整数以外,还要支持真分数的四则运算,例如:1/6+1/8=7/24 2)程序要求能处理用户的输入,判断对错,累积分 ...

  8. sublime python 断点测试_通过sublime简单的调试Python程序

    1.打开Sublime Text 3,工具(Tools)-->编译系统(Build System)-->新编译系统(Build New System),就会打开文件 untitled.su ...

  9. java和python自学教程_适合 Java开发者学习的Python 入门教程—文海思创

    原标题:适合 Java开发者学习的Python 入门教程-文海思创 [文海思创讯]在Java文章频道里,我们大部分人应该对该语言都非常的了解,而且在该生态圈内至少已经呆了好几年了.这让我们有常规和专业 ...

最新文章

  1. 将图像转换为8位单通道_数字图像存储
  2. mysql 分组占比_含泪整理MySQL索引
  3. 基本查询(Query查询中文)
  4. DEDE 文章常用标签
  5. python 今日头条 控制手机_你知道Python脚本控制安卓手机可以用来做什么吗?
  6. oracle技术之一次RMAN备份报错的诊断过程(五)
  7. 用什么软件测试路由器,软件测试路由器系统的方法及其运用
  8. 网页视频播放器代码大全 + 21个为您的网站和博客提供的免费视频播放器
  9. C++排列与组合算法详解
  10. linux u盘启动系统教程视频教程,如何用u盘启动linux系统教程
  11. ad7606驱动及仿真
  12. 我知道很多主播因为以前因为公会的名声不太好,或者不想签约被束缚等原因
  13. 测绘资质分级标准-工程测量、界线与不动产测绘
  14. 传奇SF的架设-开外网
  15. 7-7 超级玛丽 (10 分)
  16. 【深度强化学习】GAIL 与 IRL 的理解
  17. Active X控件在IE上自动下载并注册
  18. Visual studio 默认不支持x64下__asm{}内联汇编的解决方案(含资源共享)
  19. Java中的方法覆盖(Overriding)和方法重载(Overloading)是什么意思?
  20. 支付宝的手机网站支付接口的应用

热门文章

  1. 【汇编语言】王爽第六章程序6.3解答,8086汇编语言实现数据的倒序存放
  2. 106. 从中序与后序遍历序列构造二叉树
  3. Java开发框架!阿里大牛亲手操刀微服务架构实战
  4. [十二省联考2019]皮配
  5. stand up meeting 12/21/2015
  6. Mozilla Firefox 10.0 beta4 发布
  7. CAS的ABA问题描述 AtomicStampReference
  8. 编程算法 - 将排序数组按绝对值大小排序 代码(java)
  9. Iphone NSMutableArray,NSMutableDictionary AND 动态添加按钮
  10. LoadRunner8.1破解汉化过程