简体   繁体   English

python 跳出循环

[英]python breaking out of loop

I don't know how to break out of the loop.我不知道如何跳出循环。 The program is asking my user the same question two times, and I cannot work out why.该程序两次问我的用户同一个问题,我无法弄清楚为什么。 it should ask me which team won the event only ONE time, then ask me, 'is this correct' but then it asks again who won它应该问我哪支球队只赢了一次比赛,然后问我,“这是正确的吗”,然后又问谁赢了

import time
class Team:
    def __init__(self, num, name, size, score):
        self.num = num
        self.name = name
        self.size = size
        self.score = score

    def add_victory(self):
        self.score += 1

    def __repr__(self):
        return f'Team Number: {self.num} |-| Team Name: {self.name} |-| Member Count: {self.size} |-| Team Score: {self.score}'

def NewTournament():

    TeamCounter=int(input('How many Teams will be in the tournament? '))

    print('')
    for i in range(TeamCounter):
        NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
        MemberCount=int(input('How Many Members in Team? '))
        print('')
        teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )


def Score(teams):
    winner = input('Which Team Won the Event? ')
    for team in teams:
        if team.name == winner:
            team.add_victory()
            break
            print('Updated Leaderboard')

def Leaderboard():
    for t in teams:
        print(t)
    
def Menu():
    MenuLoop=1
    while MenuLoop==1:
        print('1.Create Tournament')
        print('2.Update Existing Tournament')
        print('3.View Leaderboard')
        print('4.Exit')
        MenuOption=input('')
        if MenuOption=='1':
            print('Creating Tournament')
            NewTournament()#runs the new tournament function
            MenuLoop-=1
            Menu()
        elif MenuOption=='2':
            print('Updating Tournament')
            MenuLoop-=1
            EventName=input('Which Event Was Completed? ')
            winner=input('Which Team Won the Event? ')#asking me this 2 times
            print('Event Winner:', winner, '||', 'Event:',EventName)
            print('Is this correct? Y/N') 
            Check=input('')
            if Check=='y':
                print('Updating Leaderboard')
                Score(teams)
                Menu()
                    
                
                
        elif MenuOption=='3':
            MenuLoop-=1
            Leaderboard()
            print('')
            time.sleep(0.3)
            Menu()
                
        elif MenuOption=='4':
            print('Exiting Program...')
        else:
            print('Error, please choose an option from the list below.')#keeps looping if user is not choosing a correct number from list


#start of program
teams = []        

print('░██╗░░░░░░░██╗███████╗██╗░░░░░░█████╗░░█████╗░███╗░░░███╗███████╗')
print('░██║░░██╗░░██║██╔════╝██║░░░░░██╔══██╗██╔══██╗████╗░████║██╔════╝')
print('░╚██╗████╗██╔╝█████╗░░██║░░░░░██║░░╚═╝██║░░██║██╔████╔██║█████╗░░')
print('░░████╔═████║░██╔══╝░░██║░░░░░██║░░██╗██║░░██║██║╚██╔╝██║██╔══╝░░')
print('░░╚██╔╝░╚██╔╝░███████╗███████╗╚█████╔╝╚█████╔╝██║░╚═╝░██║███████╗')
print('░░░╚═╝░░░╚═╝░░╚══════╝╚══════╝░╚════╝░░╚════╝░╚═╝░░░░░╚═╝╚══════╝')#welcome user
print('')
Username=input('Enter Username: ')
Password=input('Enter Password: ')
if Username =='Admin' and Password == 'Admin':#very basic login system for security of school
    print('Logging in...')
    print('User Verified')
    Menu()
else:
    print('User Does Not Exist.')#stops pupils gaining unauthorised access

I get this output:我得到这个 output:

1.Create Tournament
2.Update Existing Tournament
3.View Leaderboard
4.Exit
2
Updating Tournament
Which Event Was Completed? Football
Which Team Won the Event? Two
Event Winner: Two || Event: Football
Is this correct? Y/N
y
Updating Leaderboard
Which Team Won the Event? Two
1.Create Tournament
2.Update Existing Tournament
3.View Leaderboard
4.Exit
3

It loops back to the menu() as I would like, but I do not like how it is asking me 'which team won the event?'它像我希望的那样循环回到menu() ,但我不喜欢它如何问我“哪支球队赢得了比赛?” twice.两次。 It should only be once.应该只有一次。

So made a few adjustments:于是做了一些调整:

  1. You get asked 'Which Team Won the Event?'你会被问到'Which Team Won the Event?' twice because you literally have it in there twice: once in the Menu() MenuOption 2, and then Score() which you call in that same option 2. So you need to decide which one to keep.两次,因为您确实将它放在那里两次:一次是在 Menu() MenuOption 2 中,然后是您在同一个选项 2 中调用的 Score()。因此您需要决定保留哪一个。 I kept the one in the Menu(), then pass that winner input into the Score() function我将那个保留在 Menu() 中,然后将该winner输入传递到Score() function
  2. A better way to handle the loop here is simply have the while loop continue while the MenuOption != '4'在这里处理循环的更好方法是让while循环继续而MenuOption != '4'
  3. You need to fix your Check .您需要修复Check You ask the user to input uppercase Y/N , but then you if Check=='y' .您要求用户输入大写Y/N ,然后您输入if Check=='y' So even if the user enters Y , Check=='y' will return False .所以即使用户输入YCheck=='y'也会返回False Also to that point, why the separate print() followed by input ?同样对于这一点,为什么单独的print()后跟input Just combine that.只是结合起来。
  4. You added a print() statement after break in Score() ?您在Score()中的break后添加了print()语句? You realize then everything after a break won't run?你意识到break后一切都不会运行吗?
  5. Having the Menu() function with the Menu() function. Calling that recursively will keep you in the while loop when you're expecting it to jump out.将 Menu() function 与 Menu() function 结合使用。当您期望它跳出时,递归调用将使您处于 while 循环中。

So made those few changes.所以做了那些小改动。 I'd suggest find/use and IDE that can let you debug and run the code line by line, so that you can sort of follow your code/logic.我建议查找/使用和 IDE 可以让您逐行调试和运行代码,这样您就可以按照您的代码/逻辑进行操作。 PyCharm is very popular one. PyCharm 是非常受欢迎的一个。 I use Spyder.我使用 Spyder。

import time
class Team:
    def __init__(self, num, name, size, score):
        self.num = num
        self.name = name
        self.size = size
        self.score = score

    def add_victory(self):
        self.score += 1

    def __repr__(self):
        return f'Team Number: {self.num} |-| Team Name: {self.name} |-| Member Count: {self.size} |-| Team Score: {self.score}'

def NewTournament():

    TeamCounter=int(input('How many Teams will be in the tournament? '))

    print('')
    for i in range(TeamCounter):
        NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
        MemberCount=int(input('How Many Members in Team? '))
        print('')
        teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )


def Score(teams, winner):
    for team in teams:
        if team.name == winner:
            team.add_victory()
            print('Updated Leaderboard')
            break

def Leaderboard():
    for t in teams:
        print(t)
    
def Menu():
    MenuOption = False
    while MenuOption!='4':
        print('1.Create Tournament')
        print('2.Update Existing Tournament')
        print('3.View Leaderboard')
        print('4.Exit')
        MenuOption=input('')
        if MenuOption=='1':
            print('Creating Tournament')
            NewTournament()#runs the new tournament function
            
        elif MenuOption=='2':
            print('Updating Tournament')
            EventName=input('Which Event Was Completed? ')
            winner=input('Which Team Won the Event? ')#asking me this 2 times
            print('Event Winner:', winner, '||', 'Event:',EventName)
            Check=input('Is this correct? Y/N\n') 
            if Check.upper()=='Y':
                print('Updating Leaderboard')
                Score(teams, winner)
                
        elif MenuOption=='3':
            Leaderboard()
            print('')
            time.sleep(0.3)
            
                
        elif MenuOption=='4':
            print('Exiting Program...')
        else:
            print('Error, please choose an option from the list below.')#keeps looping if user is not choosing a correct number from list


#start of program
teams = []        

print('░██╗░░░░░░░██╗███████╗██╗░░░░░░█████╗░░█████╗░███╗░░░███╗███████╗')
print('░██║░░██╗░░██║██╔════╝██║░░░░░██╔══██╗██╔══██╗████╗░████║██╔════╝')
print('░╚██╗████╗██╔╝█████╗░░██║░░░░░██║░░╚═╝██║░░██║██╔████╔██║█████╗░░')
print('░░████╔═████║░██╔══╝░░██║░░░░░██║░░██╗██║░░██║██║╚██╔╝██║██╔══╝░░')
print('░░╚██╔╝░╚██╔╝░███████╗███████╗╚█████╔╝╚█████╔╝██║░╚═╝░██║███████╗')
print('░░░╚═╝░░░╚═╝░░╚══════╝╚══════╝░╚════╝░░╚════╝░╚═╝░░░░░╚═╝╚══════╝')#welcome user
print('')
Username=input('Enter Username: ')
Password=input('Enter Password: ')
if Username =='Admin' and Password == 'Admin':#very basic login system for security of school
    print('Logging in...')
    print('User Verified')
    Menu()
else:
    print('User Does Not Exist.')#stops pupils gaining unauthorised access

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

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