简体   繁体   English

(python)在让用户输入内容之前如何检查while循环的有效性?

[英](python) How to check the validity of a while loop before letting the user to input things?

import random

numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king']
total = 0

while total <= 21:
    output = random.choice(numberList)
    if output == 'jack' or output == 'queen' or output == 'king':
        print(f'({output})')
        output = 10

    print(f'you got {output} points')
    total += output

    ask_cont = input(f'you now have {total} points, continue? [y/n]: ').lower()
    if ask_cont == 'y':
        continue
    else:
        print(f'game finished. You gain {total} points!')
        break
else:
    print(f'you lost! points exceeded = {total - 21} points!')

I am coding a blackjack game.我正在编写二十一点游戏。 However, in the while loop (condition: total amount at hand <= 21), when it exceeded 21 points, it still ask me to continue (ask_cont variable) or not [y/n] for ONCE before code finished and if I type 'n', it just give me the current points (>21) and the 'game finished' statement.但是,在 while 循环中(条件:手头总量 <= 21),当它超过21 个点时,它仍然要求我在代码完成之前是否继续( ask_cont变量)或不继续 [y/n] 如果我输入'n',它只是给我当前点数(>21)和'游戏结束'声明。 How can I fix this?我怎样才能解决这个问题? Thank you very much非常感谢

(also, if there is any way to trim the code please comment, many thanks!) (另外,如果有任何方法可以修剪代码,请发表评论,非常感谢!)

First of all, don't worry about your code being too verbose.首先,不要担心您的代码过于冗长。 It's better to have long, readable code, than short, hard to decipher code.拥有长而易读的代码比短而难破译的代码要好。 Your code looks just fine.你的代码看起来很好。

As far as preventing the user from continuing if total > 21 , this is because you are adding to the total total += output before you get to the while total <= 21 .至于如果total > 21阻止用户继续,这是因为您在达到while total <= 21之前要添加到total += output To fix this, you just have two options.要解决此问题,您只有两个选择。

The first is to have it ask at the start of the while loop, before points are added.第一个是让它在 while 循环开始时询问,然后再添加点。 If you do this, you would also have it ask once before the while loop starts.如果你这样做,你也会让它在 while 循环开始之前询问一次。 Normally you would do this using a do..while loop, but python doesn't have those.通常您会使用do..while循环来执行此操作,但 python 没有这些。

The second optional would be to just add an extra if statement, where it only asks you to continue if total <= 21 , otherwise it does something that finishes the game with the exceed message.第二个选项是只添加一个额外的 if 语句,它只要求您继续 if total <= 21 ,否则它会执行一些以超出消息结束游戏的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM