【问题标题】:How do you add a list to jump to a line on my code?你如何添加一个列表来跳转到我的代码上的一行?
【发布时间】:2016-05-26 14:39:39
【问题描述】:

我有一个修复手机的 python 代码,我想知道当我输入例如“Broken Screen”时跳转到特定问题的最佳方法是什么

我真的卡住了,需要这样做我非常感谢所有答案

def menu():
   print("Welcome to Sams Phone Troubleshooting program")
   print("Please Enter your name")
   name=input()
   print("Thanks for using Kierans Phone Troubleshooting program "+name)
   print("Would you like to start this program? Please enter either y for yes or n for no")  
   select=input()
   if select=="y":
      troubleshooter()
   elif select=="n":
      quit
   else:
      print("Invalid please enter again")
      menu()
def troubleshooter():
   print("Does Your Phone Turn On")
   answer=input()
   if answer=="y":
      print("Does it freeze?")
   else:
      print("Have you plugged in a charger?")
   answer=input()

   if answer=="y":
      print("Charge it with a diffrent charger in a diffrent phone socket")
   else:
      print("Plug it in and leave it for 20 mins, has it come on?")
   answer=input()

   if answer=="y":
      print("Is there any more problems?")
   else:
      print("Is the screen cracked?")
   answer=input()

   if answer=="y":
      print("Restart this program")
   else:
      print("Thank you for using my troubleshooting program!")
   answer=input()

   if answer=="y":
      print("Replace screen in a shop")
   else:
      print("Take it to a specialist")
   answer=input()

   if answer=="y":
      print("Did you drop your device in water?")
   else:
      print("Make sure the sim card is inserted properly and do a hard reset on the device")
   answer=input()

   if answer=="y":
      print("Do not charge it and take it to the nearest specialist")
   else:
      print("Try a hard reset when the battery has charge")
   answer=input()



menu()

【问题讨论】:

  • 我需要在代码中添加什么?顺便说一句,非常感谢你
  • 将逻辑拆分为单独的问题,您可以单独调用。
  • 能否请您这样做,我将不胜感激
  • 不,请自行尝试。如果您最终遇到问题,我们可以提供帮助,但您应该先尝试自己解决。
  • 我的回答对您有帮助吗,还是您想要一些不同的东西?

标签: python python-3.x


【解决方案1】:

以下代码应提供一个框架,在该框架上构建和扩展您的问题中的程序。大多数代码应该和当前编写的一样好,但如果需要,您可以扩展其功能。要继续构建可以提出的问题和给出的答案,请考虑在文件顶部的数据库中添加更多部分。这些案例可以很容易地扩充。

#! /usr/bin/env python3

"""Cell Phone Self-Diagnoses Program

The following program is designed to help users to fix problems that they may
encounter while trying to use their cells phones. It asks questions and tries
to narrow down what the possible cause of the problem might be. After finding
the cause of the problem, a recommended action is provided as an attempt that
could possibly fix the user's device."""

# This is a database of questions used to diagnose cell phones.
ROOT = 0
DATABASE = {
            # The format of the database may take either of two forms:
            # LABEL: (QUESTION, GOTO IF YES, GOTO IF NO)
            # LABEL: ANSWER
            ROOT: ('Does your phone turn on? ', 1, 2),
            1: ('Does it freeze? ', 11, 12),
            2: ('Have you plugged in a charger? ', 21, 22),
            11: ('Did you drop your device in water? ', 111, 112),
            111: 'Do not charge it and take it to the nearest specialist.',
            112: 'Try a hard reset when the battery has charge.',
            12: 'I cannot help you with your phone.',
            21: 'Charge it with a different charger in a different phone '
                'socket.',
            22: ('Plug it in and leave it for 20 minutes. Has it come on? ',
                 221, 222),
            221: ('Are there any more problems? ', 222, 2212),
            222: ('Is the screen cracked? ', 2221, 2222),
            2212: 'Thank you for using my troubleshooting program!',
            2221: 'Replace in a shop.',
            2222: 'Take it to a specialist.'
            }

# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))


def main():
    """Help diagnose the problems with the user's cell phone."""
    verify(DATABASE, ROOT)
    welcome()
    ask_questions(DATABASE, ROOT)


def verify(database, root):
    """Check that the database has been formatted correctly."""
    db, nodes, visited = database.copy(), [root], set()
    while nodes:
        key = nodes.pop()
        if key in db:
            node = db.pop(key)
            visited.add(key)
            if isinstance(node, tuple):
                if len(node) != 3:
                    raise ValueError('tuple nodes must have three values')
                query, positive, negative = node
                if not isinstance(query, str):
                    raise TypeError('queries must be of type str')
                if len(query) < 3:
                    raise ValueError('queries must have 3 or more characters')
                if not query[0].isupper():
                    raise ValueError('queries must start with capital letters')
                if query[-2:] != '? ':
                    raise ValueError('queries must end with the "? " suffix')
                if not isinstance(positive, int):
                    raise TypeError('positive node names must be of type int')
                if not isinstance(negative, int):
                    raise TypeError('negative node names must be of type int')
                nodes.extend((positive, negative))
            elif isinstance(node, str):
                if len(node) < 2:
                    raise ValueError('string nodes must have 2 or more values')
                if not node[0].isupper():
                    raise ValueError('string nodes must begin with capital')
                if node[-1] not in {'.', '!'}:
                    raise ValueError('string nodes must end with "." or "!"')
            else:
                raise TypeError('nodes must either be of type tuple or str')
        elif key not in visited:
            raise ValueError('node {!r} does not exist'.format(key))
    if db:
        raise ValueError('the following nodes are not reachable: ' +
                         ', '.join(map(repr, db)))


def welcome():
    """Greet the user of the application using the provided name."""
    print("Welcome to Sam's Phone Troubleshooting program!")
    name = input('What is your name? ')
    print('Thank you for using this program, {!s}.'.format(name))


def ask_questions(database, node):
    """Work through the database by asking questions and processing answers."""
    while True:
        item = database[node]
        if isinstance(item, str):
            print(item)
            break
        else:
            query, positive, negative = item
            node = positive if get_response(query) else negative


def get_response(query):
    """Ask the user yes/no style questions and return the results."""
    while True:
        answer = input(query).casefold()
        if answer:
            if any(option.startswith(answer) for option in POSITIVE):
                return True
            if any(option.startswith(answer) for option in NEGATIVE):
                return False
        print('Please provide a positive or negative answer.')


if __name__ == '__main__':
    main()

【讨论】:

  • 如果此答案有问题,请提供修改以解决问题或提出改进建议的评论。
  • 非常感谢您,先生您非常有才华:)
  • @KieranMcCarthy 请考虑阅读What should I do when someone answers my question?。如果上面显示的代码符合您的需要,您可能希望接受答案。
  • 对不起,我是新人,我强调这个代码很抱歉,但它不是我想要的,非常感谢你,因为我正在寻找更多带有关键字的代码,然后跳转到某个问题我的 Skype 是 kkid19,如果你能帮助我,我会欣喜若狂,因为我会在这个网站上给你我所能提供的一切
  • @KieranMcCarthy 这正是程序顶部的DATABASE 所做的。让我们以1: ('Does it freeze? ', 11, 12), 为例。这意味着以下问题的标签为“1”。问题是Does it freeze?。如果答案是肯定的,请转到标签“11;”但如果答案是否定的,请转到标签“12”。我们可以看另一个例子:2221: 'Replace in a shop.', 这行表示标签是 2221。这不是一个问题,而是一个终止程序的答案。答案是Replace in a shop.你可以随意扩展数据库。
【解决方案2】:

这是我复制您的代码的最佳尝试。 我提出了几个问题 def() 以便您可以分别调用每个问题。 我希望这是你想要的!

def menu():
  print("Welcome to Sams Phone Troubleshooting program")
  print("Please Enter your name")
  name=input()
  print("Thanks for using Kierans Phone Troubleshooting program "+name +"\n")

def start():
  select = " "
  print("Would you like to start this program? Please enter either y for yes or n for no")
  select=input()
  if select=="y":
    troubleshooter()
  elif select=="n":
    quit
  else:
    print("Invalid please enter again")

def troubleshooter():
  print("""Please choose the problem you are having with your phone (input 1-4):
1) My phone doesn't turn on
2) My phone is freezing
3) The screen is cracked
4) I dropped my phone in water\n""")
  problemselect = int(input())
  if problemselect ==1:
    not_on()
  elif problemselect ==2:
    freezing()
  elif problemselect ==3:
    cracked()
  elif problemselect ==4:
    water()
  start()

def not_on():
  print("Have you plugged in the charger?")
  answer = input()
  if answer =="y":
    print("Charge it with a diffrent charger in a diffrent phone socket. Does it work?")
  else:
    print("Plug it in and leave it for 20 mins, has it come on?")
  answer = input()
  if answer=="y":
    print("Are there any more problems?")
  else:
    print("Restart the troubleshooter or take phone to a specialist\n")
  answer=input()
  if answer =="y":
    print("Restart this program")
  else:
    print("Thank you for using my troubleshooting program!\n")

def freezing():
  print("Charge it with a diffrent charger in a diffrent phone socket")
  answer = input("Are there any more problems?")
  if answer=="y":
    print("Restart the troubleshooter or take phone to a specialist\n")
  else:
    print("Restart this program\n")

def cracked():
  answer =input("Is your device responsive to touch?")
  if answer=="y":
    answer2 = input("Are there any more problems?")
  else:
    print("Take your phone to get the screen replaced")
  if answer2=="y":
    print("Restart the program or take phone to a specialist\n")
  else:
    print("Thank you for using my troubleshooting program!\n")

def water():
  print("Do not charge it and take it to the nearest specialist\n")

menu()
while True:
  start()
  troubleshooter()

希望这会有所帮助,如果代码有小问题,请给我发消息! (我对这个网站比较陌生!)

【讨论】:

  • 非常感谢你的帮助,我非常感谢你的帮助,你是一个非常善良的人,但是我要求我输入“屏幕冻结”这样的关键字而不是数字,再次感谢你你治愈了我这么多:)))
  • 我的 Skype 是 kkid19,如果你愿意帮助我,我会非常感谢
  • @KieranMcCarthy 不确定您是否已解决问题,但只需将数字更改为关键字就应该是您想要的!将problemselect == 1 更改为problemselect == "Broken Screen" 等,看看是否可行:) 可能需要进行一些调整,但祝你好运!!
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2020-01-23
  • 2017-08-29
  • 2010-09-15
相关资源
最近更新 更多