I will post 2 scripts that are doing (supposedly) the same thing. First one is the script i created, second one is the solution from the course.
What would you consider wrong (if anything) with the script that i made? Should i think scripts more like the second one, with functions and so?
My script
import random
print(art.logo)
print("Welcome to the number guessing game! ")
print("I'm thinking of a number between 1 and 100.")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
ATTEASY = 10
ATTHARD = 5
playAgain = True
while playAgain :
numberIs = random.randint(0,100)
atteasy = ATTEASY
atthard = ATTHARD
while atteasy and atthard != 0 :
if difficulty == "easy" :
print(f"You have {atteasy} attempts remaining to guess the number. ")
guess = input("Make a guess: ")
if int(guess) == numberIs :
print(f"You are right! The number was indeed {numberIs}")
break
else :
if int(guess) > numberIs :
print("To high.")
else :
print("To low.")
atteasy = atteasy - 1
if atteasy != 0 :
print("Guess again.")
else :
print(f"You have {atthard} attempts remaining to guess the number. ")
guess = input("Make a guess: ")
if int(guess) == numberIs :
print(f"You are right! The number was indeed {numberIs}")
break
else :
if int(guess) > numberIs :
print("To high.")
else :
print("To low.")
atthard = atthard - 1
if atthard != 0 :
print("Guess again.")
if atteasy or atthard == 0 :
print(f"You lost. The numbers was {numberIs}")
break
Script from the course
For comparison, not for review:
from random import randint EASY_LEVEL_TURNS = 10 HARD_LEVEL_TURNS = 5 #Function to check user's guess against actual answer. def check_answer(guess, answer, turns): """checks answer against guess. Returns the number of turns remaining.""" if guess > answer: print("Too high.") return turns - 1 elif guess < answer: print("Too low.") return turns - 1 else: print(f"You got it! The answer was {answer}.") #Make function to set difficulty. def set_difficulty(): level = input("Choose a difficulty. Type 'easy' or 'hard': ") if level == "easy": return EASY_LEVEL_TURNS else: return HARD_LEVEL_TURNS def game(): #Choosing a random number between 1 and 100. print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100.") answer = randint(1, 100) print(f"Pssst, the correct answer is {answer}") turns = set_difficulty() #Repeat the guessing functionality if they get it wrong. guess = 0 while guess != answer: print(f"You have {turns} attempts remaining to guess the number.") #Let the user guess a number. guess = int(input("Make a guess: ")) #Track the number of turns and reduce by 1 if they get it wrong. turns = check_answer(guess, answer, turns) if turns == 0: print("You've run out of guesses, you lose.") return elif guess != answer: print("Guess again.") game()