دستور switch در پایتون :
دستور Switch در پایتون : یک دستور چند شاخه ایی می باشد که مقدار یک متغیر را با مقادیر مشخص شده در دستورات CASE مقایسه می کند .
زبان پایتون دستور switch ندارد
پایتون از نگاشت دیکشنری برای پیاده سازی دستور switch استفاده می کند .
مثال :
1 2 3 4 5 6 7 8 9 10 11 12 |
function(argument){ switch(argument) { case 0: return "This is Case Zero"; case 1: return " This is Case One"; case 2: return " This is Case Two "; default: return "nothing"; }; }; |
کد معادل پایتون برای کد بالا برابر است با :
1 2 3 4 5 6 7 8 9 10 11 12 |
def SwitchExample(argument): switcher = { 0: " This is Case Zero ", 1: " This is Case One ", 2: " This is Case Two ", } return switcher.get(argument, "nothing") if __name__ == "__main__": argument = 1 print (SwitchExample(argument)) |
مثال پایتون 2
کدهای بالا همه برای پایتون 3 بودند اما اگر بخواهیم آن ها را در پایتون 2 اجرا کنید از کدهای زیر استفاده می کنیم .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# If Statement #Example file for working with conditional statement # def main(): x,y =2,8 if(x < y): st= "x is less than y" print st if __name__ == "__main__": main() # How to use "else condition" #Example file for working with conditional statement # def main(): x,y =8,4 if(x < y): st= "x is less than y" else: st= "x is greater than y" print st if __name__ == "__main__": main() # When "else condition" does not work #Example file for working with conditional statement # def main(): x,y =8,8 if(x < y): st= "x is less than y" else: st= "x is greater than y" print st if __name__ == "__main__": main() # How to use "elif" condition #Example file for working with conditional statement # def main(): x,y =8,8 if(x < y): st= "x is less than y" elif (x == y): st= "x is same as y" else: st="x is greater than y" print st if __name__ == "__main__": main() # How to execute conditional statement with minimal code def main(): x,y = 10,8 st = "x is less than y" if (x < y) else "x is greater than or equal to y" print st if __name__ == "__main__": main() # Nested IF Statement total = 100 #country = "US" country = "AU" if country == "US": if total <= 50: print "Shipping Cost is $50" elif total <= 100: print "Shipping Cost is $25" elif total <= 150: print "Shipping Costs $5" else: print "FREE" if country == "AU": if total <= 50: print "Shipping Cost is $100" else: print "FREE" #Switch Statement def SwitchExample(argument): switcher = { 0: " This is Case Zero ", 1: " This is Case One ", 2: " This is Case Two ", } return switcher.get(argument, "nothing") if __name__ == "__main__": argument = 1 print SwitchExample(argument) |