計算機中的開關(guān)案例聲明 編程語言是一種功能強大的工具,它使程序員可以根據(jù)表達式或變量的結(jié)果完全控制程序的流程。開關(guān)條件特別用于在程序運行期間執(zhí)行與表達式結(jié)果有關(guān)的不同代碼塊。如果結(jié)果是某個值,則程序?qū)?zhí)行特定的過程,如果結(jié)果是另一個值,則程序?qū)?zhí)行另一條過程,依此類推。首先向您展示switchcase語句如何在Java中起作用,以便您了解在Java中期望得到什么。
Pythonswitchcase語句,盡管實現(xiàn)方式可能有所不同,但概念仍然相同。繼續(xù)學(xué)習(xí)本教程您可以使用任何喜歡的PythonIDE或代碼編輯器。Java切換案例演示,介紹如何在一年中的幾個月之間進行切換以及如果在switch語句中找不到匹配項,則提供默認結(jié)果。
publicstaticvoidswitch_demo(String[]args){intmonth=7;
StringmonthString;switch(month){case1: monthString="January";break;case2: monthString="February";break;case3: monthString="March";break;case4: monthString="April";break;case5: monthString="May";break;case6: monthString="June";break;case7: monthString="July";break;case8: monthString="August";break;case9: monthString="September";break;case10:monthString="October";break;case11:monthString="November";break;case12:monthString="December";break;default:monthString="Invalidmonth";break;
}
System.out.println(monthString);
}
讓我們分解上面的switchcase語句:
步驟1:編譯器首先為switch語句生成一個跳轉(zhuǎn)表
步驟2:switch語句僅對變量或表達式求值一次。
步驟3:switch語句查看評估的結(jié)果,并根據(jù)結(jié)果決定執(zhí)行哪個代碼塊。
Python開發(fā)人員GuidoVanRossum相信一種簡單的編程語言可以繞開其他編程語言中發(fā)現(xiàn)的系統(tǒng)漏洞和障礙,因此他想創(chuàng)建一種具有更復(fù)雜的語法短語的簡單語法。
他從未想象過,如今,Python編程語言可以成為設(shè)計科學(xué)機器學(xué)習(xí)應(yīng)用程序的標(biāo)準(zhǔn)語言時需要使用的編程語言。
在Python中切換案例
Python 沒有內(nèi)置的switch語句,就像您可以找到的編程語言一樣 取而代之的是,PHP和Java確實像Python程序員一樣會使用if-else-if塊,但由于跳轉(zhuǎn)表比if-else-if梯形圖更有效,因此切換案例的使用效率很高。
這樣做的原因是,它不是按順序評估每個條件,而是查看評估的表達式或變量,然后直接跳轉(zhuǎn)到要執(zhí)行的代碼的相關(guān)分支。
使用if-else-if梯子進行切換,以查找圓柱體的表面積,文字區(qū)域和體積。
defswitch():
r=int(input("EnterRadius:"))
h=int(input("EnterHeight:"))
print("Press1forSurfaceArea press2forLiteralArea press3forVolume ")
option=int(input("youroption:"))ifoption==1:
result=2*3.17*r*(r+h)
print(" SurfaceAreaOfCylinder=",result)elifoption==2:
result=2*3.17*r*h
print("LiteralAreaOfCylinder=",result)elifoption==3:
result=3.17*r*r*h
print("VolumeOfCylinder=",result)else:
print("Incorrectoption")
switch()
說明:在上面的示例中,如果選項為1,則計算圓柱體的表面積;如果選項為2,則計算文字表面積,最后計算選項3,計算圓柱體的體積。
使用類切換案例語句以將文字轉(zhuǎn)換為字符串“month”
classPythonSwitchStatement:defswitch(self,month):
default="Invalidmonth"returngetattr(self,'case_'+str(month),lambda:default)()defcase_1(self):return"January"defcase_2(self):return"February"defcase_3(self):return"March"defcase_4(self):return"April"defcase_5(self):return"May"defcase_6(self):return"June"defcase_7(self):return"July"defcase_8(self):return"August"defcase_9(self):return"September"defcase_10(self):return"October"defcase_11(self):return"November"defcase_12(self):return"December"
s=PythonSwitchStatement()
print(s.switch(1))
print(s.switch(3))
print(s.switch(13))
Theoutputwillbe:
___________________
January
March
Invalidmonth
___________________
說明:首先,創(chuàng)建一個名為PythonSwitchStatement定義一個switch()方法。它還針對特定的不同情況定義了其他功能。
的switch()方法采用參數(shù)'month'并將其轉(zhuǎn)換為字符串,然后將其附加到大小寫文字中,然后將其傳遞給getattr()方法,然后返回該類中可用的匹配函數(shù)。
如果找不到匹配項,則getattr()方法將返回lambda函數(shù)作為默認值。
字典映射替換
#Functiontoconvertnumberintostring
#Switcherisdictionarydatatypehere
defnumbers_to_strings(argument):
switcher={0:"zero",1:"one",2:"two",
}
#get()methodofdictionarydatatypereturns
#valueofpassedargumentifitispresent
#indictionaryotherwisethesecondargumentwill
#beassignedasthedefaultvalueofthepassedargumentreturnswitcher.get(argument,"nothing")
#Driverprogramif__name__=="__main__":
argument=0
printnumbers_to_strings(argument)
使用字典映射功能切換器的示例
defone():return"January"deftwo():return"February"defthree():return"March"deffour():return"April"deffive():return"May"defsix():return"June"defseven():return"July"defeight():return"August"defnine():return"September"deften():return"October"defeleven():return"November"deftwelve():return"December"defnumbers_to_months(argument):
switcher={1:one,2:two,3:three,4:four,5:five,6:six,7:seven,8:eight,9:nine,10:ten,11:eleven,12:twelve
}#Getthefunctionfromswitcherdictionary
func=switcher.get(argument,lambda:"Invalidmonth")#Executethefunctionprintfunc()
使用字典映射返回值的示例
b={'a':122,'b':123,'c':124,'d':125
}#takeuserinput
inp=input('inputacharacter:')#-1isthedefaultvalueiftherearenokeysthatmatchtheinput
print('Theresultforinpis:',b.get(inp,-1))
使用字典映射來切換星期幾
defweek(i):
switcher={0:'Sunday',1:'Monday',2:'Tuesday',3:'Wednesday',4:'Thursday',5:'Friday',6:'Saturday'
}returnswitcher.get(i,"Invaliddayoftheweek")
然后撥打week()使用不同的值來找出星期幾。
即week(2),輸出將是星期二,week(4),輸出將是星期四,而week(5.5)將輸出“星期幾無效”
結(jié)論
Python沒有內(nèi)置的switch-case構(gòu)造,但是您可以使用字典映射代替switchcase。
Python開發(fā)人員出于充分的理由不包括switch-case結(jié)構(gòu)。
盡管許多程序員和開發(fā)人員一直在努力在Python中包含切換用例構(gòu)造,但是無論是否考慮他們的建議,Python切換用例替代方案都可以提供更好的服務(wù)。想了解更多關(guān)于Python的信息,請繼續(xù)關(guān)注中培偉業(yè)。