番茄游戏中 发表于 2021-8-24 15:43:59

求问一下零基础学python26讲的课后作业

作业连接:https://fishc.com.cn/thread-45159-1-1.html

动动手的答案部分有一些看不太懂,我把疑惑的部分代码贴上去,希望各位路过朋友帮忙解惑。
我不理解为什么要建立chosen这个变量

答案为:
while True:
      chosen = False
      while not chosen:
            choice = input(prompt)
            if choice not in 'NnEeQq':
                print('您输入的指令代码错误,请重新输入:')
            else:
                chosen = True

      if choice == 'q' or choice == 'Q':
            break
      if choice == 'n' or choice == 'N':
            new_user()
      if choice == 'e' or choice == 'E':
            old_user()

为何不能直接删除chosen变量改为:
while True:
      choice = input(prompt)
      if choice not in 'NnEeQq':
                print('您输入的指令代码错误,请重新输入:')
      if choice == 'q' or choice == 'Q':
            break
      if choice == 'n' or choice == 'N':
            new_user()
      if choice == 'e' or choice == 'E':
            old_user()

第一次发求助帖,不知道是否合规范,先谢谢大家了。

wp231957 发表于 2021-8-24 15:47:11

if choice not in 'NnEeQq':
                print('您输入的指令代码错误,请重新输入:')
无法实现 重新输入

冬雪雪冬 发表于 2021-8-24 16:32:35

当输入不正确时,还需做后面三个if判断,增加程序的运行时间

番茄游戏中 发表于 2021-8-24 16:47:24

wp231957 发表于 2021-8-24 15:47
if choice not in 'NnEeQq':
                print('您输入的指令代码错误,请重新输入:')
无法实现 重 ...

刚刚试了一下,可以的呀?因为前面是whie True,就一直是这个循环

番茄游戏中 发表于 2021-8-24 16:51:46

冬雪雪冬 发表于 2021-8-24 16:32
当输入不正确时,还需做后面三个if判断,增加程序的运行时间

思考了半天才懂。谢谢!

冬雪雪冬 发表于 2021-8-24 17:09:41

番茄游戏中 发表于 2021-8-24 16:51
思考了半天才懂。谢谢!

其实用elif也能提高效率
页: [1]
查看完整版本: 求问一下零基础学python26讲的课后作业