PYTHON 基础 from codecademy

PYTHON from codecademy

1. python 基础

1.1.1 Python Operators 运算子

** ; % ; //

a = 13 
b = 14
#modulus (%) operator
print (a % b) # prints the remainder of a/b
#exponent (**) operator
print (a ** b) #prints a^b
# // 
print (a // b) #输出整数,向下取整,即使小数点为9,也会向下取整
13
3937376385699289
0

1.1.2 << >> & | ^ ~

print(5 >> 4)  # 输出 0  (Right Shift)。将数字 5 的二进制表示向右移动 4 位。
print(5 << 1)  # 输出 10 (Left Shift)。将数字 5 的二进制表示向左移动 1 位。

print(8 & 5)   
#8 的二进制是 1000。
#5 的二进制是 101。
#按位与操作后得到 100。
#输出:4

print(9 | 4)  
#9 的二进制是 1001。
#4 的二进制是 100。
#按位或操作后得到 1101。
#输出:13

print(12 ^ 42) # 输出 34
print(~88)     # 输出 -89

1.2 len() ;upper() ;lower() ; isalpha()

x="asdasdas"
a=len(x)
b=x.upper()

#The .lower() function does not modify the string itself, it simply returns a lowercase-version.
c=x.lower()

d=x.isalpha()

print(str(x) + " " + str(a) + " " + str(b) + " "+ str(c) + " "+ str(d))
asdasdas 8 ASDASDAS asdasdas True

1.3 ‘not’ ; ‘and’ ; ‘or’

True 为 1
False 为 0

not运算:
添加否定

and运算:
乘法
for instance : True and False = 1*0 = False

or运算:
加法
for instance : True and False = 1+0 =True

运算顺序如下:

not is evaluated first;(负号)
and is evaluated next;(乘号)
or is evaluated last.(加号)

1.4 if 用法

def grade_converter(grade):
    if grade>=90:   #若成绩>90则返回A,结束函数。
        return "A"
    elif grade>=80: #需要注意的是:if语句是有执行顺序的,所以不需要添加上限。
        return "B"
    elif grade>=70:
        return "C"
    elif grade>=65:
        return "D"
    else:
        return "F"
    
print(grade_converter(38))
F

1.5 input()

input("Enter a word:")  
' asdasd '

1.6 引用module包

""" from module import function """
""" * means import all"""
from math import *
"""to see everything in the module"""
import math 
everything = dir(math) # Sets everything to a list of things from math
print (everything) # Prints 'em all!
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

1.7 min() ; max() ; abs()

def biggest_number(*args):
  print (str(max(args)))
  return max(args)
    
def smallest_number(*args):
  print (str(min(args)))
  return min(args)

def distance_from_zero(arg):
  print (str(abs(arg)))
  return 0
biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)
10
-10
10





0

1.8 join的用法

s1 = "-"
s2 = " "
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))

r-u-n-o-o-b
r u n o o b

1.9 while 的用法

python的while比for还像C的for循环

1.10 range()

range 返回的是一个列表

=======================================================================================================

遇到的问题

1. 函数调用与for循环中变量的选取
shopping_list = ["banana", "orange", "apple"]

stock = {
  "banana": 6,
  "apple": 0,
  "orange": 32,
  "pear": 15
}
    
prices = {
  "banana": 4,
  "apple": 2,
  "orange": 1.5,
  "pear": 3
}

def compute_bill(food): 
#此处的food 可以是可迭代对象中的元素。
#即使food不是一个明确的列表,只要它是可迭代的,就可以在for循环中使用。
  total = 0
  for item in food:
    total += prices[item] 
    print (total)
  return total

print (compute_bill(shopping_list)) #此处调用函数时,不能直接‘banana’,而是键入一个list
                                    #因为如果键入‘banana’是返回给函数一个字符串,函数在字符串中循环,当然是错的。

学以致用

lloyd = {
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
}
alice = {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
}
tyler = {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
  total = sum(numbers)
  total = float(total)
  return total / len(numbers)

def get_average(student):
  homework = average(student["homework"])
  quizzes = average(student["quizzes"])
  tests = average(student["tests"])
  return homework*0.1 + quizzes*0.3 + tests*0.6

def get_letter_grade(score):
  if score >=90:
    return "A"
  elif score >=80:
    return "B"
  elif score >=70:
    return "C"
  elif score >=60:
    return "D"
  else: return "F"

x=get_letter_grade(get_average(lloyd))
print (x)

def get_class_average(class_list):
  results=[]
  for x in class_list:
   a = get_average(x)
   results.append(a)
  return average(results)

students = [alice,lloyd,tyler]
print (get_class_average(students))
print (get_letter_grade(get_class_average(students)))

B
83.86666666666666
B

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

2. further python

2. “remove” 和 “del” 的不同用法和含义。

“remove”:

“remove” 用于从列表中删除特定的元素。它接受一个值作为参数,并删除列表中首次出现的该值。
示例:

numbers = [1, 2, 3, 4, 5]

numbers.remove(3)  # 从列表中删除值为 3 的元素

print(numbers)  # 输出: [1, 2, 4, 5]
[1, 2, 4, 5]

“del”:

“del” 用于删除变量或列表中指定位置的元素。
当用于删除变量时,它会删除该变量,释放内存。
当用于删除列表中的元素时,它可以根据索引删除指定位置的元素。
示例:

numbers = [1, 2, 3, 4, 5]

del numbers[2]  # 删除列表中索引为 2 的元素(值为 3)

print(numbers)  
# 输出: [1, 2, 4, 5]

del numbers  # 删除整个变量 numbers

总结:

“remove” 用于删除列表中特定的元素。
“del” 用于删除列表中指定位置的元素或整个变量。

=======================================================================================================

2.3 Loop

2.3.1 enumerate()

enumerate 枚举
返回index值和值

a = ["1,3,4,5,6","a","s","asd"]
list(enumerate(a))
[(0, '1,3,4,5,6'), (1, 'a'), (2, 's'), (3, 'asd')]

2.3.2 zip() zip(*)

zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.

like the example below

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 2.x zip() 返回的是一个列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同


list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
print (zip(list_a, list_b))
print(list(zip(list_a, list_b)))
a1, a2 = zip(*zip(list_a, list_b))
print(zip(*zip(list_a, list_b))) #zip(*)解压,返回矩阵,而非;list
print(a1)
print(a2)
print(list(a1))
<zip object at 0x00000263878D7980>
[(3, 2), (9, 4), (17, 8), (15, 10), (19, 30)]
<zip object at 0x0000026387915540>
(3, 9, 17, 15, 19)
(2, 4, 8, 10, 30)
[3, 9, 17, 15, 19]

2.3.3 字符串的乘法

print("*"*50)
**************************************************

2.3.4 int(“b”,a )

b的a进制数的十进制数

print(int("10001101",2))
141

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

3. LIST comprehension syntax

3.1 [x for… if…]

c = ['C' for x in range(5) if x < 3]
print (c)

['C', 'C', 'C']

3.2 list的使用(形如C的数组)

append() index() insert()

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")# Use index() to find "duck"
print (duck_index)

animals.append("asdasd")

# replace duck to cobra
animals.insert(duck_index,"cobra")

print (animals) # Observe what prints after the insert operation

""" ['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox'] """
2
['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox']





" ['aardvark', 'badger', 'cobra', 'duck', 'emu', 'fennec fox'] "

3.3 for: 语句

下面的代码我认为是很好的筛选例子,如果数组中没有错误的“fruit”

则可以全部遍历并利用else给出结论

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print ('You have...')
for f in fruits:
  if f == 'tomato':
  #if f == 'xxxx': 则可以触发else
    print ('A tomato is not a fruit!') # (It actually is.)
    break
  print ('A'), f
#
#
#这里的else只有for正常结束时才触发。
#如果上面的for语句hit到break了,就不会触发
else: 
  print ('A fine selection of fruits!')
You have...
A
A
A
A tomato is not a fruit!

3.4 [start : end : stride]

start 表示切片开始的位置(包含在内)。
end 表示切片结束的位置(不包含在内)。
stride 步长,从一个元素迈步到下一个元素的距离

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
x = my_list[0:3]  # start=0, end=3, stride=1(默认值)
print(x)  # 输出:[0, 1, 2]

a = my_list[::2]  # start=0(默认值),end=末尾(默认值),stride=2
print(a)  # 输出:[0, 2, 4, 6, 8]

backwards = my_list[::-1]   #stride 为-1,倒着输出
print (backwards)           
[0, 1, 2]
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

3.5 lambda函数

lambda 函数是匿名的,它们没有函数名称,只能通过赋值给变量或作为参数传递给其他函数来使用。

lambda 函数通常只包含一行代码,这使得它们适用于编写简单的函数。

from functools import reduce
 
numbers = [1, 2, 3, 4, 5]
 
# 使用 reduce() 和 lambda 函数计算乘积
product = reduce(lambda x, y: x * y, numbers)
 
print(product)  # 输出:120

3.6 filter() 过滤器

过滤掉不要的,留下符合条件的

squares=[x**2 for x in range(1,11)] # the squares of the numbers 1 to 10

#Use filter() and a lambda expression to print out only the squares that are between 30 and 70 .
print (filter(lambda x : x in range(30,70),squares)) 

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

4. Dictionaries

4.1 字典的添加

值得注意的是,dictionary是无序的数据结构。

menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print (menu['Chicken Alfredo'])

#Add some dish-price pairs to menu!
menu['x'] = 10
menu['y'] = 12
menu['z'] = 23

print  ("There are " + str(len(menu)) + " items on the menu.")
print (menu)

4.2 del() 字典的删除

# key - animal_name : value - location 
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines

# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
print (zoo_animals)

4.3 .get() 字典的读取

dict1 = {'Name': 'Runoob', 'Age': 27}

print (dict1.get('Name'))

print (dict1.get('name',0.0)) #0.0为我设的默认值,没识别到‘name’则返回0.0

print (dict1.get("name",0.1)) #字典的识别要注意前面item的格式,有些是“”,有些是‘’。这里的“”是读不到的

Runoob
0.0
0.1

4.4 .items() .values() .keys()

d = {
    "what" : "is" ,
    "A" : "bloody",
    "dictionary" : True
}

print(d.values())
print (d.keys())
print (d.items())
dict_values(['is', 'bloody', True])
dict_keys(['what', 'A', 'dictionary'])
dict_items([('what', 'is'), ('A', 'bloody'), ('dictionary', True)])

5. Class 类

5.1 object类

class classname(object):
#object是一个基本类,是所有类的基本类。可以不写。如下:

#class classname:

    pass

5.2 INHERIT

5.2.1类的继承
class ParentClass(object):
  pass
class ChildClass(ParentClass):
  # new variables and functions go here
  pass

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值