python入门(上)

python入门(变量,位运算,三大语句,异常处理)

1.变量,运算符,数据类型

1.运算符:// 整除 ** 幂

2.逻辑运算符:and, or, not

3.位运算符:~取反,

4.三元运算符:small = x if x < y else y

5.其他运算符: in,not in,eg: letters=[ ‘A’,‘B’ ] if ‘A’ in letters print

​ is ,is not, is, is not 对比的是两个变量的内存地址 ==, != 对比的是两个变量的值

6.print:

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end=' ''.")
for item in shoplist:
    print(item, end=' ')    #没有end则会换行,print中的(A,B,sep='&')则是用&连接

2.位运算

1.原码,补码,反码

计算机内部是用补码表示

原码:就是其二进制表示(注意,有一位符号位)10 00 00 11 -> -3

反码:正数的反码就是原码,负数的反码是符号位不变,其余位取反 11 11 11 00 -> -3

补码:正数的补码就是原码,负数的补码是反码+1。11 11 11 01 -> -3

3. 条件语句

temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)    #temp为str,需转化为int
if guess > 8:
    print("大了,大了")
else:
    if guess == 8:
        print("你太了解小姐姐的心思了!")
        print("哼,猜对也没有奖励!")
    else:
        print("小了,小了")
print("游戏结束,不玩儿啦!")
#elif
temp = input("请输入评价:")
source = int(temp)
if 100 >= source >= 90:
    print("excellent!")
elif 90 >= source >= 80:
    print("Nice!")
else:
    print("good!")
#assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
my_list = ['lsgogroup']
my_list.pop(0)    #弹出最早删除的元素
assert len(my_list) > 0

# AssertionError

4.循环语句

1.while循环

while 布尔表达式:
    代码块

【例子】

string = 'abcd'
while string:
    print(string)
    string = string[1:]

# abcd
# bcd
# cd
# d

2.while-else循环

while 布尔表达式:
    代码块    #用break可跳出循环
else:
    代码块

【例子】

count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = 6
    break
else:
    print("%d is not less than 5" % count)

# 0 is  less than 5

3.for循环

可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict

for 迭代变量 in 可迭代对象:
    代码块

【例子】

member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
    print(each)

# 张三
# 李四
# 刘德华
# 刘六
# 周润发

for i in range(len(member)):
    print(member[i])

# 张三
# 李四
# 刘德华
# 刘六
# 周润发

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key, value in dic.items():
    print(key, value, sep=':', end=' ')
    
# a:1 b:2 c:3 d:4 

4.for-else循环

for 迭代变量 in 可迭代对象:
    代码块
else:
    代码块

5.range函数

range([start,] stop[, step=1])  #左闭右开 step默认为1

for i in range(2, 9):  # 不包含9
    print(i,end=' ')     #2 3 4 5 6 7 8

6.enumerate()函数

enumerate(sequence, [start=0])

【例子】

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

7.continue语句

**continue ** 终止本轮循环进入下一循环。

for i in range(10):
    if i % 2 != 0:
        print(i)
        continue
    i += 2
    print(i,end=' ')
    #2 1
    #4 3
    #6 5
    #8 7
    #10 9

9.pass语句

pass 语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass 语句就是用来解决这些问题的。

def a_func():
    pass    #如果暂时不确定要什么代码,可以先放置一个pass语句,让代码可以正常运行。

10.推导式

列表推导式 [… for … in … [if …]]

【例子】

x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)

# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]

元组推导式 :( expr for value in collection [if condition] )

字典推导式 :{ key_expr: value_expr for value in collection [if condition] }

b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}

集合推导式 :{ expr for value in collection [if condition] }

c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}

5.异常处理

3.try-except语句

try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码
#keyError是LookupError的子类,必须坚持对其规范排序,要从最具针对性的异常到最通用的异常。
dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except KeyError:    
    print('键错误')
except LookupError:
    print('查询错误')
else:
    print(x)    # 键错误


#except同时处理多个异常
except (OSError, TypeError, ValueError) as error:
    print('出错了!\n原因是:' + str(error)) 

4.try-except-finally语句

不管try子句里面有没有发生异常,finally子句都会执行。

5.try-except-else语句(更广泛)

try:
    检测范围
except:
    出现异常后的处理代码
else:
    如果没有异常执行这块代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值