PROBLEMA Python, problema con if all'interno di una funzione

Francesco Gallo

Utente Attivo
165
6
Salve, sono nuovo in python e, dopo aver seguito un corso online (non molto esaudiente, difatti opterò per qualche libro come si deve) ho deciso di creare un gioco che permetta di indovinare un numero. Il problema sta nel fatto che il programma interpreta QUALSIASI input relativo al numero come ERRATO ed esegue le relative istruzioni (anche se il numero viene indovinato, motivo della stringa print(number) ).
Qualche aiuto? Dove potrei aver sbagliato?
Python:
def decor(func):
    def decor():
        print("=====================================")
        func()
        print("=====================================")
    return decor
def func():
    print("GAME CREATED BY V3nom._.")
decorated = decor(func)
decorated()
print("Hi!\nWelcome to the Guess The Number Game!")
def decore_rules(explain_rules):
    def decorator():
        print("==============================================")
        explain_rules()
        print("==============================================")
    return decorator
def explain_rules():
    print("Here are the rules:")
    print("I will choose a number between 0 and 50")
    print("I will give you some advices about the number, so you can guess it more easly")
    print("When you think you have guessed the number, write it on screen")
    print("You have 3 attempts to guess the number")
decored_rules = decore_rules(explain_rules)
def start():
    import random
    number = random.randint(0,50) #choosing the random number
    attempts = 3
    while attempts != 0:
        print("========================================")
        print(number)
        if number%(2) == 0: #start the advices about the choosen number
            print ("The number is even")
        if number%(2) != 0:
            print ("The number is odd")
        if number%(3) == 0:
            print("The number is a multiply of 3")
        if number%(3) != 0:
            print("The number isn't a multiply of 3")
        if number > 30:
            print("The number is higher than 30")
        if number < 30:
            print("The number is lower than 30")
        if number < 40:
            print("The number is lower than 40")
        if number > 40:
            print("The number is higher than 40")
        if number < 20:
            print("The number is lower than 20")
        if number > 20:
            print("the number is higher than 20")
        if number < 10:
            print("The number is lower than 10")
        if number > 10:
            print("The number is higher than 10")
        if number%(5) == 0:
            print ("The number is a multiply of 5")
        if number%(5) != 0:
            print ("The number isn't a multiply of 5") #end the advices about the number
        print("========================================")
        guess = input("So, what's the number? ")
        attempts = attempts-1
        guessed = guess==(number)
        if guessed == True:
            print("Great work!\nYou guessed the number!")
            again = input("Do you want to play again?")
            if again == "No" or again == "no":
                print("Ok, goodbye!")
            if again == "Yes" or again == "yes": #define what to do if the user want to play again
                attempts=3
                start() #call the function "start"
        if guessed == False:
            if attempts > 0:
                print("Ops...wrong number!\nTry again!",attempts,"Attempts remaining")
                guess
            if attempts == 0:
                print("No more attempts remaining!")
def start_game():
    ready = input("Are you ready? ")
    if ready == "No" or ready == "no":
            print("Ok, see you next time!") #if answer is No or no, exit the game
    if ready == "Yes" or ready == "yes": #if answer is Yes or yes, start the game
        print("Ok, let's start!") #start game rules
        know_rules = input("Do you know the rules? ")
        if know_rules == "Yes" or know_rules == "yes":
            start()
        if know_rules == "No" or know_rules == "no":
            decored_rules()
            start()
start_game()
 

clessidra

Utente Attivo
766
272
CPU
VIA C3
GPU
Ati Rage
OS
linux - Red Hat 1.1
Perchè effettui un confronto tra una stringa e un intero, quindi guessed sarà sempre False-
 

Francesco Gallo

Utente Attivo
165
6
Capisco, anche però scrivendo "if guess == number: .." e così anche per l'altra opzione comunque non esegue le istruzioni relative ad un input corretto ma SOLO quelle relative all'input errato
 

1nd33d

Utente Attivo
653
279
CPU
Intel i5 3570K @ 4,5Ghz
Dissipatore
Scythe Mugen 2
Scheda Madre
Gigabyte Z77X-UD3H
HDD
Samsung 840 PRO 256GB + Sandisk Ultra 250GB + Sandisk Plus 960GB
RAM
2x8GB Crucial Ballistix Tactical @2000Mhz CL9
GPU
XFX RX480 GTR Black Edition
Audio
Auzentech X-Fi Forte
Monitor
AOC i2369VW
PSU
Seasonic P660
Case
eh?
Periferiche
Razer Naga HEX v2
OS
Windows 10 64bit - Linux Mint 18
Capisco, anche però scrivendo "if guess == number: .." e così anche per l'altra opzione comunque non esegue le istruzioni relative ad un input corretto ma SOLO quelle relative all'input errato
Come ti ha detto l'utente sopra, "guess == number" sarà sempre False perchè sono due tipi diversi, quindi eseguirà sempre e solamente le istruzioni di input errato.
Prova con un cast da stringa a intero, quindi
Python:
guessed = int(guess) == number
 

BAT

Moderatore
Staff Forum
Utente Èlite
22,944
11,580
CPU
1-Neurone
Dissipatore
Ventaglio
RAM
Scarsa
Net
Segnali di fumo
OS
Windows 10000 BUG
La conversione in int va fatta al momento dell'acquisizione del tentativo
Python:
guess = int(input("So, what's the number? "))
altrimenti tutte le istruzioni di confronto lo interpreteranno come stringa.
Poi
Python:
if guessed == True: # NON SI PUO' VEDERE...
basta
Python:
if guessed:
analogamente
Python:
if guessed == False: # NON SI PUO' VEDERE...
dovresti scrivere
Python:
if not guessed:
 
  • Mi piace
Reazioni: Mursey

Francesco Gallo

Utente Attivo
165
6
La conversione in int va fatta al momento dell'acquisizione del tentativo
Python:
guess = int(input("So, what's the number? "))
altrimenti tutte le istruzioni di confronto lo interpreteranno come stringa.
Poi
Python:
if guessed == True: # NON SI PUO' VEDERE...
basta
Python:
if guessed:
analogamente
Python:
if guessed == False: # NON SI PUO' VEDERE...
dovresti scrivere
Python:
if not guessed:
Grazie mille per la risposta, chiedo scusa per la mia inesperienza
 

1nd33d

Utente Attivo
653
279
CPU
Intel i5 3570K @ 4,5Ghz
Dissipatore
Scythe Mugen 2
Scheda Madre
Gigabyte Z77X-UD3H
HDD
Samsung 840 PRO 256GB + Sandisk Ultra 250GB + Sandisk Plus 960GB
RAM
2x8GB Crucial Ballistix Tactical @2000Mhz CL9
GPU
XFX RX480 GTR Black Edition
Audio
Auzentech X-Fi Forte
Monitor
AOC i2369VW
PSU
Seasonic P660
Case
eh?
Periferiche
Razer Naga HEX v2
OS
Windows 10 64bit - Linux Mint 18
Tra l'altro nel caso del test su guessed sarebbe meglio qualcosa del genere, risparmiando un confronto inutile
Python:
if guessed:
   #indovinato
else:
   #non indovinato
Così come quella serie di "if" per i suggerimenti, che tra l'altro stampano un sacco di stringhe inutilmente. Se dico che un numero è minore di 30, è ovvio che sia anche minore di 40.
 
  • Mi piace
Reazioni: BAT

Entra

oppure Accedi utilizzando
Discord Ufficiale Entra ora!

Discussioni Simili