while True:
a,b=input("Enter two numbers (sperated by a comma): ")
operator=raw_input("Do you want to add, subtract, multiply, or divide? ")
if operator=="divide":
print "Your answer is", a/b
if operator=="multiply":
print "Your answer is", a * b
if operator=="add":
print "Your answer is", a + b
if operator=="subtract":
print "Your answer is", a - b
repeat=raw_input("Do you want to perform another calculation(yes or no)? ")
if repeat == 'no':
break
雖然真正的永續循環,它可以通過關鍵字突破(它打破了最近的循環(for或while))被打破。
當處理來自用戶的輸入以確定條件時,最好檢查來自用戶的輸入是以「y」(是)開始還是以「n」(否)開始,因爲用戶可能會輸入y的是他可能惹的資本,下面是實現此代碼:
while True:
a,b=input("Enter two numbers (sperated by a comma): ")
operator=raw_input("Do you want to add, subtract, multiply, or divide? ")
if operator=="divide":
print "Your answer is", a/b
if operator=="multiply":
print "Your answer is", a * b
if operator=="add":
print "Your answer is", a + b
if operator=="subtract":
print "Your answer is", a - b
repeat=raw_input("Do you want to perform another calculation(yes or no)? ")
if repeat.lower.startswith('n'):
break
「重複」是一個字符串,它有一個方法(類同功能)被稱爲「低」,則此方法返回小寫字母表示,那麼你可以通過使用另一個叫做startswith的方法來檢查小寫表示(也是一個字符串)是否以字母「n」開頭。只要答案是「是」(不區分大小寫)
repeat = "yes"
while repeat.lower().strip() == 'yes':
a,b=input("Enter two numbers (sperated by a comma): ")
operator=raw_input("Do you want to add, subtract, multiply, or divide? ")
if operator=="divide":
print "Your answer is", a/b
if operator=="multiply":
print "Your answer is", a * b
if operator=="add":
print "Your answer is", a + b
if operator=="subtract":
print "Your answer is", a - b
repeat=raw_input("Do you want to perform another calculation(yes or no)? ")
這將循環:
可以把真實的情況 – 2015-04-03 11:39:55