## Python笔记
安装python你的第一个python程序输出打印内容print("Mosh Hamedani")三 程序怎样运行画一只狗:代码:print('O----')print(' ||||')输出多个相同的字符:代码:print('*' * 10)四 variables 变量定义一个变量并输出代码:price = 10##整型rating = 4.9##浮点型name = 'Mosh'##字符型is_p
安装python
你的第一个python程序
输出打印内容
print("Mosh Hamedani")
三 程序怎样运行
画一只狗:
代码:
print('O----')
print(' ||||')
输出多个相同的字符:
代码:
print('*' * 10)
四 variables 变量
定义一个变量并输出
代码:
price = 10 ##整型
rating = 4.9 ##浮点型
name = 'Mosh' ##字符型
is_published = False ##布尔型
print(price)
print(rating)
print(name)
print(is_published)
练习:为医院写一个小程序,我们检查一个叫John Smith的病人,20岁,是个新病人,在这里定义三个变量:名字、年龄、和另一个变量(是否是新病人)
代码:
name = 'John Smith'
age = 20
is_new = True
五 getting input 获取输入
在屏幕上显示“what is your name?”输入姓名,打印出Hi+姓名
代码:
name = input('What is your name ? ')
print('Hi '+ name)
练习:问两个问题,用户的名字和最喜欢的颜色并打印出来
代码:
name = input('What is your name ? ')
favorite_color = input('What is your favorte color? ')
print(name +' likes '+ favorite_color)
六 Type Conversion 获取输入
编写一个程序来询问出生的那一年,然后它会计算我们的年纪并在终端上打印
代码:
birth_year = input('Birth year: ')
print(type(birth_year)) ##打印变量的类型
age = 2019 - int(birth_year)
print(type(age)) ##打印变量的类型
print(age)
Int() 将字符串转换成整型
Float() 将字符串转换成浮点型
Bool() 将字符串转换成布尔型
练习:向用户询问他们的体重然后将其转换成千克并打印出来
代码:
weight_lbs = input('Weight (lbs): ')
weight_kg = int(weight_lbs) * 0.45
print(weight_kg)
七 Strings 字符串
代码:
1.
course = "Python's Course for Beginners"
print(course)
2.course = 'Python Course for "Beginners"'
print(course)
3.
course = '''
Hi John,
Here is our first email to you
Thank you
'''
print(course)
4.
course = 'Python Course for Beginners'
print(course[0])
(输出“P”)
5.
course = 'Python Course for Beginners'
print(course[-1])
(输出“s”)
6.
course = 'Python Course for Beginners'
print(course[0:3])
(输出“Pyt”)
7.
course = 'Python Course for Beginners'
print(course[0:])
(输出“Python Course for Beginners”)
8.
course = 'Python Course for Beginners'
print(course[1:])
(输出“ython Course for Beginners”)
9.
course = 'Python Course for Beginners'
print(course[:5])
(输出“Pytho”)
10.
course = 'Python Course for Beginners'
another = course[:]##复制course
print(another)
(输出“Python Course for Beginners”)
11.
name = 'Jennifer'
print(name[1:-1])
(输出“ennife”)
八 Formatted Strings 格式化字符串
代码:
first = 'John'
last = 'Smith'
message = first + ' [ ' + last + ' ] is a coder '
print(message)
(输出“John [ Smith ] is a coder ”)
first = 'John'
last = 'Smith'
message = first + ' [ ' + last + ' ] is a coder '
msg = f'{first} [{last}] is a coder' ##f开头表示在字符串内支持大括号内的python 表达式
print(msg)
(输出“John [Smith] is a coder”)
九 Strings Method 字符串方法
course = 'Python for Beginners'
print(len(course))
(输出“20”)
course = 'Python for Beginners'
print(course.lower())
print(course.upper())
(输出“python for beginners
PYTHON FOR BEGINNERS”)
course = 'Python for Beginners'
print(course.find('P'))##找到P的索引 (输出“0”)print(course.find('o'))##找到o的索引 (输出“4”)print(course.find('O')) (输出“-1”,因为没有O)print(course.find('Beginners')) (输出“11”,因为Beginner从11开始)
替换:
course = 'Python for Beginners'
print(course.replace('Beginners','Absolute Beginners'))####把'Beginners'替换成Absolute Beginners##replace和find一样,也区分大小写(输出Python for Absolute Beginners)course = 'Python for Beginners'
print(course.replace('P','J'))##把'P'替换成J(输出Jython for Beginner) course = 'Python for Beginners'
print('Python' in course)##判断course中是否有Python(输出True) course = 'Python for Beginners'
print('python' in course)##判断course中是否有python(输出False)
十 Arithmetic Operations 算术运算
print(10 / 3)##(输出3.3333333333333335) print(10 // 3)##(输出3) print(10 % 3)##(输出1) print(10 ** 3)##(指数输出1000) x = 10
x = x + 3
print(x) ##输出13 x = 10
x -= 3
print(x) ##输出7
十一 Operator Precedence 算术优先级
x = 10 + 3 * 2
print(x) ##输出16 括号>指数运算(2**3=2的3次方)>乘除法>加减法 x = 10 + 3 * 2 ** 2
print(x) ##输出22 x = (2 + 3) * 10 -3
print(x) ##输出47
十二Math Functions 数学函数
x = 2.9
print(round(x)) ##四舍五入 输出3 x = 2.1
print(round(x)) ##输出2 x = 2.9
print(abs(-2.9))##abs()绝对值函数 import math##导入数学模块
print(math.ceil(2.9))##密封 输出3(应该是进1) import math##导入数学模块
print(math.floor(2.9))##地板方法 输出2(应该是退1)
(搜索Python 3 math module )
十三If Statement if语句
is_hot = False
is_cold = True
if is_hot:
print("It's a hot day")
print("Drink plenty water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")##输出It's a cold day
## Wear warm clothes
## Enjoy your day
练习:
代码:
price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
else:
down_payment = 0.2 * price
print(f"Down payment: ${down_payment}")##输出:Down payment: $100000.0
十四Logical Operators 逻辑运算符
and :has_high_income = True
has_good_cresit = True
if has_high_income and has_good_cresit:
print("Eligible for loan")
##输出Eligible for loan or :has_high_income = False
has_good_cresit = True
if has_high_income or has_good_cresit:
print("Eligible for loan")
##输出Eligible for loan and not :has_good_income = True
has_criminal_record = False
if has_good_income and not has_criminal_record:
print("Eligible for loan")
##输出Eligible for loan
十五 Comparison Operators 比较运算符
temperature = 30
if temperature > 30:
print("It's a hot day")
else:
print("It's not a hot day")#$输出It's not a hot day
练习
name = "J"
if len(name) < 3:
print("Name must be at least 3 characters")
elif len(name) > 50:
print("Name must be a maximum of 50 characters")
else:
print("Name looks good")
十六 Project:weight Converter 项目:体重转换器
weight = int(input('Weight: '))
unit = input('(L)bs or (K)g: ')
if unit.upper() == "L":
converted = weight * 0.45
print(f"You are {converted} kilos")
else:
converted = weight // 0.45
print(f"You are {converted} pounfs")##输出:
##Weight: 160
##(L)bs or (K)g: l
##You are 72.0 kilos
十七 While loops 循环 80’50’’
i = 1
while i <=5:
print(i)
i = i + 1
print("Done")##输出
##1
##2
##3
##4
##5
##Done i = 1
while i <=5:
print('*' * i)
i = i + 1
print("Done")
"""输出
*
**
***
****
*****
Done"""
十八 Guessing Game 猜谜游戏 84’13’’
Tip:重命名变量:右键→Refactor→Rename
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess == secret_number:
print('You won!')
break
else:
print('Sorry, you failed!')
十九 Car Game 汽车游戏 90’58’’
command = ""
while command.lower() != "quit":
command = input(">") ##这里可以改成:command = input(">").lower(),这样下边的“.lower()”就都可以删掉了
if command.lower() == "start":
print("Car started...")
elif command.lower() == "stop":
print("Car stopped.")
汽车游戏代码1:输入quit时程序退出;输入start时显示Car started;输入stop时显示Car stop;输入help时显示帮助清单
command = ""
while command.lower() != "quit":
command = input(">").lower()
if command == "start":
print("Car started...")
elif command == "stop":
print("Car stopped.")
elif command == "help":
print("""
start - to start the car
stop - to stop the
quit - to quit
""")
elif command == "quit":
break
else:
print("Soor,I don't understand that")
汽车游戏代码2:输入quit时程序退出;输入start时显示Car started;再次输入start时显示Car is already started;输入stop时显示Car stop;再次输入stop时显示Car is already stoped;输入help时显示帮助清单
command = ""
started = False
while True:
command = input(">").lower()
if command == "start":
if started:
print("Car is already started")
else:
started = True
print("Car started...")
elif command == "stop":
if not started:
print("car is already stopped")
else:
started = False
print("Car stopped.")
elif command == "help":
print("""
start - to start the car
stop - to stop the
quit - to quit
""")
elif command == "quit":
break
else:
print("Soor,I don't understand that")
二十 For Loops For循环 101’55’’
for item in 'Python':
print(item)'''输出:
P
y
t
h
o
n
''' for item in ['Mosh','John','Sara']:
print(item)
'''输出:
Mosh
John
Sara
''' for item in range(10):
print(item)
'''输出:
0
1
2
3
4
5
6
7
8
9
''' for item in range(5,10):
print(item)
'''输出:
5
6
7
8
9
''' for item in range(5,10,2):
print(item)
'''输出:
5
7
9
''' prices = [10,20,30]
total = 0
for price in prices:
total += price
print(f"Total:{total}")
##输出:Total:60
二十一 Nested Loops 嵌套循环 107’54’’
for x in range(4):
for y in range(3):
print(f'({x},{y})')
'''输出
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
(3,0)
(3,1)
(3,2)
'''
练习:
numbers = [5,2,5,2,2]
for x_count in numbers:
print('x' * x_count)
'''输出:
xxxxx
xx
xxxxx
xx
xx
''' numbers = [5,2,5,2,2]
for x_count in numbers:
output = ''
for count in range(x_count):
output += 'x'
print(output)
'''输出:
xxxxx
xx
xxxxx
xx
xx
''
二十二 List 列表 115’58’’
names = ['John','Bob','Mosh','Sarah','Mary']
print(names)
##输出:['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] names = ['John','Bob','Mosh','Sarah','Mary']
print(names[0])
##输出:John names = ['John','Bob','Mosh','Sarah','Mary']
print(names[-1])
##输出:Mary names = ['John','Bob','Mosh','Sarah','Mary']
print(names[2:])
##输出:['Mosh', 'Sarah', 'Mary'] names = ['John','Bob','Mosh','Sarah','Mary']
print(names[2:4]) ##不包括4
##输出:['Mosh', 'Sarah'] names = ['John','Bob','Mosh','Sarah','Mary']
names[0] = 'Jon'
print(names)
##输出:['Jon', 'Bob', 'Mosh', 'Sarah', 'Mary']
练习:找到列表中最大的数
numbers = [3,6,2.8,4,10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)##输出:10
二十三 2D List 二维列表 121’54’’
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix[0][1])
##输出2 matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
matrix[0][1] = 20
print(matrix[0][1])
##输出20 matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
for row in matrix: ##row 是行
for item in row:
print(item)
'''输出:
1
2
3
4
5
6
7
8
9
'''
二十四 List Method 列表方法 126’13’’
numbers = [5,2,1,7,4]
numbers.append(20) #向列表中添加一个数
print(numbers)#输出[5, 2, 1, 7, 4, 20] numbers = [5,2,1,7,4]
numbers.insert(0,10) #向列表中插入一个数
print(numbers)
#输出[10, 5, 2, 1, 7, 4] numbers = [5,2,1,7,4]
numbers.remove(5) #在列表中去除一个数
print(numbers)
#输出[2, 1, 7, 4] numbers = [5,2,1,7,4]
numbers.clear() #清空
print(numbers)
#输出[] numbers = [5,2,1,7,4]
numbers.pop() #去除最后一个数
print(numbers)
#输出[5, 2, 1, 7] numbers = [5,2,1,7,4]
print(numbers.index(5)) #找到5的索引
#输出0 numbers = [5,2,1,7,4]
print(numbers.index(50)) #找到50的索引
#错误:ValueError: 50 is not in list numbers = [5,2,1,5,7,4]
print(numbers.count(5)) #输出5的个数
#输出2 numbers = [5,2,1,5,7,4]
numbers.sort() #给列表排序
print(numbers)
#输出[1, 2, 4, 5, 5, 7] numbers = [5,2,1,5,7,4]
numbers.sort() #给列表排序
numbers.reverse() #翻转列表
print(numbers)
#输出[7, 5, 5, 4, 2, 1] numbers = [5,2,1,5,7,4]
numbers2 = numbers.copy() #把列表1复制给列表2
numbers.append(10) #
print(numbers2)
#输出[5, 2, 1, 5, 7, 4] 没有10,因为numbers1和numbers2是两个不同的列表
练习:写一个程序,删除我们列表上的重复数字
numbers = [2,2,4,6,3,4,6,1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
#输出[2, 4, 6, 3, 1]
二十五 Tuples 元组 133’39’’
numbers = (1,2,3) #元组中的元素不能更改
print(numbers[0])
#输出1 coordinates = (1,2,3)
x = coordinates[0]
y = coordinates[1]
z = coordinates[2]
x,y,z = coordinates #和2,3,4行代码作用相同 这是解压缩,也可以用于列表
print(x)
print(y)
print(z)
#输出
# 1
#2
#3
二十六 Dictionaries 字典 138’32’’
customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
print(customer["name"])
#s输出:John Smith customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
print(customer["birthday"])
#s错误:KeyError: 'birthday' customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
print(customer["Name"])
#s错误:KeyError: 'Name' customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
print(customer.get("Birthday"))
#输出:None customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
print(customer.get("Birthday"),"Jan 1 1980") #如果字典中没有Birthday,就返回默认值Jan 1 1980
#输出:None Jan 1 1980 customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
customer["name"] = "Jack Smith"
print(customer["name"]) #如果字典中没有Birthday,就返回默认值Jan 1 1980
#输出:Jack Smith customer = {
"name":"John Smith", #z字典中的键是唯一的
"age":30,
"is_verified":True
}
customer["birthday"] = "Jan 1 1980"
print(customer["birthday"]) #如果字典中没有Birthday,就返回默认值Jan 1 1980
#输出:Jan 1 1980
练习:写一个程序,询问电话号码,然后把它翻译成英文
phone = input("Phone:")
digits_mapping = {
"1":"One",
"2":"Two",
"3":"Three",
"4":"Four"
}
output = ""
for ch in phone:
output += digits_mapping.get(ch,"!") + " "
print(output)#输出:
# Phone:1345
# One Three Four !
二十七 Emoji Converter 表情转换 146’31’’
message = input(">")
words = message.split(' ') #把message用空格分开
print(words)
#输出
#>good morning 这个是从键盘上输入进去的
# ['good', 'morning'] message = input(">")
words = message.split(' ') #把message用空格分开
emoji = {
":)":"❤",
":(":"☆"
}
output = ""
for word in words:
output += emoji.get(word,word) + " "
print(output)
#输出
#>>Good morining :) 这个是从键盘上输入进去的
# Good morining ❤
#>I'm sad :(
# I'm sad ☆
二十八 Functions 函数 150’46’’
def greet_user():
print('Hi there!')
print('Welcome aboard')
print("Start")
greet_user()
print("Finish")
#输出:Start
# Hi there!
# Welcome aboard
# Finish
二十九 Parameters 参数 155’32’’
def greet_user(name):
print(f'Hi {name}!')
print('Welcome aboard')
print("Start")
greet_user("John")
print("Finish")
#输出:
# Start
# Hi John!
# Welcome aboard
# Finish
注:parameter是孔或者占位符,我们在函数中定义了接收信息Argument是为这些函数提供的实际信息
def greet_user(first_name,last_name):
print(f'Hi {first_name} {last_name}!')
print('Welcome aboard')
print("Start")
greet_user("John", "Smith")
print("Finish")
#输出:
# Start
# Hi John Smith!
# Welcome aboard
# Finish
三十 Keyword Argument 关键词参数 159’37’’
def greet_user(first_name,last_name):
print(f'Hi {first_name} {last_name}!')
print('Welcome aboard')
print("Start")
greet_user(last_name="Smith",first_name="John")
print("Finish")
#输出:
# Start
# Hi John Smith!
# Welcome aboard
# Finish
三十一 Return statement 返回 165’06’’
def square(number):
return number * number
result = square(3)#或者:print(square(3))
print(result)
#输出:9
三十二 Create a Reusable function 创建一个没有用的函数 169’06’’
def emoji_converter(messge):
words = message.split(' ') # 把message用空格分开
emoji = {
":)": "❤",
":(": "☆"
}
output = ""
for word in words:
output += emoji.get(word, word) + " "
return output
message = input(">")
print(emoji_converter(message))
#输出
#>>Good morining :) 这个是从键盘上输入进去的
# Good morining ❤
#>I'm sad :(
# I'm sad ☆
三十三 Exception 异常 173’54’’
使用尝试接受块来处理异常try: #尝试一下下面的代码
age = int(input('Age:'))
print(age)
except ValueError: #如果不成功,就打印Invalid value 这样就不会破坏程序
print('Invalid value')
#输出:
# Age:sad
# Invalid value try: #尝试一下下面的代码
age = int(input('Age:'))
income = 20000
risk = income / age
print(age)
except ZeroDivisionError: #除法错误
print('Age cannot be Zero')
except ValueError: #如果不成功,就打印Invalid value 这样就不会破坏程序
print('Invalid value') #就是要捕获程序所出的错误
#输出:
# Age:0
# Age cannot be Zero
三十四 Comments注释 179’26’’
三十五 Classes类 181’59’’
class Point:
def movr(self):
print("move")
def draw(self):
print("draw")
point1 = Point()
point1.draw()
#输出:draw class Point:
def movr(self):
print("move")
def draw(self):
print("draw")
point1 = Point()
point1.x = 10
point1.y = 20
print(point1.x)
point1.draw()
#输出:draw
#10
三十六 Constructors 构造函数 188’02’’
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def movr(self):
print("move")
def draw(self):
print("draw")
point = Point(10,20)
print(point.x)
#输出:10 class Point:
def __init__(self,x,y): #构造函数
self.x = x
self.y = y
def movr(self):
print("move")
def draw(self):
print("draw")
point = Point(10,20)
point.x = 11
print(point.x)
#输出:11
练习:
class Person:
def __init__(self,name):
self.name = name
def talk(self):
print("talk")
john = Person("John Smith")
print(john.name)
john.talk()
#输出:
# John Smith
# talk class Person:
def __init__(self,name):
self.name = name
def talk(self):
print(f"Hi, I'm {self.name}")
john = Person("John Smith")
john.talk()
#输出:Hi, I'm John Smith class Person:
def __init__(self,name):
self.name = name
def talk(self):
print(f"Hi, I'm {self.name}")
john = Person("John Smith")
john.talk()
bob = Person("Bob Smith")
bob.talk()
#输出:Hi, I'm John Smith
# Hi, I'm Bob Smith
三十七 Inheritance继承 194’54’’
class Mammal:
def walk(self):
print("walk")
class Dog(Mammal): #将继承Mammal类中定义的所有方法
pass #pass没有意义,只是因为python不支持空的类
class Cat(Mammal):
pass
dog1 = Dog()
dog1.walk() class Mammal:
def walk(self):
print("walk")
class Dog(Mammal): #将继承Mammal类中定义的所有方法
def bark(self):
print("bark")
class Cat(Mammal):
def be_annoying(self):
print("annoying")
dog1 = Dog()
dog1.bark()
cat1 = Cat()
cat1.be_annoying()
#输出:bark
# annoying
三十八 Modules模块 199’47’’
可以把模块放到一个单独的模块中,叫做转换器,然后可以把这个模块导入到任何一个需要这些功能的程序中 打开project → 点击项目 → new → file/python file →调用文件converters.py → 把app.py的代剪切到converters.py中 → → → → converters.py的代码:
def lbs_to_kg(weight):
return weight * 0.45
def kg_to_lbs(weight):
return weight / 0.45
app.py的代码:
import converters #导入整个模块
from converters import kg_to_lbs #导入部分模块
kg_to_lbs(100)
print(kg_to_lbs(70))
#输出:155.55555555555554
练习:
Utils.py代码:
def find_max(numbers):
max = numbers[0]
for number in numbers:
if number > max:
max = number
return max
App.py代码:
from utils import find_max
numbers = [10,3,6,3]
max = find_max(numbers)
print(max) #输出10
三十九 Packages封装 210’27’’
更多推荐
所有评论(0)