Trying again using multiple loops in a code - python

I have a problem using the while loop. When I am inputting right answer for example, and the second one is wrong, the tryAgain input is showing. If I want to play again, it just looping in from the start and choosing a topic won't work. If I made it wrong, from the start, it will just loop on its own from inputting answers.
tryAgain = True
repeat = True
while tryAgain:
print("TOPICS: \n")
print("1. topic 1")
print("2. topic 2")
print("3. topic 3")
print("======================================")
num = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if num > 3:
print("There is no given topic")
print("==========================")
tryAgain = True
else:
if num == 1:
reader = WordListCorpusReader('filename', ['textfile'])
with open('filename') as f:
text = [line.strip().upper() for line in f]
answer = []
while lives > 0:
while repeat:
index = 0
while index < 10:
answerlst = input(str(index + 1) + '. ').upper()
if answerlst in text: #condition if the inputted answer is on the file
if answerlst in answer: #check if the inputted answer is on the array
print("\nYou repeated your answer!")
repeat = True
continue
else:
answer.append(answerlst)
print("Correct!")
repeat = False
if answerlst == "ans1":
print("Points: 10")
points += 10
elif answerlst == "ans2":
print("Points: 20")
points += 20
elif answerlst == "ans3":
print("Points: 30")
points += 30
elif answerlst == "ans4":
print("Points: 40")
points += 40
elif answerlst == "ans5":
print("Points: 50")
points += 50
elif answerlst == "ans6":
print("Points: 60")
points += 60
elif answerlst == "ans7":
print("Points: 70")
points += 70
elif answerlst == "ans8":
print("Points: 80")
points += 80
elif answerlst == "ans9":
print("Points: 90")
points += 90
elif answerlst == "ans10":
print("Points: 100")
points += 100
if points == 550:
print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", points)
break
else:
if answerlst == "ans1":
points += 10
elif answerlst == "ans2":
points += 20
elif answerlst == "ans":
points += 30
elif answerlst == "ans4":
points += 40
elif answerlst == "ans5":
points += 50
elif answerlst == "ans6":
points += 60
elif answerlst == "ans7":
points += 70
elif answerlst == "ans8":
points += 80
elif answerlst == "ans9":
points += 90
elif answerlst == "ans10":
points += 100
lives -= 1
if lives == 0:
print("\nGAME OVER!!!!!\n")
print("You just got a: ", points)
break
index +=1
playAgain = input("Do you want to play again? [Y] / [N]: ").upper()
if playAgain == 'Y':
answer.clear() #to clear the list
tryAgain = True
I just show the structure of my code in order to understand.

Congratulations, because now you've learned what spaghetti code is - it's just a mess, where you can't properly find errors. When such situation occurs, try to divide your problem into smaller parts (stages). Implement the stages as functions, and your code will become much easier.
For example I tried to rework your program like this. ATTENTION: I don't have your files, so this code probably won't work out of the box, I cannot test it. But just try to read it and understand the approaches.
After reworking this code I noticed that you never set lives to any number, but you should.
def input_topic():
while True:
print("TOPICS: \n")
print("1. topic 1")
print("2. topic 2")
print("3. topic 3")
print("======================================")
topic = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if topic > 3:
print("There is no given topic")
print("==========================")
else:
return topic
def read_text(filename):
reader = WordListCorpusReader(filename, ['textfile'])
with open(filename) as f:
text = [line.strip().upper() for line in f]
return text
def input_answer_and_check(index, text, already_answered):
while True:
answerlst = input(str(index+1) + '. ').upper()
if answerlst in text:
if answerlst not in answer:
return True, answerlst
else:
print("\nYou repeated your answer!")
else:
return False, answerlst
def get_answer_points(answerlst)
if answerlst == "ans1":
return 10
elif answerlst == "ans2":
return 20
elif answerlst == "ans3":
return 30
elif answerlst == "ans4":
return 40
elif answerlst == "ans5":
return 50
elif answerlst == "ans6":
return 60
elif answerlst == "ans7":
return 70
elif answerlst == "ans8":
return 80
elif answerlst == "ans9":
return 90
elif answerlst == "ans10":
return 100
def ask_try_again():
playAgain = input("Do you want to play again? [Y] / [N]: ").upper()
return playAgain == 'Y'
while True:
topic = input_topic()
text = read_text('filename')
answer = []
lives_left = 5
index = 0
max_index = 10
total_points = 0
while lives_left > 0 and index < max_index and total_points < 550:
is_correct_answer, answerlst = input_answer_and_check(index, text, answer)
answer_points = get_answer_points(answerlst)
total_points += answer_points
if is_correct_answer:
answer.append(answerlst)
print("Correct!")
print(f"Points: {answer_points}")
else:
lives_left -= 1
index += 1
if lives_left == 0:
print("\nGAME OVER!!!!!\n")
print("You just got a: ", total_points)
elif total_points >= 550:
print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", total_points)
if not ask_try_again():
break

Related

Arrow Simulator Highest score and its holder

from multiprocessing.resource_sharer import stop
import random
import math
play_again = 'y'
while play_again == 'y':
remaining_attempts = 3
current_score = 0
print('Welcome to archery simulator!')
print('please input your name:')
name = input(str())
if name == 'Quit':
break
print('Your current score:',current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer = str(input())
if answer == 'Quit':
break
while remaining_attempts > 0:
if answer == 'y':
target_location_x = random.uniform(30, 150)
target_location_y = random.uniform(0,15)
print('The target is at location:', target_location_x, ',', target_location_y)
print('Input the arrows initial velocity:')
initial_velocity = float(input())
if initial_velocity == 'Quit':
stop
while initial_velocity <= 0:
print('Error: Only values greater than 0')
initial_velocity = float(input())
if initial_velocity == 'Quit':
break
print('Input the angle the arrow is fired:')
#to convert to radians so that trig comes out as degrees
arrow_angle = math.radians(float(input()))
if arrow_angle == 'Quit':
break
while arrow_angle >= 90:
print('Error: Only values >=0 and <90')
#to convert to radians so that trig comes out as degrees
arrow_angle = math.radians(float(input()))
if arrow_angle == 'Quit':
break
X0 = 0
Y0 = 1
g = 9.8
t = 0.5
#to calculate where x and y ends up for the arrow
angle_x = math.cos(arrow_angle)
arrow_x = X0 + ((t*initial_velocity)*angle_x)
angle_y = math.sin(arrow_angle)
arrow_y = Y0 + ((t*initial_velocity)*angle_y)-(((1/2)*g)*(t**2))
#to get the distance from the bullseye
def distance_bullseye (arrow_x, arrow_y):
distance_bullseye = ((arrow_x-target_location_x)**2)+((arrow_y-target_location_y)**2)
distance_centre = math.sqrt(distance_bullseye)
return distance_centre
distance_centre = distance_bullseye(arrow_x, arrow_y)
print('Arrow ends up at:',arrow_x,',',arrow_y)
if distance_centre > 10:
print('You missed! Distance from centre', distance_centre)
current_score = current_score
remaining_attempts = remaining_attempts - 1
print('Your current score:', current_score)
if remaining_attempts == 0:
current_score
print('Simulation over.')
print('Highest score holder:', #Highest score holder here)
print('Highest score:',#Highest score here)
print('Play again?')
play_again = str(input())
if play_again == 'y':
remaining_attempts = 3
current_score = 0
print('Welcome to archery simulator!')
print('Please input your name:')
name = str(input())
elif play_again == 'Quit' or 'n':
stop
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 10 >= distance_centre > 5:
print('You hit the outer ring!')
current_score = current_score+50
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 5 >= distance_centre > 1:
print('You hit the inner ring!')
current_score = current_score+200
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
elif 1 >= distance_centre >= 0:
print('You hit the bullseye!')
current_score = current_score +500
remaining_attempts = 3
print('Your current score:', current_score)
print('Remaining attempts',remaining_attempts)
print('Would you like to fire an arrow?')
answer =input(str())
if answer == 'Quit':
break
#don't know how to get highest score holder or highest score
elif answer == 'n':
print('Simulation over.')
print('Highest score holder:', #Highest score holder here)
print('Highest score:',#Highest score here)
print('Play again?')
play_again = str(input())
if play_again == 'Quit' or 'n':
stop
else:
print('Input y or n')
answer = str(input())
if answer == 'Quit':
break
Tried making a list but couldn't get the one variable to stay the same through the code loops it keeps resetting to the new name and new score. is there any way I could keep the highest score and its holder throughout the loops?
it should keep the name from the start if that name has the highest score and the program runs again and that player has a lower score should print the first name and first score, if it's higher it should print the second name with the second score.

How can I repeat inputting with the for loop numbering if the answer is not accepted?

I am using a for loop for numbering for my input answers. If the user gets a correct answer, it will stored in the list. But, if the user want to repeat the answer, it will print out that the user repeated the answer but the problem is, instead of inputting in the same number, it will go on the next number
answer = []
while lives > 0:
while repeat:
for i in range(0,10):
answerlst = input(str(i + 1) + '. ').upper()
if answerlst in text:
if answerlst in answer:
print("You repeated your answer!")
repeat = True
else:
answer.append(answerlst)
repeat = False
else:
print("Incorrect. You just lose a life")
lives -= 1
if lives == 0:
print("GAME OVER!!!!!\n")
break
ask = input("\nWanna play again? [Y] / [N]: ").upper()
if ask == 'Y':
tryAgain = True
else:
tryAgain = False
Example:
Dark
Dark
You repeated your answer!
#This is the problem
Instead of inputting in number 3, it should be number 2 because it only repeats the answer.
In such cases using a while loop is the best choice. Assign a variable as starting point and then increment if condition false, if true use continue then it would have the same index.
answer = []
while lives > 0:
while repeat:
index = 0
while index < 10:
answerlst = input(str(index + 1) + '. ').upper()
if answerlst in text:
if answerlst in answer:
print("You repeated your answer!")
repeat = True
continue
else:
answer.append(answerlst)
repeat = False
else:
print("Incorrect. You just lose a life")
lives -= 1
if lives == 0:
print("GAME OVER!!!!!\n")
break
index += 1
ask = input("\nWanna play again? [Y] / [N]: ").upper()
if ask == 'Y':
tryAgain = True
else:
tryAgain = False

Else and elif trouble decision

Imagine i have the following problem.Write a program to play the following simple game. The player starts with $100. On each
turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each
correct guess and loses $10 for each incorrect guess. The game ends either when the player
runs out of money or gets to $200.
I have already solved the problem by using a while loop and some if and else statements. I will post the code. When i use if and else my program prints p1_points and p2_points.
import random
coin = ['h','t']
def cpu_guess():
return random.choice(coin)
def player1_guess():
return input('Digit your choice player 1\n')
def player2_guess():
return input('Digit your choice player 2\n')
def guessing_game():
p1_points = 100 #each player starts with 100$
p2_points = 100 #each player starts with 100$
while (0 < p1_points <= 200) or (0 < p2_points < 200):
cpu_choice = cpu_guess()
print(cpu_choice)
player1_choice = player2_guess()
player2_choice = player2_guess()
if player1_choice == cpu_choice:
p1_points += 45
print(p1_points)
else:
p1_points = p1_points - 45
print(p1_points)
if player2_choice == cpu_choice:
p2_points += 45
print(p2_points)
else:
p2_points = p2_points - 45
print(p2_points)
if p1_points > p2_points:
print('Player 1 won the game (',p1_points,'-',p2_points,')')
elif p2_points > p1_points:
print('Player 2 won the game (', p2_points, '-', p1_points, ')')
else:
print('Even game (',p1_points,'-',p2_points,')')
return p1_points,p2_points
print(guessing_game())
However imagine i want to put the following code.
if player1_choice == cpu_choice:
p1_points += 45
print(p1_points)
elif player_choice != cpu_choice
p1_points = p1_points - 45
print(p1_points)
elif player2_choice == cpu_choice:
p2_points += 45
print(p2_points)
else:
p2_points = p2_points - 45
print(p2_points)
In this situation why are only the player 1 points printed and not the player 2 points aswell?
It sounds like you want two separate if/else blocks:
if player1_choice == cpu_choice:
p1_points += 45
else:
p1_points -= 45
print(p1_points)
if player2_choice == cpu_choice:
p2_points += 45
else:
p2_points -= 45
print(p2_points)

Camel Game, trouble with native distance values

I'm trying to write the Camel game using functions instead of so many nested if statements. I think I've done something wrong though, I've had to tinker with the native distance portion a lot as I kept getting into parts where they only got further away not closer. But now after trying to change the randomint values I can never escape them. Any suggestions for improvement are much appreciated!
Here is my code:
import random
def quitGame():
print("I am guitting now.")
return True
def status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks):
print(
"""
You have traveled %d miles
Your Camel Status is %d (lower is better)
You have %d drinks left in your canteen
Your thirst is %d (lower is better)
The Natives are %d miles behind you
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
def rest():
print("The camel is happy")
distanceN = random.randint(7,14)
return(distanceN)
def fullSpeed():
distanceT = random.randint(10,20)
print("You travel %d miles"%distanceT)
camelT = random.randint(1,3)
distanceN = random.randint(7,14)
return(distanceT,camelT,distanceN)
def moderateSpeed():
distanceB = random.randint(5,12)
print("You travel %d miles"%distanceB)
nativesB = random.randint(7,14)
return(distanceB,nativesB)
def thirsty(drinksLeft):
drinksL = drinksLeft - 1
return(drinksL)
def main():
choice = ""
done = False # loop variable
#variables for game
milesTraveled = 0
thirst = 0
camelTiredness = 0
distanceNativesTraveled = -20
drinks = 5
print(
"""
Welcome to the Camel Game!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down. Survive your
desert trek and out run the native.
"""
)
while not done:
findOasis = random.randint(1,20)
print(
"""
Here are your choices:
A - Drink from you canteen.
B - Ahead moderate speed.
C - Ahead full speed.
D - Stop and rest for night.
E - Status check.
Q - Quit the Game
"""
)
choice = input(" Your choice?\n")
if choice.upper() == "Q":
done = quitGame()
elif findOasis is 1 :
print("Wow! You've found an Oasis. Your thirst is quenched, canteen topped off, \
and your camel is now well rested and happy.")
drinks = 5
thirst = 0
camelTiredness = 0
elif choice.upper() == "A":
if drinks > 0:
drinks = thirsty(drinks)
thirst = 0
else:
print("Error: Uh oh! No water left.")
elif choice.upper() == "B":
milesB,nativesB = moderateSpeed()
milesTraveled += milesB
camelTiredness += 1
thirst += 1
distanceNativesTraveled += nativesB
elif choice.upper() == "C":
milesT,camelTired,nativesT= fullSpeed()
milesTraveled += milesT
camelTiredness += camelTired
distanceNativesTraveled += nativesT
thirst += 1
elif choice.upper() == "D":
distanceT = rest()
camelTiredness = 0
distanceNativesTraveled += distanceT
elif choice.upper() == "E":
statusCheck = status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks)
else:
print("That was not a correct choice - Enter (A through E or Q)")
if thirst > 4 and thirst <= 6:
print("You are thirsty")
elif thirst > 6:
print("GAME OVER \nYou died of thirst!")
done = True
elif camelTiredness > 5 and camelTiredness <= 8:
print("Your camel is getting tired")
elif camelTiredness > 8:
print("GAME OVER \nYour camel is dead.")
done = True
elif distanceNativesTraveled >= 0:
print("GAME OVER \nThe natives have captured you!")
done = True
elif distanceNativesTraveled > -15:
print("The natives are getting close!")
elif milesTraveled >= 200:
print("YOU WIN \nCongrats, you made it across the desert!")
done = True
# call main
main()
The game ends when distanceNativesTraveled >= 0 and yet there's no code at all to decrease distanceNativesTraveled. So with every turn distanceNativesTraveled keeping increasing, the game is bound to end quickly.
What you really want here is to check if distanceNativesTraveled has surpassed milesTraveled, so change:
elif distanceNativesTraveled >= 0:
to:
elif distanceNativesTraveled >= milesTraveled:
And for the check to see if natives are getting close, change:
elif distanceNativesTraveled > -15:
to:
elif distanceNativesTraveled - milesTraveled > -15:
And to properly show the how many miles the natives are behind you, you should show the difference between the miles you and the natives traveled, so change:
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
to:
"""%(milesTraveled,camelTiredness,drinks,thirst,milesTraveled - distanceNativesTraveled))

Beginner Python-Looping to the beginning of a programme

I will start fresh! I have included the full code so you can get a picture for what i am trying to do. Prob (1) I can not loop back to the very beginning. Prob (2) It is not looping # the While higher_or_lower part of the code. it just goes through the if and else higher_or_lower statements. Thanks
done = False
while done == False:
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess)
input("Correct!\nWell done\n\n")
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the number game. Goodbye")
done = True
breaK
Ok, a primer in how Python indentation works.
number = 1
while number < 10:
print(number)
number += 1
print("this will print everytime because it's inside the while")
Output:
1
this will print everytime because it's inside the while
2
this will print everytime because it's inside the while
3
this will print everytime because it's inside the while
4
this will print everytime because it's inside the while
5
this will print everytime because it's inside the while
6
this will print everytime because it's inside the while
7
this will print everytime because it's inside the while
8
this will print everytime because it's inside the while
9
this will print everytime because it's inside the while
Notice that the second print prints every time because of it's indentation.
Now the second example:
number = 1
while number < 10:
print(number)
number += 1
print("this will print AFTER the loop ends")
Output:
1
2
3
4
5
6
7
8
9
this will print AFTER the loop ends
See how it only printed after the loop ended? That is because of the indentation. You should correct your code and indent it properly...
Ok, I corrected the code and it seems to be working now. Most of it was because of the indentation. Please try to understand how it works...
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result #this was out indented
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a guessing number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess) # this was out indented
print("Correct!\nWell done\n\n") # this all the way to the bottom was out indented
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the awesome number game. Goodbye")
done = True
It looks like adding a little structure would help you out.
Something like this might help you with doing your control flow. Hopefully gives you an outline that makes sense and makes it easier to run the loop multiple times.
""" Guess the number game.
"""
import random
def is_same(targ, num):
""" Check for correct entry. """
if targ == num:
result = "WIN"
elif targ > num:
result = "LOW"
else:
result = "HIGH"
return result
def play_game():
""" Play the game 1 time, returns play_again """
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print("""\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""")
Choose_Level = input("\t\tPlease choose your Level : ")
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
# this could be simplified to: while choose_level not in 'EMF':
Choose_Level = input("Sorry. You must type in one of the letters " +
"'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! " +
"You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1, 10)
elif Choose_Level == "M":
computer_number = random.randint(1, 50)
else:
computer_number = random.randint(1, 100)
counter = 1
higher_or_lower = ""
while higher_or_lower != "WIN":
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter += 1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
print("\nSorry, you are to low. Please try again.\n:")
elif higher_or_lower == "HIGH":
print("Guess attempts", counter)
print("\nSorry, To high. Please try again. \n:")
else:
print("Correct!\nWell done\n\n")
break
print("""
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = input("\t\t Please choose a option 'S' or 'E' ")
while start_again != "S" and start_again != "E":
# can simplify: while start_again not in 'SE':
start_again = input("You must enter a upper case letter" +
"'S' or 'E' to continue")
if start_again == "S":
return True
else:
return False
def main():
""" Main loop for playing the game. """
play_again = True
while play_again:
play_again = play_game()
print("Thanks for playing the number game. Goodbye")
if __name__ == '__main__':
main()

Categories