本文共 2251 字,大约阅读时间需要 7 分钟。
while循环是Python中常用的循环控制结构,用于执行重复操作。以下是while循环的基本使用方法和示例:
count = 1while count <= 10: if count == 7: count += 1 continue # 跳过else部分,直接回到while条件检查 else: print(count) count += 1print('end') count <= 10,表示当count小于等于10时继续执行循环。count是否等于7。count等于7,执行count += 1后使用continue语句,直接跳过else部分,返回到while条件检查。count不等于7,则执行print(count)和count += 1,然后继续循环。count超过10时,循环结束,执行print('end')。count = 1while count <= 10: if count != 7: print(count) count += 1 else: count += 1print('end') break语句,否则循环提前终止。and或or,因为这些逻辑运算符可能导致循环条件错误。字符串格式化是将变量值嵌入到字符串中的一种方法,常用于打印或显示信息。Python提供了两种主要的字符串格式化方法:%格式和.format()方法。
%格式:name = input('请输入姓名:')age = input('请输入年龄:')job = input('请输入职业:')hobby = input('请输入爱好:')msg = '''---------info of alex li--------name: %ssage: %sjob: %shobby: %s---------end-------'''print(msg % (name, age, job, hobby)) .format()方法:name = '我叫{0},年龄{1}'.format('xxx', 99)print(name) % 符号,需要使用%%来表示一个 %。 name = 'alex'template = '%s手机的电量是100%%' % nameprint(template)
运算符是编程中的基本元素,用于执行算术运算、赋值操作和逻辑判断。以下是常见运算符的分类和示例:
| 运算符 | 描述 | 示例 |
|---|
a + ba - ba * b / | 除法,返回浮点数结果 | b / a % | 取模,返回除法的余数 | b % a // | 取整除,返回向下取接近除数的整数 | 9 // 2 ** | 幂运算,返回x的y次幂 | a ** b| 运算符 | 描述 | 示例 |
|---|---|---|
| = | 简单的赋值运算符 | c = a + b |
| += | 加法赋值运算符 | c += a |
| -= | 减法赋值运算符 | c -= a |
c *= a /= | 除法赋值运算符 | c /= a %= | 取模赋值运算符 | c %= a //= | 取整除赋值运算符 | c //= a **= | 幂赋值运算符 | c **= a| 运算符 | 描述 | 示例 |
|---|---|---|
| and | 布尔"与" | a and b |
| or | 布尔"或" | a or b |
| not | 布尔"非" | not (a and b) |
notandorvalue1 = 0 or 1 # 1value2 = 8 or 10 # 8value3 = 0 or 9 or 8 # 9print(value1, value2, value3)
value1 = 1 and 9 # 9value2 = 1 and 0 # 0value3 = 0 and 7 # 0value4 = 0 and "" # 0value5 = 1 and 0 and 9 # 0print(value1, value2, value3, value4, value5)
value = 1 and 9 or 0 and 8print(value) # 9
编码是将字符转换为数字值的过程,常用于处理文本数据。在Python中,常用的编码包括ASCII、Unicode、UTF-8等。
转载地址:http://dwfwk.baihongyu.com/