目錄
用戶輸入
input()函數 字符串輸入
name = input("Please enter your name: ") #括號內爲輸入時的提示語
print("Hello, " + name + "!")
int()函數 數值轉化
nums = input("nums?")
num = int(nums) #輸入 ”43“ 則 傳遞給num爲數值43 ;輸入小數等會出錯
print(nums,age)
#python中的字符數字之間的轉換函數
int(x [,base ]) #將x轉換爲一個整數
long(x [,base ]) #將x轉換爲一個長整數
float(x ) #將x轉換到一個浮點數
complex(real [,imag ]) #創建一個複數
str(x ) #將對象 x 轉換爲字符串
repr(x ) #將對象 x 轉換爲表達式字符串
eval(str ) #用來計算在字符串中的有效Python表達式,並返回一個對象
tuple(s ) #將序列 s 轉換爲一個元組
list(s ) #將序列 s 轉換爲一個列表
chr(x ) #將一個整數轉換爲一個字符
unichr(x ) #將一個整數轉換爲Unicode字符
ord(x ) #將一個字符轉換爲它的整數值
hex(x ) #將一個整數轉換爲一個十六進制字符串
oct(x ) #將一個整數轉換爲一個八進制字符串
求模運算符 %
yushu = 6 % 4 #得到餘數爲2
while循環
while循環代碼結構
while 條件 :
循環體 #循環體使條件不滿足時或者執行break語句,循環纔會結束
退出while循環的辦法:
- 改變while循環的條件 比如利用一個條件變量,在循環體中改變該變量,直到變量不再滿足條件
- 在循環體中加入判斷語句,當不符合時,執行break語句
while循環中的continue語句
while true:
代碼1
if 條件1:
continue
代碼2
當條件1爲真時,代碼2不會執行,但會繼續循環。
while循環的簡單應用
1. 列表循環
List = ['apple','peanut','banana']
while List:
print(List.pop().title()) #輸出順序從末尾開始
2. 列表刪某一元素
List = ['apple','peanut','banana','apple']
while ‘apple’ in List:
List.remove('apple')
print(List)
可以觀察到,每次刪除只刪除一個。最終會刪除所以的‘apple’。
3. 用戶輸入字典
Dicts = {}
active = True
while active:
name = input("輸入名字:")
sage = input("輸入年齡:")
age = int(sage)
Dicts[name] = age
repeat = input("繼續嗎? 回車繼續,輸入no結束 ")
if repeat=='no':
break # 或者active = False
print("--------Dicts--------")
for name, age in Dicts.items():
print(name + " is " + str(age) +" years old.")