本文主要是介绍freeCodeCamp的python教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
20200910
字符串类型的使用
20200914
数字类型的使用
用户输入
创建一个计算器
列表list
元组truple
函数
if语句
字典
while循环
for循环
二维列表
Giraffe language
Try/Except
文件操作
模块&pip
类
对象函数
继承
20200910
字符串类型的使用
转义符 在类似“前加\
输入:
print ("OvO\"QAQ")
输出:
OvO"QAQ
一些自带的字符串函数:upper() lower()
输入:
print(character_name.lower())
print(character_name.islower())
print(len(character_name))
print(character_name[0])
print(character_name.index("J")) #通过索引查到字符串中字符
print(character_name.index("ohn")) #查询开始位置
print(character_name.replace("J", "H")) #替换函数
输出:
john j #全小写字母
False
4
J
0
1
Hohn H
20200914
数字类型的使用
输入:
print(pow(2, 3)) # 2的3次幂
print(min(2, 3))
print(round(3.2))
print(round(3.5)) #四舍五入from math import *print(floor(3.7))
print(ceil(3.7))
print(sqrt(36))
输出:
8
2
3
4
3
4
6.0
用户输入
输入:
name = input("Enter your name: ")print(name)
输出:
Enter your name: shen
shen
创建一个计算器
输入:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = num1 + num2print(result)
输出:
Enter a number: 1
Enter another number: 2
12
Python中使用input接收用户输入时会默认将输入转化为字符串,所以需要使用int将字符串转换为整型
但是int函数无法处理浮点,所以可以换成float
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)print(result)
列表list
注意一下使用copy函数和不使用的区别
输入:
friends = ["A", "B", "C", 2, True]print(friends)
print(friends[0])
print(friends[-1]) #采用负数索引反向访问列表
print(friends[1:]) #索引1之后的元素friends[1] = "F"
print(friends[1])list = ["A", "B", "C"]
num = [2, 4, 12]list.extend(num) #连接两个列表
print(list)
list.insert(1, "F") #在某一索引后添加元素
print(list)
list.remove("A")
print(list)
list.append("D") #添加到最后
print(list)
a = list.pop() #弹出最后一个元素
print(a)print(list.index("B")) #通过元素找到索引
print(list.count("B")) #元素数量
num.sort() #升序排列
print(num)
num.reverse() #将列表逆置
print(num)num2 = num.copy() #使用copy函数是创建一个新副本,而直接赋值是赋指针。前者修改时两者互不影响,后者修改时两个列表都会被修改
print(num2)list.clear()
print(list)
输出:
['A', 'B', 'C', 2, True]
A
True
['B', 'C', 2, True]
F
['A', 'B', 'C', 2, 4, 12]
['A', 'F', 'B', 'C', 2, 4, 12]
['F', 'B', 'C', 2, 4, 12]
['F', 'B', 'C', 2, 4, 12, 'D']
D
1
1
[2, 4, 12]
[12, 4, 2]
[12, 4, 2]
[]
元组truple
coordinates = (4, 5)
print(coordinates[0])#coordinates[1] = 2 这是错的,元组不可以改变,但可以修改然后赋值给新的元组coordinates1 = [(4, 5), (1, 2), (4, 12)] # 一个元组列表
函数
def sayhi(name, age):print("hi" + name + age)sayhi("A", "12")def sayhi(name, age):print("hi" + name + str(age))sayhi("A", 12)
if语句
is_male = True
is_tall = Trueif is_male and is_tall:print("You are a male or tall or both")
elif is_male and not(is_tall):print("short male")
else:print("You are not")
def max_num(num1, num2, num3):if num1 >= num2 and num1 >= num3:return num1elif num2 >= num1 and num2 >= num3:return num2else:return num3print(max_num(2, 5, 3))
字典
monthConversions = {"Jan" : "January","Feb" : "February" #键值必须唯一
}print(monthConversions["Jan"])
print(monthConversions.get("Jan", "not a vaild key")) #用get()可以返回默认值避免报错
print(monthConversions.get("J", "not a vaild key")) #用get()可以返回默认值避免报错
while循环
i = 1
while i <= 10:print(i)i += 1
for循环
for letter in "Giraffe Academy":print(letter)friends = ["A", "B", "C"]
for friend in friends:print(friend)for index in range(10): #0-9,没有10print(index)for index in range(3, 10):print(index)for index in range(len(friends)):print(friends[index])
二维列表
number_grid = [[1, 2, 3],[4, 5, 6],[7, 8, 9],[0]
]for row in range(len(number_grid)):for col in number_grid[row]:print(col)for row in number_grid: #先定位到每一行for col in row: #再定位到每一列的各个数print(col)
Giraffe language
1. lower()和isupper()的使用
2. 在if中用in遍历字符串依次判断
def translate(phrase):translation = ""for letter in phrase:if letter.lower() in "aeiou":if letter.isupper():translation = translation + "G"else:translation = translation + "g"else:translation = translation + letterreturn translationprint(translate(input("Enter a phrase:")))
Try/Except
输入:
1. 在except后加不同的错误类型用于捕捉不同的错误
2. 使用as来得到错误信息,并打印
try:value = 10 / 0number = int(input("Enter a number:"))print(number)
except ZeroDivisionError as err:print(err)
except ValueError:print("Invalid input")
输出:
division by zero
文件操作
1. “r” 只读 2. “w” 写不可读 3. “a” appand 4. “r+” 读和写
读操作:
注意在调用了read()后则读指针已经指向了最后,在调用readline()或者readlines()是读不到内容的
#file = open("test.txt", "r")
with open("test.txt", "r") as file:print(file.readable()) #是否可读print(file.read())print(file.readline().strip('\n'))print(file.readlines()) #将每一行读入一个列表中#print(file.readlines()[1])for num in file.readlines():print(num)#file.close() 用with open不需要再额外写close()了
写操作:
a为在原文件后添加,w为重写该文件,也可以用w来创建一个文件
with open("test1.txt", "a") as file: #创建了一个新文件file.write("\nabc")with open("test1.html", "w") as file: #创建了一个新文件file.write("<p>Hello</p>")
模块&pip
输入:
import useful_toolsprint(useful_tools.roll(6))
输出:
4
Python的一些模块,可以节省很多时间https://docs.python.org/3/py-modindex.html
包安装(windows):pip install ***
移除:pip uninstall ***
类
创建一个学生类:注意文件名和类名一致
class Student:def __init__(self, name, major, gpa):self.name = nameself.major = majorself.gpa = gpa
创建一个学生对象:
from Student import Studentstudent1 = Student("A", "AI", 3.2)print(student1.name)
对象函数
类:
class Student:def __init__(self, name, major, gpa):self.name = nameself.major = majorself.gpa = gpadef on_honor_roll(self):if self.gpa >= 3.5:return Trueelse:return False
主函数:
from Student import Studentstudent1 = Student("A", "AI", 3.2)
student2 = Student("B", "AI", 3.7)print(student1.on_honor_roll())
print(student2.on_honor_roll())
输出:
False
True
继承
继承类:
from Student import Studentclass badstudent(Student):def do_not_finish_homework(self):print("no homework")
主函数:
from badstudent import badstudentstudent3 = badstudent("C", "AI", 3.0)student3.do_not_finish_homework()
输出:
no homework
这篇关于freeCodeCamp的python教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!