Python:当一个函数检查变量是否大于0时,我的程序重新启动

2024-06-24 12:58:27 发布

您现在位置:Python中文网/ 问答频道 /正文

当变量等于或小于0时,我的程序应该停止,但当程序运行时,如果变量大于0,代码将重置。你知道吗

这是我的密码: 主.py你知道吗

import random
import os 
import sys
global foodamount
foodamount = random.randint(1,10)
answer = str(input(("Right or Left")))
if answer == "Right" or answer == "right":
  #Check if foodamount is greater than 1, then if it is run cave.py
  foodamount = foodamount -1
  if foodamount < 1:
    print("You ran out of food. You lose")
    sys.exit()
  if foodamount > 0:
    os.system('python cave.py')

这是洞穴.py你知道吗

import random import sys import os import main print("Do you want to attack?") attak = str(input(("Yes or No"))) if attak == "Yes" or attak == "yes": x = random.randint(1,2) if x == 1: os.system('python attack') if x == 2: print("You lose") sys.exit() if attak == "no" or attak == "No": print("Do you leave the cave or go around the spider?") y = str(input("Leave or Around")) if y == "Leave" or y == "leave": main.foodamount = main.foodamount -1 if main.foodamount < 1: print("You ran out of food. You lose") sys.exit() else: os.system('python test')

当我用python运行这个程序时,程序从头开始,程序从头重新启动。你知道吗

如果你能帮上忙,我们将不胜感激。你知道吗


Tags: oranswerpyimport程序youifos
2条回答

你的程序重新启动,因为你的导入都错了。我不知道正确的输出应该是什么,但我解决了你的代码,所以它不会重新启动之前,做它应该做的事。我希望这有帮助。最后,您需要将两个文件放在同一个目录中,这样它们才能正常工作。你知道吗

你知道吗主.py你知道吗

import random
import os 
import sys
import cave

foodamount = random.randint(1,10)

def main():
    global foodamount

    answer = str(input(("Right or Left")))

    if answer == "Right" or answer == "right":
        #Check if foodamount is greater than 1, then if it is run cave.py
        foodamount = foodamount -1

        if foodamount < 1:
            print("You ran out of food. You lose", foodamount)
            sys.exit()
        elif foodamount > 0:
            os.system('python cave.py')        
main()

你知道吗洞穴.py你知道吗

import random
import sys
import os
from Main import *

print("You are in a cold section of the cave")
print("You see a spider in front of you")
print("Do you want to attack?")

attak = str(input(("Yes or No")))

if attak == "Yes" or attak == "yes":
    x = random.randint(1,2)
    if x == 1:
        os.system('python attack')     
    if x == 2:
        print("You lose")
        sys.exit()

if attak == "no" or attak == "No":
    print("Do you leave the cave or go around the spider?")
    y = str(input("Leave or Around"))
    if y == "Leave" or y == "leave":
        foodamount = foodamount -1
        if foodamount < 1:
            print("You ran out of food. You lose")
            sys.exit()
        else:
            os.system('python test')

似乎您已经编写了一个脚本,如果满足某些条件,它将在最后自动运行。别这样。相反,编写一个实现游戏逻辑的函数,并在“while”循环中运行该函数,如下所示:

def play_game():
    if the player dies:
        return False
    return True

while play_game():
    pass

相关问题 更多 >