Python Learning Day 60: Mastering pass, while/for Loops, break‑continue and String Operations
This tutorial‑style note walks through Python’s pass statement, the mechanics of while and for loops (including nested loops and common pitfalls), the use of break and continue, and a comprehensive overview of string creation, slicing, case conversion, searching, replacement, and encoding, all illustrated with concrete code examples and expected outputs.
This entry is part of a daily Python learning series (Day 60) and begins with the pass keyword, explaining that it serves only as a placeholder to keep a statement syntactically complete. The author shows a simple example where pass is used inside an if block and demonstrates the program’s output.
age = int(input("请输入你的年龄:"))
if age > 16:
# print("欢迎光临游戏城")
pass
print("hello world")Output:
请输入你的年龄:20
hello worldThe note then introduces the while loop, describing its three parts: initial condition, loop‑body condition, and update condition. It notes that Python lacks a do‑while construct and does not support ++/-- operators. A basic counting loop is provided:
num = 0
while num < 10:
print("hello world")
num += 1Output:
hello world
hello world
... (10 times)Several practical exercises follow:
Print numbers 1‑100.
Calculate the sum of 1‑100 (result 5050).
Sum of even numbers between 1‑100 (result 2550).
Sum of odd numbers between 1‑100 (result 2500).
A discussion of infinite loops ( while True) is included, with a username/password validation example that breaks when correct credentials are entered.
while True:
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "张" and password == "123456":
print("恭喜您,账号和密码正确,欢迎光临")
break
else:
print("用户名和密码错误,请重新输入")The article then covers the for loop in Python, noting its for ... in ... syntax, the use of range, and how iterable objects (strings, lists, tuples, sets) can be traversed. Example:
# output 1‑10
for i in range(1, 11):
print(i)
# iterate over a list
for i in [12, 34, 5, 6, 86, 42]:
print(i)
# iterate over a string
for ch in "hello":
print(ch)Next, the break and continue statements are explained. break terminates the entire loop, while continue skips to the next iteration. Sample code shows both behaviours:
# break example
num = 0
while num < 5:
if num == 3:
num += 1
break
print(num)
num += 1
# output: 0 1 2
# continue example
num = 0
while num < 5:
if num == 3:
num += 1
continue
print(num)
num += 1
# output: 0 1 2 4Nested loops are introduced for generating tabular data such as a 3×4 asterisk grid and the 9×9 multiplication table. The author provides both for ‑nested and while ‑nested implementations, emphasizing that the outer loop controls rows and the inner loop controls columns.
# for‑nested example (3 rows, 4 columns)
for i in range(3):
for j in range(4):
print("*", end="\t")
print()
# while‑nested example (same grid)
i = 0
while i < 3:
j = 0
while j < 4:
print("*", end="\t")
j += 1
print()
i += 1The note then shifts to string fundamentals : declaring strings with single, double, triple quotes; embedding quotes; escape characters ( \, \n, \t); raw strings ( r"...") and f‑strings for interpolation. Example outputs illustrate each case.
# different quote styles
a = "hello"
b = 'world'
c = '''床前明月光'''
d = """疑是地上霜"""
print(a, b, c, d)
# output: hello world 床前明月光 疑是地上霜
# escape characters
e = "你\"好吗?"
print(e) # 你"好吗?
f = "欢迎学习
Python"
print(f) # 两行输出
g = "今天天气\t很晴朗!"
print(g) # 带制表符String slicing syntax string[start:end:step] is explained with examples showing inclusive start, exclusive end, and step values, including reverse slicing.
str2 = "welcome to beijing"
print(str2[0:3]) # wel
print(str2[1:]) # elcome to beijing
print(str2[:4]) # welc
print(str2[1:4:2]) # ec
print(str2[::-1]) # gnijieb ot emoclewLength and count operations ( len(), str.count()) are demonstrated, followed by case‑conversion methods ( upper(), lower(), swapcase(), title()) and their outputs.
s = " i Miss you VERY much"
print(s.upper()) # I MISS YOU VERY MUCH
print(s.lower()) # i miss you very much
print(s.swapcase())# i MISs YOU very MUCH
print(s.title()) # I Miss You Very MuchString searching methods ( find(), index(), rfind()) are shown with both successful and failing cases, illustrating the return of -1 versus raising an exception.
txt = "abcdefghijklmn123987654zxyslt"
print(txt.find('l')) # 11
print(txt.find('o')) # -1
print(txt.index('a')) # 0
print(txt.rfind('l')) # 28
print(txt.find('l',3,12)) # 11Replacement ( replace()) and boolean checks ( isupper(), islower(), isdigit(), istitle(), isalpha()) are covered with sample inputs and outputs.
msg = "这个店铺的商品很垃圾,这么垃圾的产品怎么能用来卖呢?"
print(msg.replace("垃圾", "**")) # 替换全部
print(msg.replace("垃圾", "**", 1)) # 替换一次
print("helloWORLD".isupper()) # False
print("HELLO".isupper()) # True
print("hello".islower()) # True
print("123".isdigit()) # True
print("Hello World".istitle()) # TrueFinally, the article touches on encoding/decoding ( encode() with UTF‑8 and GBK) and ASCII conversion using chr() and ord(), showing the byte representations of a Chinese string and converting numeric codes to characters.
text = "我爱你中国"
print(text.encode()) # default utf‑8 bytes
print(text.encode('gbk')) # GBK bytes
print(chr(97)) # a
print(ord('c')) # 99Throughout the note, each concept is introduced, demonstrated with a concrete code snippet, and followed by the exact output, allowing readers to follow the reasoning process step‑by‑step.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
