如何使程序根据命令重新启动

时间:2019-03-09 23:10:39

标签: python

我是Juan Salcedo,我正在为我的计算机科学和软件工程决赛做一个程序。我已经在此程序上工作了两天,我希望我的用户可以选择重新玩拼图或再次玩或停止玩。我将如何去做呢? 谢谢您的帮助,祝娟!

# Hangman
# Juan Salcedo
# 3.7.19

# Importing necessary modules
import random
import sys

print(dir(random))
print(dir(sys))

# Randomize list and break down into letters
words = ['bread', 'clock', 'mouse', 'banana', 'suitcase', 'kitten', 'jupiter', 'bucket', 'cake', 'goose']

random.choice(words)

answer = list(random.choice(words))

# Replace letters with dashes '-'
display = []
display.extend(answer)

for i in range(len(display)):
    display[i] = '-'

# Modified after "Repl_w/_dash" branch
print(' '.join(display))

# Asks user or letters until all are guessed correctly
num = 0

while num < len(answer):
    user_guess = input('Guess a letter: ')
    # Modified after "User input" branch
    user_guess = user_guess.lower()
    print(num)

    # Replaces dashes with user chosen letters
    for i in range(len(answer)):
        if answer[i] == user_guess:
            display[i] = user_guess
            num = num + 1

    print(' '.join(display))

2 个答案:

答案 0 :(得分:1)

您可以只使用while循环

import this
import that

while True:
    #play game
    print('do you want to play again? y/n')
    ans = input()
    if ans != 'y': 
        break

答案 1 :(得分:1)

这应该有效。我已经包含了完整的代码。这是代码:

# Hangman
# Juan Salcedo
# 3.7.19

# Importing necessary modules
import random
import sys
while True:
    print(dir(random))
    print(dir(sys))
    # Randomize list and break down into letters
    words = ['bread', 'clock', 'mouse', 'banana', 'suitcase', 'kitten', 'jupiter', 'bucket', 'cake', 'goose']
    random.choice(words)
    answer = list(random.choice(words))
    # Replace letters with dashes '-'
    display = []
    display.extend(answer)
    for i in range(len(display)):
        display[i] = '-'
    # Modified after "Repl_w/_dash" branch
    print(' '.join(display))
    # Asks user or letters until all are guessed correctly
    num = 0
    while num < len(answer):
        user_guess = input('Guess a letter: ')
        # Modified after "User input" branch
        user_guess = user_guess.lower()
        print(num)
        # Replaces dashes with user chosen letters
        for i in range(len(answer)):
            if answer[i] == user_guess:
                display[i] = user_guess
                num = num + 1
        print(' '.join(display))
    print('do you want to play again? y/n')
    ans = input()
    if ans != 'y': 
        break