1.用戶輸入
1.1 函數input()
input()讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入後,Python將其存入變量中,以方便使用。
a = input("輸入一些東西,我再返回給你:")
print(a)
b = '輸入一些東西,'
b += "我再返回給你:"
a = input(b)
print(a)
1.2 使用int()來獲取數值輸入
使用input()時,Python將用戶解讀爲字符串。函數int()可將輸入值視爲數值,將數字的字符串表示轉換爲數值表示
b = input("你幾歲啊?")
a = int(b)
if a >= 10:
print("好噠。")
1.3 求模運算符
兩個相除並返回餘數。
print(4%3)
k = 7%4
print(k)
2.while循環
2.1 使用while循環
a = 1
while a <= 5:
print(a)
a += 1
2.2 讓用戶選擇如何退出
a = "請輸入:"
b = ""
while b != "quit":
b = input(a)
if b != "quit":
print(b)
2.3 使用標誌
a = "請輸入:"
b = ""
aa = True
while aa:
b = input(a)
if b == "quit":
aa = False
else:
print(b)
2.4 使用Break退出循環
a = "請輸入:"
b = ""
while b != "quit":
b = input(a)
if b == "quit":
break
else:
print(b)
2.5 在循環中使用continue
a = 1
while a <= 10:
a += 1
if(a%2==0):
continue;
else :
print(a)
3.使用while循環來處理列表和字典
3.1 在列表之間移動元素
a = ['x','y','z']
b = []
while a:
aa = a.pop()
print("用戶: "+aa)
b.append(aa)
print("\nb的用戶: ")
while b:
bb = b.pop()
print(bb)
3.2 刪除包含特定值的所有列表元素
a = ['x','y','z','x','r','u']
print(a)
while 'x' in a:
a.remove('x')
print(a)
3.3 使用用戶輸入來填充字典
a = {}
aa = True
while aa:
s = input("你的出生年份?")
q = input("你的出生月份?")
a[s] = q
r = input("還有小朋友嗎?")
if r == 'no':
break
print("顯示結果:")
for s,q in a.items():
print("出生日期:"+ s + " " + q)
[點擊並拖拽以移動]