多项选择菜单 Python

N3R*_*R0X -2 python python-3.x

我尝试做一个选择菜单,每个菜单做不同的事情,例如如果你选择数字1,会很好,但是如果你尝试选择2或其他数字,首先会尝试运行1,而我不想要这个。有没有办法让每个选项“独立”?

示例(这将起作用):

choice = input ("""
    1. Make thing 1
    2. Make thing 2
    3. Make thing 3
    4. Exit

    Please select your choice:""")

if choice == "1":
    print("thing 1")
if choice == "2":
    print("thing 2")
if choice == "3":
    print("thing 3")
if choice == "4":
    print("thing 4")
Run Code Online (Sandbox Code Playgroud)

但是,如果 1 以后有更多编码,并且您想使用选项 2,python 也将运行 1...

Sco*_*ott 5

Python lacks a switch/case statement (like C/C++) in which you CAN have it perform multiple (adjacent) case conditions, and then have it break before processing further cases. In Python you'll need to simulate using if-elif-else statements, perhaps utilizing comparison operators (like ==, <) and/or boolean operators ( like and, or) in conditionals accordingly.

Here's an example of a C language switch/case switch/case in python:

switch(n) {
  case 0:
    printf("You typed zero.\n");
    break;
  case 1:
  case 9:
    printf("n is a perfect square\n");
    break;
  case 2:
    printf("n is an even number\n");
  case 3:
  case 5:
  case 7:
    printf("n is a prime number\n");
    break;
  case 4:
    printf("n is a perfect square\n");
  case 6:
  case 8:
    printf("n is an even number\n");
    break;
  default:
    printf("Only single-digit numbers are allowed\n");
  break;
}
Run Code Online (Sandbox Code Playgroud)

Here's how you might take a first crack at simulating the switch/case in Python switch/case in python:

if n == 0:
    print "You typed zero.\n"
elif n == 1 or n == 9 or n == 4:
    print "n is a perfect square\n"
elif n == 2 or n == 6 or n == 8:
    print "n is an even number\n"
elif n == 3 or n == 5 or n == 7:
    print "n is a prime number\n"
elif n > 9:
    print "Only single-digit numbers are allowed\n"
Run Code Online (Sandbox Code Playgroud)

And here's a much better, "Pythonic" way of doing it switch/case in python:

options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

options[num]()
Run Code Online (Sandbox Code Playgroud)