py4_control structure

本文介绍了Python程序的控制结构,包括分支与循环结构,特别是简洁的条件判断和异常处理。异常处理部分讲解了try/except的用法,并强调了它与if/else的区别。此外,还概述了Python的随机库,列举了如seed、random、randint等基本随机函数的使用,强调了seed在重现实验中的重要性,并提及了其他如shuffle等实用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • The Control Structure of Programs

Branch & Loop Structure
Compact type: &lt; c o m m a n d 1 &gt; &lt;command1&gt; <command1> if &lt; c o n d i t i o n &gt; &lt;condition&gt; <condition> else &lt; c o m m a n d 2 &gt; &lt;command2&gt; <command2>, means if condition is judged true, do the command1, and if condition is judged false, do the command2.
Exception Handling: try/except combination, ATTENTION: try/except is different from if/else in Python, it’s NameError.

After the exception type is annotated, it only responds to THIS exception, and the name of the exception is same as the variable.
The high-level of using Exception Handling:
try:
&lt; c o m m a n d 1 &gt; &lt;command1&gt; <command1>
except:
&lt; c o m m a n d 2 &gt; &lt;command2&gt; <command2>
else:
&lt; c o m m a n d 3 &gt; &lt;command3&gt; <command3>
finally:
&lt; c o m m a n d 4 &gt; &lt;command4&gt; <command4>
The commands in Finally Struct must be executed, the commands in Else Struct will be executed when exception do not happen.

  • The overview of Random Library

Basic Random Function:
seed(a= None):Initialize the given-random number seed, default value is the time of system. e.g: random.seed(10) produce the sequence of the seed 10.
random(): generate a random decimal from 0.0 to 1.0.
WARNING: Using seed can get a accurate number of time, so we can playback the experiment we have done before, if don’t use the seed, the default value–system number–is a value accurate to the millisecond and it’s very difficult to recurrent.
randint(a, b): generate a random integer from a to b.
randrange(m, n, [k]): generate a random integer from m to n according to the step k, parameter k is alternate.
getrandbits(k): generate a random integer which is k bits long.
uniform(a, b): generate a random decimal from a to b, can reach the 16byte precision.

choice(seq): choose a element randomly from the sequence seq.
shuffle(seq): sort the elements in the sequence seq randomly, return the chaos-shuffled sequence.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值