xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python & dict & switch...case All In One

Python & dict & switch...case All In One

💩 Python 中是没用switch语句的,这应该是体现 Python 大道至简的思想,Python 中一般多用字典来代替 Switch 来实现。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 22:12:43 2019

@author: xgqfrms-mbp
"""

#coding: utf-8
from __future__ import division
  
def jia(x,y):
    print(x+y);
  
def jian(x,y):
    print(x-y);
  
def cheng(x,y):
    print(x*y);
  
def chu(x,y):
    print(x/y);
  
operator = {'+':jia,'-':jian,'*':cheng,'/':chu};
  
def f(x,o,y):
    operator.get(o)(x,y);
  
f(3,'+',2);

object === dict

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 22:12:43 2019

@author: xgqfrms-mbp
"""

#coding: utf-8
from __future__ import division
  
def jia(x,y):
    print(x+y);
  
def jian(x,y):
    print(x-y);
  
def cheng(x,y):
    print(x*y);
  
def chu(x,y):
    print(x/y);
  
operator = { '+': jia, '-': jian, '*': cheng, '/': chu, };

# operator = {
#   '+ : jia,
#   '-' : jian,
#   '*' : cheng,
#   '/' : chu
# };
# SyntaxError: EOL while scanning string literal

def f(x,o,y):
    operator.get(o)(x,y);

f(3,'+',2);
# 5

IDE

Spyder IDE

https://www.spyder-ide.org/

Anaconda

https://www.anaconda.com/download/

demos

python no switch bug 💩

from typing import List

class Solution:
  def fizzBuzz(self, n: int) -> List[str]:
    result = []
    for i in range(1, n + 1):
      if(i % 15 == 0):
        result.append("FizzBuzz")
      elif(i % 5 == 0):
        result.append("Buzz")
      elif(i % 3 == 0):
        result.append("Fizz")
      else:
        result.append(str(i))
    print("result =", result)
    return result


solution = Solution()
# solution.fizzBuzz(3)
# solution.fizzBuzz(5)
solution.fizzBuzz(15)

""" 

$ py3 ./412_fizz-buzz.py
result = ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']

Input: n = 3
Output: ["1","2","Fizz"]

Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

"""

https://leetcode.com/problems/fizz-buzz/description/

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

2023.07.01 update 🚀

在 Python 中没有 switch...case 语句,但在 Python3.10 版本添加了 match...case,功能也类似,详见下文。

Python 3.10 增加了 match...case 的条件判断,不需要再使用一连串的 if-else 来判断了。

match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_ 可以匹配一切。

#!/usr/bin/env python3
# coding: utf8

__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__github__ = 'https://github.com/xgqfrms/Raspberry-Pi'
__git__ = 'https://github.com/xgqfrms/Raspberry-Pi.git'
__copyright__ = """
  Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""

"""

/**
 * 
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-01-01
 * @updated 2023-07-01
 * 
 * @description 
 * @augments 
 * @example 
 * @link https://www.runoob.com/python3/python3-conditional-statements.html#:~:text=2%20%E5%92%8C%203-,match...case,-Python%203.10%20%E5%A2%9E%E5%8A%A0
 * 
 */

"""

# Match statements require Python `3.10` or newer Pylance ❌

def http_error(status):
  match status:
    case 400:
      return "Bad request"
    case 404:
      return "Not found"
    case 418:
      return "I'm a teapot"
    case _:

      return "Something's wrong with the internet"

def test():
  status = 400
  message = http_error(status)
  print("message =", message)

test()

""" 
$ py3 ./match...case.py

"""

image

https://www.runoob.com/python3/python3-conditional-statements.html

online free Python REPL

https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3

refs

https://docs.python.org/3/tutorial/index.html

https://code.visualstudio.com/docs/languages/python

https://pypi.org/search/?c=Operating+System+%3A%3A+MacOS



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2019-01-30 22:19  xgqfrms  阅读(256)  评论(12编辑  收藏  举报