Python记录-基础语法入门

# -*- coding: utf-8 -*-
#数字计算
a=1
b=2
print(a+b)
print(a*b)
print((a+b)/1) #浮点数
print((a+b)//2) ##保留整数部分
print(17%3) #求余数
print(5**2) #幂乘方
#变量使用前必须定义赋值
#字符串
print('abc')
print("abc")
print("abc"+"def")
print('a''b')
word='python'
print(word[0]) #索引
print(word[-1])
print(word[0:2] + word[2:6]) #切片
print(word[:2] + word[2:]) #等于word
print(len(word))
#列表
squares = [1, 4, 9, 16, 25]
print(squares)
print(squares[-1])
print(squares[-3:])
print(squares[:])
print(squares + [36, 49, 64, 81, 100])
squares.append(216)
squares.append(7 ** 3)
print(squares)
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
#对切片赋值
letters[2:5] = ['C', 'D', 'E']
print(letters)
print(len(letters))
#组合
a = ['a', 'b', 'c']
n = [1, 2, 3]
x=[a,n]
print(x)
c,d=0,1
while d < 10:
    print(d)
    c,d=d,c+d
#if
x = int(input("Please enter an integer: "))
if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')
#for
words = ['cat', 'window', 'defenestrate']
for w in words:
     print(w, len(w))

for w in words[:]:  
     if len(w) > 6:
        words.insert(0, w)
print(words)
for i in range(5):
    print(i)
#range(5, 10)
#5 through 9
#range(0, 10, 3)
#0, 3, 6, 9
#range(-10, -100, -30)
#-10, -40, -70
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])
print(range(10))
print(list(range(5)))
#break continue pass
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
              print(n, 'equals', x, '*', n//x)
              break
        else:
          print(n, 'is a prime number')
for num in range(2, 10):
      if num % 2 == 0:
          print("Found an even number", num)
          continue
      print("Found a number", num)
while True:
       pass
#函数
def fib(n):
    a,b=0,1
    while a < n:
        print(a,end=' ')
        a,b=b,a+b
    print()
f=fib
f(100)
print(fib(2000))

def fib2(n):
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a,b=b,a+b
    return result
f100=fib2(100)
print(f100)

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise OSError('uncooperative user')
        print(complaint)
#只给出必要的参数:
ask_ok('Do you really want to quit?')
#给出一个可选的参数:
ask_ok('OK to overwrite the file?', 2)
#或者给出所有的参数:
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

i = 5
def f(arg=i):
    print(arg)
i = 6
f()
#将会输出5

def f(a, L=[]):
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))

#输出
#[1]
#[1, 2]
#[1, 2, 3]

#关键字参数
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
#接受一个必选参数 (voltage) 以及三个可选参数 (state, action, 和 type)。
#可以用以下的任一方法调用:
parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

#可变参数
def concat(*args, sep="/"):
    return sep.join(args)、

print(concat("earth", "mars", "venus"))
print(concat("earth", "mars", "venus", sep="."))

print(list(range(3, 6)))
args = [3, 6]
print(list(range(*args)))
#输出[3, 4, 5]

#数据结构
#追加list.append(x)
#list.extend(L)将一个列表所有元素添加到另一个列表中
#list.insert(i,x) 在指定位置插入元素
#list.remove(x) 删除元素
#list.pop([i]) 从指定的位置删除元素,并将其返回,如果没有指定索引
#a.pop()返回最后一个元素
#list.clear() 从列表中删除所有元素 相当于del a[:]
#list.index(x) 返回索引
#list.count(x) 返回x出现的次数
#list.sort() 排序
#list.reverse() 倒序
#list.copy 返回列表的一个浅拷贝,等同于a[:]
#把列表当堆栈使用
#把列表当作队列使用
#del语句
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[0]
del a[2:4]
del a[:]
del a
#元组和序列
#一个元组由数个逗号分隔的值组成
t = 12345, 54321, 'hello!'
t[0]
u = t, (1, 2, 3, 4, 5)
v = ([1, 2, 3], [3, 2, 1])
#元组就像字符串,不可变的
#列表是可变的 ,它们的元素通常是相同类型的并通过迭代访问。
#集合
#Python 还包含了一个数据类型 —— set (集合)。集合是一个无序不重复元素的集。
#基本功能包括关系测试和消除重复元素。集合对象还支持 union(联合),
#intersection(交),difference(差)和 sysmmetric difference(对称差集)
#等数学运算。大括号或 set() 函数可以用来创建集合。
#注意:想要创建空集合你必须使用 set() 而不是 {}。
#后者用于创建空字典,我们在下一节中介绍的一种数据结构。
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)  
a = set('abracadabra')
b = set('alacazam')

a - b
a | b
a & b
a ^ b

#字典
#理解字典的最佳方式是把它看做无序的键: 值对 (key:value 对)集合,
#键必须是互不相同的(在同一个字典之内)。一对大括号创建一个空的字典: {} 。
#初始化列表时,在大括号内放置一组逗号分隔的键:值对,这也是字典输出的方式。

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
del tel['sape']
list(tel.keys())
sorted(tel.keys())

dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)

for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)

  

posted @ 2019-08-06 21:42  信方  阅读(207)  评论(0编辑  收藏  举报