Python 101!Python 入门
Python是一种解释型高级语言,由 Guido van Rossum 创建,于 1991 年发布。它是动态类型的,并具有垃圾回收机制。
Python 程序的扩展名为.py ,可以通过在命令行中输入python file_name.py来运行。
它最显著的特点可能是使用大量的空白来分隔代码块,而不是更常见的 {} 符号。
行尾分号(;)是可选的,通常在 Python 中不使用。
Python 已成为 Web 应用程序、数据分析、数据科学、机器学习和人工智能等诸多领域的最佳解决方案。
Python提供的常见功能:
-
简洁性:少关注语言的语法,多关注代码本身。
-
开源:一种功能强大的语言,任何人都可以免费使用并根据需要进行修改。
-
可移植性:Python 代码可以共享,并且能够按预期运行。无缝且便捷。
-
具有可嵌入性和可扩展性:Python 可以包含其他语言的代码片段来执行某些功能。
-
被解释执行:Python 本身会处理大量的内存任务和其他繁重的 CPU 任务,让你只需专注于编码。
-
海量库:数据科学?Python 应有尽有。Web 开发?Python 依然能满足你的需求。
-
面向对象:对象有助于将复杂的现实生活问题分解成可以编写代码并解决的问题,从而获得解决方案。
Python的应用。
- 人工智能
- 桌面应用程序
- 自动化
- 网站开发
- 数据整理、探索和可视化。
安装:
请在此处下载适用于您操作系统的最新版 Python 。您可以阅读 pythontutorial.net 网站上的这篇教程,了解更多关于使用 VS Code 设置 Python 开发环境的信息。
Python Hello World。
正如Atlassian的工程经理Raghu Venkatesh所说,如果你能编写“Hello World”程序,你就能改变世界。那么,让我们来创建我们的第一个Python程序——Hello World程序。
首先,创建一个新文件夹,用于保存你的 python 文件,例如Lux。
其次,启动 VS Code 并打开你创建的新文件夹Lux。
第三,创建一个新的Python文件,比如app.py文件,输入以下代码并保存文件:
print('Hello, World!')
print ()是一个内置函数,用于在屏幕上显示消息。在本例中,它将显示消息“Hello, Word!”。
正在执行Python程序。
要执行我们上面创建的 app.py 文件,首先需要在 Windows 上启动命令提示符,或者在 macOS 或 Linux 上启动终端。
然后,导航到包含我们文件的文件夹,在本例中为Lux。
之后,输入以下命令来执行 app.py 文件:
Python3 app.py
如果一切正常,屏幕上将显示以下信息:
Hello, World!
评论
注释是程序代码、脚本或其他文件中原本不应该被运行程序的用户看到的文本。但是,在查看源代码时,注释是可见的。
注释通过解释代码的运行机制,使代码更容易理解,并有助于防止程序的部分代码执行。
# single line comment
'''
multiline comment
Using docstring
'''
注意:请在适当的地方使用评论,但不要过度评论。
算术运算符。
print(46 + 2) # 48 (addition)
print(10 - 9) # 1 (subtraction)
print(3 * 3) # 9 (multiplication)
print(84 / 2) # 42.0 (division)
print(2 ** 8) # 256 (exponent)
print(11 % 2) # 1 (remainder of the division)
print(11 // 2) # 5 (floor division)
变量
变量用于存储计算机程序中需要引用和操作的信息。它们还提供了一种用描述性名称标记数据的方法,以便读者和我们自己能够更清晰地理解程序。可以将变量视为存放信息的容器。它们的唯一目的是标记数据并将其存储在内存中。这些数据随后可以在整个程序中使用。
favourite_food = "Rösti"
print(favourite_food)
笔记:
变量无需声明。它们的数据类型会根据赋值语句推断出来,这使得 Python 成为一种动态类型语言。这意味着在代码的不同部分,同一个变量可以被赋予不同的数据类型。
favourite_food = "Rösti"
print(favourite_food)
favourite_food = 26
print(favourite_food)
favourite_food = False
print(favourite_food)
比较运算符、逻辑运算符和条件运算符。
比较运算符: ==、!=、<、>、<=、>=;
逻辑运算符: and、or、not;
条件运算符: if、else、elif
# logical operators:
laundry_day = "Monday"
today = "Tuesday"
on_vacation = False
if today is laundry_day and today is not "Sunday" and on_vacation is False:
print("It's laundry day!")
else:
print("The laundry can wait!")
# comparison operators:
age = 21
if age >= 21:
print("You can drive a trailer")
elif age >= 16:
print("You can drive a car")
else:
print("You can ride a bike")
数据类型
1)字符串。
#Example 1:
language = "Python"
#Example 2:
multiline_str = '''
one
per
line'''
#Example 3, escape characters:
escape_str = "She said: \"Python is great!\""
print(escape_str) # She said: "Python is great!"
# Example 4, concatenate strings:
one = "Lux"
two = "Academy"
print(one + " " + two) # Lux Academy
# Example 5: interpolation.
# method 1
first_name = "Lux"
last_name = "Academy"
greet = f"Welcome at {first_name} {last_name}!"
print(greet) # Welcome at Lux Tech Academy!
# method 2
first_name = "Lux"
last_name = "Academy"
greet = 'Welcome at {} {}!'.format(first_name, last_name)
print(greet) # Welcome at Lux Tech Academy!
# method 3
first_name = "Lux"
last_name = "Academy"
greet = 'Welcome at{first} {last} !'.format( first=first_name, last=last_name)
print(greet) # Welcome at Lux Tech Academy!
#Example 6, extract substrings
name = "Monty Python"
print(name[6:9]) # Pyt
print(name[6:]) # Python
print(name[:5]) # Monty
2)数字
Python 支持三种数值数据类型:int、float 和 complex。这些数据类型是自动推断的,因此无需指定。
age = 18 # int
pi = 3.14 # float
total = age + pi # float
print(type(age), type(pi), type(total)) # <class 'int'> <class 'float'> <class 'float'>
3)布尔值。
# booleans
a = True
b = False
if a is True and b is False:
print("YAY!")
4)列表。
Python 中的列表相当于其他编程语言中的数组。它们使用从零开始的索引,并且列表项可以包含任何类型的数据。列表项嵌套在方括号 [] 中。
# can store any data type
multiple_types = [True, 3.7, "Python"]
# access and modify
favourite_foods = ["pasta", "pizza", "french fries"]
print(favourite_foods[1]) # pizza
favourite_foods[0] = "rösti"
print(favourite_foods[0]) # rösti
# subsets
print(favourite_foods[1:3]) # ['pizza', 'french fries']
print(favourite_foods[2:]) # ['french fries']
print(favourite_foods[0:2]) # ['rösti', 'pizza']
# append
favourite_foods.append("paella")
# insert at index
favourite_foods.insert(1, "soup")
# remove
favourite_foods.remove("soup")
# get length
print(len(favourite_foods)) # 4
# get subset (the original list is not modified)
print(favourite_foods[1:3]) # ['pizza', 'french fries']
# lists inside lists
favourite_drinks = ["water", "wine", "juice"]
favourites = [favourite_foods, favourite_drinks]
print(favourites[1][2]) # juice
5)元组
元组就像列表,但它是不可变的(不能修改)。它们用括号括起来。
#tuples
new_tuple = ("a", "b", "c", "d")
print(len(new_tuple)) # 4
print(new_tuple[1]) # b
print(new_tuple[1:4]) # ('b', 'c', 'd')
6)字典。
字典是键值对,用花括号 {} 括起来,类似于 JavaScript 中的对象。值可以是任何数据类型。
language_creators = {
"Python" : "Guido van Rossum",
"C" : "Dennis Ritchie",
"Java" : "James Gosling",
"Go": "Robert Griesemer",
"Perl" : "Larry Wall"
}
# access, modify, delete
print(language_creators["Python"]) # Guido van Rossum
language_creators["Go"] = ["Robert Griesemer", "Rob Pike", "Ken Thompson"]
print(language_creators["Go"]) # ['Robert Griesemer', 'Rob Pike', 'Ken Thompson']
print(len(language_creators)) # 5
del language_creators["Perl"]
print(len(language_creators)) # 4
# print keys and values
print(language_creators.keys())
print(language_creators.values())
循环。
循环
# foor loop
for x in range(0, 3):
print(x)
# loop through list
for x in ["Python", "Go", "Java"]:
print(x)
# loop through dictionary
language_creators = {
"Python" : "Guido van Rossum",
"C" : "Dennis Ritchie",
"Java" : "James Gosling",
}
for key, value in language_creators.items():
print("Language: {}; Creator: {}".format(key, value))
while 循环。
# while loop
level = 0
while(level < 10):
level += 1
函数。
函数是用 def 关键字定义的。
# functions
def allowed_to_drive(age):
if age >= 21:
return True
else:
return False
print(allowed_to_drive(42)) # True
print(allowed_to_drive(12)) # False
还可以定义参数的默认值。
def is_laundry_day(today, laundry_day = "Monday", on_vacation = False):
if today is laundry_day and today is not "Sunday" and on_vacation is False:
return True
else:
return False
print(is_laundry_day("Tuesday")) # False
print(is_laundry_day("Tuesday", "Tuesday")) # True
print(is_laundry_day("Friday", "Friday", True)) # False
课程。
类是变量和操作这些变量的函数的集合。
在 Python 中,类使用 `class` 关键字定义。它们类似于 Java 和 C# 等其他语言中的类,但区别在于,Python 使用 `self` 而不是 `this` 来引用类生成的对象。此外,构造函数的名称是`init`,而不是更常见的类名。每次引用类变量时都必须使用 `self`,并且 `self` 必须是每个函数(包括构造函数)参数列表中的第一个参数。
Python 不支持方法重载,但可以通过使用参数的默认值(如函数部分所示)在一定程度上实现。
# classes
class Email:
# __ means private
__read = False
def __init__(self, subject, body):
self.subject = subject
self.body = body
def mark_as_read(self):
self.__read = True
def is_read(self):
return self.__read
def is_spam(self):
return "you won 1 million" in self.subject
e = Email("Check this out", "There are a bunch of free online course here: https://course.online")
print(e.is_spam()) # False
print(e.mark_as_read())
print(e.is_read()) # True
Python 也支持继承,这意味着可以将类设置为从另一个类或多个类继承方法和变量(多重继承)。
# inheritance
class EmailWithAttachment(Email):
def __init__(self, subject, body, attachment):
super(EmailWithAttachment, self).__init__(subject, body)
self.__attachment = attachment
def get_attachment_size(self):
return len(self.__attachment)
email_with_attachment = EmailWithAttachment("you won 1 million dollars", "open attachment to win", "one million.pdf")
print(email_with_attachment.is_spam()) # True
print(email_with_attachment.get_attachment_size()) # 15
文件 I/O
# write
todos_file = open("todos.txt", "wb")
todos_file.write(bytes("buy a new domain name\n", "UTF-8"))
todos_file.write(bytes("work on the side project\n", "UTF-8"))
todos_file.write(bytes("learn a new programming language\n", "UTF-8"))
todos_file.close()
# read
todos_file = open("todos.txt", "r+")
todos_file_contents = todos_file.read()
print(todos_file_contents)
