Fork me on CSDN

谷歌:python速成课程笔记

1.从用户那里获取信息

name = "Alex"
print("hello"  +  name)

2.让python成为你的计算器

1 print(4+5)
2 print(3-2)
3 print(2*3)
4 print(1/3)
5 print(((2+3)/3+5)*5)
6 print(2**10)

3.python语法基本介绍

Python基本数据类型一般分为:数字、字符串、列表、元组、字典、集合这六种基本数据类型。浮点型、复数类型、布尔型(布尔型就是只有两个值的整型)、这几种数字类型。列表、元组、字符串都是序列。

print(7 + "8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
#查看数据类型
print(type("a"))
<class 'str'>
print(type(7))
<class 'int'>
print(type(4.5))
<class 'float'>

变量存储在内存中的值,这就意味着在创建变量时会在内存中开辟一个空间。基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。因此,变量可以指定不同的数据类型,这些变量可以存储整数,小数或字符。

length = 10
width = 20
area = length * width
print(area)

表达式,数字和类型转换

print(7 + 8.5)
base = 3
height = 6
area = (base * height)/2
print("The area is :" + str(area))

4.定义功能

def greeting(name, department):
      print("Welcome, " + name)
      print("You are part of " + department)

greeting("blake", "AI engineering")

5.返回值

def triangle_area(base, height):
      return base * heigth / 2

area_a = triangle_area(3, 2)
area_b = triangle_area(4, 5)
sum = area_a + area_b
print("The sum of areas is : " + str(sum))

 6.while循环

def attempt(n):
      x=0
      while(x<n):
          print("Attempt" + str(x))
          x += 1
      print("Done")

attempt(5)
#用户登录输错用户名举例
username = get_username()
while not vaild_username(username):
       print("It's not vaild name,please try again")
       username = get_username()

7.无限循环以及如何打破它们

#无限循环
while x%2 ==0:
         x =  x / 2
#方法
while x!=0 and x%2 ==0:
         x =  x / 2

8.一些循环示例

#1-10的乘积
product = 1
for n in range(1,10):
     product = product * n

print(product)
#特定间隔温度转换
def to_celsius(x):
      return (x -32)*5/9

for x in range(0,101,10):
      print(x,to_celsius(x))

9.嵌套循环

#乘法表
for x in range(1,10):
     for y in range(x,10):
          print(str(x)+ "*" +str(y)+ "=" +str(x*y),end=" ")
     print()
#比赛行程,两两对抗
teams = ["Dragons", "Wolves", "Dog", "Pandas", "Unicorns"]
for home_team in teams:
     for away_team in teams:
        if home_team != away_team:
           print(home_team + "    VS   " +away_team)

10.递归

def factorial(n):
      if n<2:
         return 1
      return n * factorial(n-1)

 11.创建新字符串

#更换域名
def replace(email, old_domain, new_domain):
      if "@" + old_domain in email:
          index = email.index("@" + old_domain)
          new_email = email[:index] + "@" + new_domain
          return new_email
      return email

12.格式化字符串

name = "Nancy"
luck_number = len(name) * 3
print("Hello {},your lucky number is {}".format(name, luck_number))
#print("your lucky number is {luck_number},{name}".format(name = name, luck_number = len(name) *3))
#保留两位小数
price = 7.5
with_tax = price * 1.09
print("Basic price is ${:.2f},with_tax is ${:.2f}".format(price, with_tax))

13.列表

#增加列表元素
fruits = ["pineapple", "banana", "apple", "melon"]
#末尾加入
fruits.append("kiwi")
print(fruits)
#第一个位置加入
fruits.insert(0, "orange")
print(fruits)
#------------------------
#删除元素
fruits.remove("melon")
print(fruits)
#取出特定位置元素
fruits.pop(3)
#更改特定位置元素
fruits[2] = "Strawberry"
print(fruits)

14.元组

元组元素不可更改

#时间转换器
def convert_seconds(seconds):
      hours = seconds // 3600
      minutes = (seconds - hours * 3600) // 60
      remaining_seconds = seconds - hours * 3600 - minutes * 60
      return hours, minutes, remaining_seconds

convert_seconds(5000)

#检查元素类型
print(type(convert_seconds(5000))

15.遍历列表和元组

animals = ["lion", "zebra", "dolphin", "monkey"]
chars = 0 
for animal in animals:
     chars += len(animal)

print("total characters:{},the average length:{}".format(chars, chars/len(animals)))
winners = ["Ashep", "Bob", "Nancy"]
for index, person in enumerate(winners):
     print("{} - {}".format(index+1, person))
#分离人名和邮箱地址
def
full_emails(people): result = [] for email, name in people: result.append("{} <{}>".format(name,email)) return result print(full_emails([("Alex@qq.com", "Alex"),("Nancy@163.com", "Nancy")]))

16.列表综合

#列表推导
multiplus = []
for x in range(1,11):
     multiplus.append(x*7)

print(multiplus)
#一行实现
multiplus = [x * 7 for x in range(1,11)]
print(multiplus)
#计算列表元素的长度
languages = ["python", "perl", "java", "c++", "ruby"]
lengths = [len(language) for language in languages]
print(lengths)

#挑选符合特定条件的元素
z = [ x  for x in range(1, 100) if x % 3 ==0]
print(z)

17.字典

file_counts = {"txt":10, "png":19, "csv":23,"html":45}
#查找字典元素值
print(file_counts["txt"])
#增加元素
file_counts["gif"] = 17
print(file_counts)
#更改元素值
file_counts["png"] = 48
print(file_counts)
#迭代字典
file_counts = {"py":13, "txt":24, "gif":32}
for extension in file_counts:
     print(extension)

#友好式显示
for ext, amount in file_counts.items():
     print("There have {} files with .{} extension".format(amount, ext))

#查看字典里所有的键
file_counts.keys()
#查看字典里所有的键值
file_counts.values()
#输出所有键值
for value in file_counts.values():
     print(value)
#统计文本每个字母个数
def count_letters(txt):
      result = {}
      for letter in txt:
           if letter not in result:
              result[letter] = 0
           result[letter] +=1
      return result

count_letters("we are very good")

18.面向对象编程

#内置函数
dir(" ")
#帮助
help(" ")
#定义类苹果
class Apple:
        color = " "
        flavor = " "

#实例化
jonagold = Apple()
jonagold.color = "red"
jonagold.flavor = "sweet"
print(jonagold.color)
print(jonagold.flavor)
print(jonagold.color.upper())
#简单示例
class Piglet:
        def speak(self):
              print("oink oink")

hamlet = Piglet()
hamlet.speak()
#复杂示例
class Piglet:
        name = "piglet"
        def speak(self):
              print("Oink!I'm {},oink oink.".format(self.name))

hamlet = Piglet()
hamlet.name = "Hamlet"
hamlet.speak()
#构造函数和其他特殊方法
class Apple:
        def __init__(self, color, flavor):
             self.color = color
             self.flavor = flavor

jonagold = Apple("red", "sweet")
print(jonagold.color)

19.关于jupyter笔记本

详情参照:https://www.jianshu.com/p/91365f343585

20.继承

#定义类动物
class Animal:
        sound = " "
        def __init__(self, name):
             self.name = name
        def speak(self):
             print("{sound},I'm {name}!{sound} {sound}.".format(name = self.name,sound = self.sound))

#定义类pig,继承animal
class Piglet(Animal):
        sound = "Onik"

#实例化类pig
hamlet = Piglet("Hamlet")
hamlet.speak()

21.撰写

22.词云

https://blog.csdn.net/zzc_zhuyu/article/details/90814902

posted @ 2021-03-07 11:51  追风赶月的少年  阅读(213)  评论(0编辑  收藏  举报