Python快速入门(下)

Python编程基础:条件判断与循环语句详解
本文详细介绍了Python的基础知识,包括环境安装、条件判断(if-else, if-elif-else, 嵌套结构, 断言)和循环语句(while, for)。讲解了如何使用and, or, not操作布尔值,以及在循环中使用continue和break。还探讨了函数的实现,包括参数类型、返回值以及装饰器的使用。最后,介绍了类的简单实现和继承概念。" 124682066,2391601,SV报文解析详解,"['网络', 'macos']

环境安装

参见Python快速入门(上)

python基础

条件判断

描述

条件判断可描述为:

  • 如果满足条件condition_1,则执行语句statement_1,否则执行statement_other
  • 如果满足条件condition_1,则执行语句statement_1,如果不满足条件condition_1而满足条件condition_2,则执行语句statement_2,如果不满足条件condition_1condition_2而满足条件condition_3,则执行statement_3,···所有条件都不满足,则执行statement_other
范例

饮水的最适温度为52-70

if-else 结构
water_temperature_todrink = 55
if water_temperature_todrink > 70:
    print('it is so hot to drink')
else:
    print('ok,it is fine')
output:ok,it is fine
if-elif-else 结构
#结构中可以添加多层elif
water_temperature_todrink = 40
if water_temperature_todrink > 70:
    print('it is so hot to drink')
elif water_temperature_todrink >55:
    print('ok,it is best to drink')
else:
    print('maybe it is a little cold')
output:maybe it is a little cold

嵌套结构
water_temperature_todrink = -10
if water_temperature_todrink > 70:
    print('it is so hot to drink')
elif water_temperature_todrink >55:
    print('ok,it is best to drink')
else:
    if water_temperature_todrink <0:
        print('it is just an ice cube, I can not drink it')
    else:
        print('maybe it is a little cold')
        
output:it is just an ice cube, I can not drink it

断言

结构如下

assert condition,statement

表示如果conditionFalse,则输出statement。断言是程序开发中调试的一种手段。

范例

person = "侯亮平"
condition = ( person != "侯亮平")
assert condition,"京州不允许这么牛逼的人物存在"

output:
AssertionError: 京州不允许这么牛逼的人物存在
条件说明

条件值可以为bool类型的True或是False,也可以是一个其他类型,这个其他类型有值,则代表为True,没有值,则为False.

范例

#有值的字典
condition_has_value = {'red':'#FF0000'}
if condition_has_value:
    print('True')
else:
    print('False')
output:True

#没有值的字典
condition_has_value = {}
if condition_has_value:
    print('True')
else:
    print('False')
output:False
布尔型变量做and or not运算
# a,b 同为bool,则and运算,两个都为真,则返回True,两个有一个不为真,则为返回False
a = True
b = False
condition = a and b
if condition:
    print('a and b is true')
else:
    print('a and b is false')
 output:a and b is false
# a,b 同为bool,则or运算,两个都为假,则返回False,两个有一个不为假,则为返回True
a = True
b = False
condition = a or b
if condition:
    print('a and b is true')
else:
    print('a and b is false')
output:a and b is true
非布尔型变量做and or not运算

返回值

a = {}
b = []
print('a bool value is {}'.format(bool(a)))
print('b bool value is {}'.format(bool(b)))
print('a and b is {}'.format(a and b))
print('a and b is {}'.format(a or b))

output:
a bool value is False
b bool value is False
a and b is {}
a or b is []

我们注意到如上代码中a and b is {}是返回字典,而a or b is []返回数组。这是因为and是只要判断第一个变量aFalse便可以得出a and b is False结论,所以不继续判断,直接返回a的值。
or在判断第一个变量aFalse后,继续判断第二个变量b,才能得出a or b is False的结论,所以返回b的值

and

a = [1,2,3]
b = 10
print(b and a)
output:[1,2,3]

or

a = 'hello'
b = {'hello':'nihao'}
print(a or b)
output:hello

not

b = 'one world one dream'
print(not b)
output:False

循环语句

while循环

范例

范例一

#生成一个长度为20的随机列表
#引入random模块
import random

random_nums = []
#只要condition满足,则执行whilie内的代码块
while len(random_nums) < 20:
	#将随机生成的数,添加到数组中
    random_nums.append(random.randint(1,10))
  
print(random_nums,len(random_nums))

output:
[6, 1, 8, 1, 6, 10, 1, 3, 4, 6, 5, 6, 4, 8, 3, 7, 10, 3, 10, 5] 20

范例二

#往列表中添加随机数,直到列表中含有数字8,则终止循环
random_nums = []
while 8 not in random_nums:
      random_nums.append(random.randint(1,10))
print(random_nums,len(random_nums))

output:[7, 10, 7, 9, 3, 5, 2, 3, 9, 3, 4, 3, 8] 13

使用场景
建议:能用for循环时,尽量不使用while循环
当循环的条件判断与数量没有关系时,则必须用while

死循环
#引入时间模块
import time
number = 0
#条件判断永远为True,循环体无限执行
while True:
	#休眠1s
    time.sleep(1)
    number += 1
    print('hello world {}'.format(number),end='\r')

output:
hello world 1
hello world 2
hello world 3
hello world 4
hello world *

for循环

范例

改写while循环中的范例一

#生成一个长度为20的随机列表
#引入random模块
import random

random_nums = []
#list(range(20))的output为 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
for i in range(20):
	random_nums.append(random.randint(1,10))
print(random_nums,len(random_nums))
	
output:
[5, 9, 6, 3, 4, 3, 10, 10, 5, 9, 4, 10, 1, 3, 4, 4, 6, 10, 10, 2] 20

范例二

#算出所有银行卡的总额,看看能否支付这个月的生活费用
#ICBC-工商 BOC-中国银行 ABC-农业银行 CMB-招商银行

cards = {'ICBC':100,'BOC':50,'ABC':1000,'CMB':220}
money_account = 0
#遍历字典
for index,bank in enumerate(cards):
	#根据键bank获取对应的value
    money_account += cards[bank]
print(money_account)

output:1370
 
循环中嵌套条件判断

还是以银行卡为例


cards = {'ICBC':100,'BOC':50,'ABC':1000,'CMB':220}
money_account = 0
#遍历字典 但是ABC银行卡是自己存起来的梦想基金,不能动,所以不能算在money_account里面
for index,bank in enumerate(cards):
	#根据键bank获取对应的value
    if bank != 'ABC':
        money_account += cards[bank]
    else:
        pass
print(money_account)

ouput:370

continue语句

跳过当次循环
continue语句重写循环中嵌套条件判断中的例子

cards = {'ICBC':100,'BOC':50,'ABC':1000,'CMB':220}
money_account = 0
#遍历字典 但是ABC银行卡是自己存起来的梦想基金,不能动,所以不能算在money_account里面
for index,bank in enumerate(cards):
	
    if bank == 'ABC':
    	continue
    #根据键bank获取对应的value
    money_account += cards[bank]
        
print(money_account)

ouput:370
break语句

终止循环体
也许你现在只是需要150元就可以确保你本月生活杂费,所以在遍历银行卡时,只要money_account >= 150之后,就不再需要继续遍历了,代码实现如下:

cards = {'ICBC':100,'BOC':50,'ABC':1000,'CMB':220}
money_account = 0
for index,bank in enumerate(cards):
    money_account += cards[bank]
    print('current cycle time {}'.format(index))
    if money_account >= 150:
    	print('will break this for cycle ')
    	break
        
print(money_account)

ouput:
#循环只执行了两次后,终止执行
current cycle time 0
current cycle time 1
will break this for cycle 
150
构建推导式

所谓推导式,就是从一个数据序列构建另一个序列的方法

范例一
不用推导式,从一个数据序列构建另一个序列的方法

range_numbers = list(range(10))
random_numbers = []
for number in range_numbers:
    random_numbers.append(number*10)
random_numbers

output:[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

范例二
列表推导式,将范例一用推导式实现

range_numbers = list(range(10))
random_numbers = [i*10 for i in range_numbers ]
random_numbers

output:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

范例三
字典推导式

range_numbers = list(range(10))
dict_numbers = {i:'A' for i in range_numbers }
dict_numbers

output:
{0: 'A',
 1: 'A',
 2: 'A',
 3: 'A',
 4: 'A',
 5: 'A',
 6: 'A',
 7: 'A',
 8: 'A',
 9: 'A'}

范例四

元组推导式

range_numbers = list(range(10))
turple_numbers = (i*10 for i in range_numbers )

list(turple_numbers)

output:[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]


函数

函数实现

var_1 = {'angle_1':30,'angle_2':60,'angle_3':90}
var_2 = {'color_1':'red','color_2':'blue','color_3':'yellow'}
var_3 = {'size_1':28,'size_2':56,'size_3':84}
print([ value for key,value in var_1.items() if value != 60])
print([ value for key,value in var_2.items() if value != 'red'])
print([ value for key,value in var_3.items() if value != 56])

output:
[30, 90]
['blue', 'yellow']
[28, 84]

将上述方法用函数实现

var_1 = {'angle_1':30,'angle_2':60,'angle_3':90}
var_2 = {'color_1':'red','color_2':'blue','color_3':'yellow'}
var_3 = {'size_1':28,'size_2':56,'size_3':84}

def print_values(dict_variable,value):
    print([v  for k,v in dict_variable.items() if v !=value])

print_values(var_1,60) 
print_values(var_2,'red')
print_values(var_3,56)

output:
[30, 90]
['blue', 'yellow']
[28, 84]
	

其中 def是函数标识符,print_values是函数名,dict_variable是函数的形参。*print_values(var_1,60) * 是方法的调用,var_1,60是实参。

函数定义

函数是组织好的,可重复使用的,能够完成特定功能的代码块,它是代码块的抽象。

位置参数

如上文所述print_values(var_1,60)严格按着函数定义的参数顺序传入参数,称为位置参数,位置参数不可变更传参顺序

#改变参数顺序,方法执行体仍是将60读作dict_varibles,所以一个常数是没有items方法的
print_values(60,var_1) 
output:
AttributeError: 'int' object has no attribute 'items'

相应的可以按着参数名称传入参数,此时可以不按顺序传参

关键字参数

#可以颠倒传参顺序
print_values(value='red',dict_variable=var_2)
output:
['blue', 'yellow']
参数值的改变

函数改变实参,不会改变传递进去的不可变类型的值

animal = 'deer'

def call_deer(animal):
	animal = 'horse'
	print('this is a horse'.format(deer))

call_deer(animal)
print(animal)

output:
this is a horse
deer

如上的代码,我们发现虽然在函数体中将animal设置成了horse,但是并没有改变函数体外原变量animal的值,其值仍是deer

函数改变实参,会改变传递进去的可变类型的值

animals = ['deer','bear','cat','tiger']

def rank_animals(animals):
    sorted_animals = animals.sort()
    print('these animals are {}'.format(animals))

rank_animals(animals)
print(animals)

output:
these animals are ['bear', 'cat', 'deer', 'tiger']
['bear', 'cat', 'deer', 'tiger']

如上的代码,我们发现在函数体中将animals排序,改变了函数体外原变量animals的顺序。

不建议对可变类型在函数内进行修改,建议用函数返回值进行重新赋值

参数的收集1
def collect_arguments(arg_1,arg_2,*args,**kwargs):
    print('arg_1 is {}'.format(arg_1))
    print('arg_2 is {}'.format(arg_2))
    print('args is {}'.format(args))
    print('kwargs is {}'.format(kwargs))

collect_arguments('arg_1','arg_2',{'arg_3':'thr','arg_4':'for'},arg_5='fiv',arg_6='six')

output:
arg_1 is arg_1
arg_2 is arg_2
args is ({'arg_3': 'thr', 'arg_4': 'for'},)
kwargs is {'arg_5': 'fiv', 'arg_6': 'six'}

其中args收集任意数量任意类型的参数,kwargs收集以keyword=value的形式传入的任意参数

将函数赋值给变量

some_variable = some_function的形式,将函数赋值给变量some_variable,则可以通过变量some_variable实现方法的调用
范例一

def welcom_someone(one_name):
    print('welcom,{}'.format(one_name))

welcom_somebody = welcom_someone

welcom_somebody('libai')

output:
welcom,libai

范例二

def inner_function():
    print('I am inner function')
    
def outer_function(inner_function):
    print('i am out function and give you my inner_function')
    return inner_function

func_1 = outer_function(inner_function)

#打印函数名称
print(func_1.__name__)

func_1()

output:
i am out function and give you my inner_function
inner_function
I am inner function
将函数作为返回值
def print_floats():
    return random.random()

print_floats()

output:
0.021075079500748495
装饰器

范例

#装饰器标识符
@decorator
def test():
    return random.random()

def decorator(fun):
	#包装函数,可接收任意数量参数
    def wrapper(*args,**kwargs):
		#判断参数是否为空
        if kwargs is not None:
 
            print(kwargs)
            for k,v in kwargs.items():
            	#如果含有location的key,则将取对应value的位数,并返回
                if k == 'location':
                    return round(fun(),v)
        return fun
     #返回包装函数
    return wrapper

f = decorator(test())
f.__name__
f(location=3)

#output:
{}
wrapper #f是wrapper函数
0.676 #返还了三位



类的简单实现

#class 为类的标识符,Person为类名
class Person:

	#初始化方法
	def __init__(self,name,age):
		#变量前面加_表示私有变量
		self._name = name
		self._age = age
	#名字的获取方法
	def get_name(self):
		return self._name
	#名字的设置方法
	def set_name(self,name):
		self._name = name
#实例化Person方法,传入初始化方法的两个参数名字和年龄
person = Person('libai',54)
#person是Person的一个对象
person
#output:<__main__.Person at 0x109351f98>

#调用person的获取和设置名子的方法
person.get_name()
#output:'libai'
person.set_name('dufu')
person.get_name()
#output:'dufu'

#调用类中不存在的方法
person.get_score()
#output:AttributeError: 'Person' object has no attribute 'get_score'

类的继承

现在创建个Student类,使之继承Person类,并创建设置和获取分数的方法

class Student(Person):
    def set_score(self,score):
        self._score = score
        
    def get_score(self):
        return self._score
student = Student('yanhui','32')
student
#output:<__main__.Student at 0x108f1c748>

#获取名字
student.get_name()
#output:'yanhui'

#获取和设置分数
student.set_score(100)
student.get_score()
#output:100

  1. [*args and **kwargs in python explained]https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ ↩︎

内容概要:本文介绍了一个关于超声谐波成像中幅度调制聚焦超声所引起全场位移和应变的分析模型,并提供了基于Matlab的代码实现。该模型旨在精确模拟和分析在超声谐波成像过程中,由于幅度调制聚焦超声作用于生物组织时产生的力学效应,包括全场的位移与应变分布,从而为医学成像和治疗提供理论支持和技术超声谐波成像中幅度调制聚焦超声引起的全场位移和应变的分析模型(Matlab代码实现)手段。文中详细阐述了模型构建的物理基础、数学推导过程以及Matlab仿真流程,具有较强的理论深度与工程应用价值。; 适合人群:具备一定声学、生物医学工程或力学背景,熟悉Matlab编程,从事医学成像、超声技术或相关领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①用于超声弹性成像中的力学建模与仿真分析;②支持高强度聚焦超声(HIFU)治疗中的组织响应预测;③作为教学案例帮助理解超声与组织相互作用的物理机制;④为相关科研项目提供可复用的Matlab代码框架。; 阅读建议:建议读者结合超声物理和连续介质力学基础知识进行学习,重点关注模型假设、偏微分方程的数值求解方法及Matlab实现细节,建议动手运行并修改代码以加深理解,同时可拓展应用于其他超声成像或治疗场景的仿真研究。
### 关于PAT Basic Level Practice的测试点及题目解析 #### 题目难度分级 PAT(Programming Ability Test)是由浙江大学举办的计算机程序设计能力考试,分为不同级别。其中乙级即Basic Level主要面向初学者,考察基本编程技能[^1]。 #### 测试点特点 对于PAT Basic Level中的某些特定题目而言,其测试点设置较为严格。例如,在处理字符串匹配类问题时,需要注意算法逻辑中何时应当终止循环以防止不必要的重复计算;而在涉及数值运算的问题里,则可能因为边界条件而增加复杂度[^3]。 #### 编程语言的选择影响 值得注意的是,尽管大部分简单题目可以作为学习某种新语言的良好实践材料,但在实际操作过程中可能会遇到由于所选语言特性而导致难以通过全部测试点的情况。比如Java在面对部分效率敏感型试题时表现不佳,这可能是由于该语言本身的执行速度相对较慢以及内存管理方式等因素造成的。因此有时不得不转而采用其他更适合解决此类问题的语言版本来完成解答[^2]。 ```cpp #include<bits/stdc++.h> using namespace std; int a[100000]; int c=1; void getPrime(){ int flag=0; for(int i=2;i<105000;i++){ flag=1; for(int j=2;j<=sqrt(i);j++){ if(i%j==0){ flag=0; break; } } if(flag==1) a[c++]=i; } } int main(){ int m,n,i,t=1; scanf("%d %d",&m,&n); getPrime(); for(i=m;i<=n;i++){ if(t%10==1){ printf("%d",a[i]); t++; }else{ printf(" %d",a[i]); t++; } if((t-1)%10==0) printf("\n"); } return 0; } ``` 上述C++代码展示了如何实现一个简单的质数打印功能,并且针对输出格式进行了特殊处理以满足特定要求。这段代码很好地体现了编写高效解决方案的重要性,尤其是在应对像PAT这样的在线评测系统时[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值