IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

Instruction différente si la variable n'est pas un nombre


Sujet :

Python

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut Instruction différente si la variable n'est pas un nombre
    Bonjour à tous !

    Je débute en Python et en programmation tout court d'ailleurs, et j'aurais bien besoin de votre expérience !

    J'ai chercher pendant de longues heures une solution à mon problème mais je ne vois pas comment le résoudre.
    Je cherche à exécuter une instruction si une variable "choixNb" n'est pas un nombre (message d'erreur).

    Voici mon code de base qui normalement fonctionne plutôt bien tant que je n'ajoute pas cette instruction :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    import os
     
    def ArabicToRoman():
     
        choixNb = int(input("Saisissez un nombre entre 1 et 4999 : "))
     
        arabicToRoman = ""
        nbRomainMilliers = ""
        nbRomainCentaines = ""
        nbRomainDizaines = ""
        nbRomainUnites = ""
     
        if choixNb >= 1 and choixNb <= 4999:
     
            milliers = choixNb//1000
     
            if(milliers):           
                for millers in range(milliers):
                    nbRomainMilliers = nbRomainMilliers + "M"
     
            choixNb = choixNb - (milliers * 1000)
            centaines = choixNb//100
     
            if(centaines):
                if (centaines == 9):
                    nbRomainCentaines = "CM"
                elif(centaines <= 3):
                    for centaines in range(centaines):
                        nbRomainCentaines = nbRomainCentaines + "C"
                elif(centaines == 4):
                    nbRomainCentaines = nbRomainCentaines + "CD"
                elif(centaines > 4):
                    nbRomainCentaines = nbRomainCentaines + "D"
                    centaines = centaines - 5
                    for centaines in range(centaines):
                        nbRomainCentaines = nbRomainCentaines + "C"
                centaines = choixNb//100
     
            choixNb = choixNb - (centaines * 100)
            dizaines = choixNb//10
     
            if(dizaines):
                if(dizaines == 9):
                    nbRomainDizaines = "XC"
                elif (dizaines <= 3):
                    for dizaines in range(dizaines):
                        nbRomainDizaines = nbRomainDizaines + "X"
                elif(dizaines == 4):
                    nbRomainDizaines = nbRomainDizaines + "XL"
                elif(dizaines > 4):
                    nbRomainDizaines = nbRomainDizaines + "L"
                    dizaines = dizaines - 5
                    for dizaines in range(dizaines):
                        nbRomainDizaines = nbRomainDizaines + "X"
                dizaines = choixNb//10
     
            choixNb = choixNb - (dizaines * 10)
     
            if(choixNb):
            	if(choixNb == 9):
            		nbRomainUnites = "IX"
            	elif(choixNb <= 3):
            		for choixNb in range(choixNb):
            			nbRomainUnites = nbRomainUnites + "I"
            	elif(choixNb == 4):
            		nbRomainUnites = nbRomainUnites + "IV"
            	elif(choixNb > 4):
            		nbRomainUnites = nbRomainUnites + "V"
            		choixNb = choixNb - 5
            		for choixNb in range(choixNb):
            			nbRomainUnites = nbRomainUnites + "I"
     
        elif(choixNb < 1 or choixNb > 4999):
            print("Soit votre nombre est nul ou négatif, soit il est supérieur à 4999. Réessayez !")
     
        arabicToRoman = (nbRomainMilliers + nbRomainCentaines + nbRomainDizaines + nbRomainUnites)
        print(arabicToRoman)
     
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
     
     
     
     
     
    os.system("pause")
    J'ai essayé en ajoutant à la première condition un elif :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    elif(choixNb < 1 or choixNb > 4999):
            print("Soit votre nombre est nul ou négatif, soit il est supérieur à 4999. Réessayez !")
    elif type(choixNb)!= int:
            print("Ceci n'est pas un nombre, veuillez saisir un nombre entre 1 et 4999 : ")
    Ça ne fonctionne pas. Si l'utilisateur entre des lettres le programme plante toujours...

    J'ai essayé aussi avec Try: et Exept: mais je ne pense pas les utiliser correctement car pour le coup : si l'utilisateur entre des lettres il y a bien un message d'erreur et le programme boucle sur l'input() mais tout le reste du programme ne fonctionne plus....

    Pouvez-vous me filer un coup de main svp ?

  2. #2
    Expert confirmé

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 307
    Par défaut
    Salut,

    Récupère d'abord l'entrée utilisateur et traite la ensuite.

    En outre, ton code est inutilement compliqué.

    Exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    from sys import exit
    
    NUMBERS = ((1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), 
            (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), 
            (4, 'IV'), (1, 'I'))
    
    def convert(n):
        roman = ''
        for numb in NUMBERS:
            e, n = divmod(n, numb[0])
            roman += ** Ici, ton code qui fait usage de numbs[x] et e **
    
        return roman
    
    def arabe_2_roman():
        while 1:
            data = input('Entrez un nombre entier entre 1 et 3999 (Q pour quitter): ')
            if data in ('Q', 'q'):
                exit()
    
            try:
                nb = int(data)
            except:
                continue
    
            if 1 > nb or nb > 3999:
                continue
    
            print("\n\tLe nombre %s s'écrit %s\n" %(nb, convert(nb)))
    
    if __name__ == '__main__':
        arabe_2_roman()
    Tu remarqueras qu'il manque la fin d'une ligne de code (la principale) je ne peut te donner une solution toute faite.

  3. #3
    Membre émérite

    Homme Profil pro
    linux, pascal, HTML
    Inscrit en
    Mars 2002
    Messages
    649
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 76
    Localisation : Belgique

    Informations professionnelles :
    Activité : linux, pascal, HTML
    Secteur : Enseignement

    Informations forums :
    Inscription : Mars 2002
    Messages : 649
    Billets dans le blog
    1
    Par défaut
    Trouvé ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    choix=0
     while choix==0:
     
        choixNB=raw_input("Entrez un nombre : ")
     
        try:
            int(choixNB)
     
            choix=1
            break
     
        except ValueError:
            print("Entrez un nombre !!!.")

  4. #4
    Membre Expert Avatar de plxpy
    Homme Profil pro
    Ingénieur géographe
    Inscrit en
    Janvier 2009
    Messages
    792
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 60
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Ingénieur géographe
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Janvier 2009
    Messages : 792
    Par défaut
    Ce code est vraiment crade ! Pourquoi introduire une variable choix, à la base de la condition du while si c'est pour sortir via le break quand la conversion en int s'est bien passé ?!?!? à oublier au plus vite. La façon de traiter la saisie par VinS est préférable (boucle "infinie" avec break quand la saisie est ok)

  5. #5
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut
    @Michel : J'ai vu cette solution mais je n'ai pas su l'inclure à mon code. J'ai essayé la manière optimisée de ce code et celle-ci non plus je ne l'ai pas utilisée correctement.

    Voici ce qui était proposé :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    while True:
        try:
            nb_car=int(raw_input("Entrez le nombre de caracteres du mdp a generer : "))
            break
        except ValueError:
            print("Entrez un nombre.")
    [EDIT]A la relecture je me rends compte que j'ai très mal utilisé ce code (notamment pas utilisé raw_input())
    mais si ce code est "crade" comment puis-je adapté mon propre code en incluant mon message d'erreur ?


    @VinsS : J'ai coder ce programme de conversion avec les choses que j'ai apprises, et que je comprends. Dans le code que tu me proposes il y a certaines choses que je ne comprends pas, donc je ne peux pas l'utiliser et encore moins le terminer (comme je vous ai dit je débute !).
    Qu'entends-tu par : "Récupère d'abord l'entrée utilisateur et traite la ensuite." ?

  6. #6
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut
    @Michel : J'ai réessayé d'adapter mon code, je m'y prends mal et ça bug :

    "Traceback (most recent call last):
    File "D:\SIO\SI2\test.py", line 84, in <module>
    ArabicToRoman()
    File "D:\SIO\SI2\test.py", line 7, in ArabicToRoman
    choixNb = int(raw_input("Saisissez un nombre entre 1 et 4999 : "))
    NameError: name 'raw_input' is not defined"

    Voilà mon code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    import os
     
    def ArabicToRoman():
     
        choix = 0
        while choix == 0:
            choixNb = int(raw_input("Saisissez un nombre entre 1 et 4999 : "))
            try:
                int(choixNb)
                choix = 1           
                break
            except ValueError:
                print("Soit vous n'avez pas saisi des chiffres, soit ils sont négatifs, nuls, ou supérieurs à 4999.")
                pass
     
        arabicToRoman = ""
        nbRomainMilliers = ""
        nbRomainCentaines = ""
        nbRomainDizaines = ""
        nbRomainUnites = ""
     
        if choixNb >= 1 and choixNb <= 4999:
     
            milliers = choixNb//1000
            if(milliers):
                for millers in range(milliers):
                    nbRomainMilliers = nbRomainMilliers + "M"
                    choixNb = choixNb - (milliers * 1000)
                    centaines = choixNb//100
     
                    if(centaines):
                        if (centaines == 9):
                            nbRomainCentaines = "CM"
                        elif(centaines <= 3):
                            for centaines in range(centaines):
                                nbRomainCentaines = nbRomainCentaines + "C"
                        elif(centaines == 4):
                            nbRomainCentaines = nbRomainCentaines + "CD"
                        elif(centaines > 4):
                            nbRomainCentaines = nbRomainCentaines + "D"
                            centaines = centaines - 5
                            for centaines in range(centaines):
                                nbRomainCentaines = nbRomainCentaines + "C"
                                centaines = choixNb//100
     
                    choixNb = choixNb - (centaines * 100)
                    dizaines = choixNb//10
     
                    if(dizaines):
                        if(dizaines == 9):
                            nbRomainDizaines = "XC"
                        elif (dizaines <= 3):
                            for dizaines in range(dizaines):
                                nbRomainDizaines = nbRomainDizaines + "X"
                        elif(dizaines == 4):
                            nbRomainDizaines = nbRomainDizaines + "XL"
                        elif(dizaines > 4):
                            nbRomainDizaines = nbRomainDizaines + "L"
                            dizaines = dizaines - 5
                            for dizaines in range(dizaines):
                                nbRomainDizaines = nbRomainDizaines + "X"
     
                    dizaines = choixNb//10
                    choixNb = choixNb - (dizaines * 10)
     
                    if(choixNb):
                        if(choixNb == 9):
                            nbRomainUnites = "IX"
                        elif(choixNb <= 3):
                            for choixNb in range(choixNb):
                                nbRomainUnites = nbRomainUnites + "I"
                        elif(choixNb == 4):
                            nbRomainUnites = nbRomainUnites + "IV"
                        elif(choixNb > 4):
                            nbRomainUnites = nbRomainUnites + "V"
                            choixNb = choixNb - 5
                            for choixNb in range(choixNb):
                                nbRomainUnites = nbRomainUnites + "I"
     
        arabicToRoman = (nbRomainMilliers + nbRomainCentaines + nbRomainDizaines + nbRomainUnites)
        print(arabicToRoman)
     
     
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
     
     
     
     
     
    os.system("pause")
    [EDIT] A priori pas de "raw_input()" sur python 3x, et si je le remplace en mettant uniquement int(input("")), le programme ne fonctionne pas.

  7. #7
    Expert confirmé

    Homme Profil pro
    Inscrit en
    Octobre 2008
    Messages
    4 307
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Octobre 2008
    Messages : 4 307
    Par défaut
    Citation Envoyé par Romenag Voir le message
    @VinsS : J'ai coder ce programme de conversion avec les choses que j'ai apprises, et que je comprends. Dans le code que tu me proposes il y a certaines choses que je ne comprends pas, donc je ne peux pas l'utiliser et encore moins le terminer (comme je vous ai dit je débute !).
    Qu'entends-tu par : "Récupère d'abord l'entrée utilisateur et traite la ensuite." ?
    Je parlais de cette partie:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
        while 1:
            data = input('Entrez un nombre entier entre 1 et 3999 (Q pour quitter): ')
            if data in ('Q', 'q'):
                exit()
     
            try:
                nb = int(data)
            except:
                continue
     
            if 1 > nb or nb > 3999:
                continue

  8. #8
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
        while 1:
            data = input('Entrez un nombre entier entre 1 et 3999 (Q pour quitter): ')
            if data in ('Q', 'q'):
                exit()
     
            try:
                nb = int(data)
            except:
                continue
     
            if 1 > nb or nb > 3999:
                continue
    Du coup en gardant mon code, il faut que je remplace ta variable nb par choixNb ?
    Parce que j'ai essayé en faisant ça et ça déconne... ou alors j'ai pas compris ?

    J'ai fait ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    import os
     
    def ArabicToRoman():
     
        while 1:
            data = input("Entrez un nombre entier entre 1 et 4999 (Q pour quitter): ")
            if data in ("Q", "q"):
                exit()
     
            try:
                choixNb = int(data)
            except:
                continue
     
            if 1 > choixNb or choixNb > 4999:
                continue
     
            arabicToRoman = ""
            nbRomainMilliers = ""
            nbRomainCentaines = ""
            nbRomainDizaines = ""
            nbRomainUnites = ""
     
            if choixNb >= 1 and choixNb <= 4999:
     
                milliers = choixNb//1000
                if(milliers):
                    for millers in range(milliers):
                        nbRomainMilliers = nbRomainMilliers + "M"
                        choixNb = choixNb - (milliers * 1000)
                        centaines = choixNb//100
     
                        if(centaines):
                            if (centaines == 9):
                                nbRomainCentaines = "CM"
                            elif(centaines <= 3):
                                for centaines in range(centaines):
                                    nbRomainCentaines = nbRomainCentaines + "C"
                            elif(centaines == 4):
                                nbRomainCentaines = nbRomainCentaines + "CD"
                            elif(centaines > 4):
                                nbRomainCentaines = nbRomainCentaines + "D"
                                centaines = centaines - 5
                                for centaines in range(centaines):
                                    nbRomainCentaines = nbRomainCentaines + "C"
                                    centaines = choixNb//100
     
                        choixNb = choixNb - (centaines * 100)
                        dizaines = choixNb//10
     
                        if(dizaines):
                            if(dizaines == 9):
                                nbRomainDizaines = "XC"
                            elif (dizaines <= 3):
                                for dizaines in range(dizaines):
                                    nbRomainDizaines = nbRomainDizaines + "X"
                            elif(dizaines == 4):
                                nbRomainDizaines = nbRomainDizaines + "XL"
                            elif(dizaines > 4):
                                nbRomainDizaines = nbRomainDizaines + "L"
                                dizaines = dizaines - 5
                                for dizaines in range(dizaines):
                                    nbRomainDizaines = nbRomainDizaines + "X"
     
                        dizaines = choixNb//10
                        choixNb = choixNb - (dizaines * 10)
     
                        if(choixNb):
                            if(choixNb == 9):
                                nbRomainUnites = "IX"
                            elif(choixNb <= 3):
                                for choixNb in range(choixNb):
                                    nbRomainUnites = nbRomainUnites + "I"
                            elif(choixNb == 4):
                                nbRomainUnites = nbRomainUnites + "IV"
                            elif(choixNb > 4):
                                nbRomainUnites = nbRomainUnites + "V"
                                choixNb = choixNb - 5
                                for choixNb in range(choixNb):
                                    nbRomainUnites = nbRomainUnites + "I"
     
        arabicToRoman = (nbRomainMilliers + nbRomainCentaines + nbRomainDizaines + nbRomainUnites)
        print(arabicToRoman)
     
     
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
    ArabicToRoman()
     
     
     
     
     
    os.system("pause")

  9. #9
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 743
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 743
    Par défaut
    Salut,

    Citation Envoyé par Romenag Voir le message
    Parce que j'ai essayé en faisant ça et ça déconne... ou alors j'ai pas compris ?
    Relisez votre code. Si l'input est différent de 'Qq', il ne sort jamais de la boucle while.
    (ajouter des "print" pour afficher les différentes étapes de traitement. Ça vous permettra de voir si elles sont atteintes ou pas).
    Puisque vous savez a peut près ce qu'est une fonction, çà serait mieux de faire la saisie du nombre avant d'appeler la fonction avec le nombre saisi en paramètre. Cela vous permettrait de mieux séparer le calcul de l'opération de saisie... Et d'avoir un code plus facile à tester.


    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Débutant] Vérifier qu'une variable ne dépasse pas le type INT
    Par ktm26 dans le forum C#
    Réponses: 9
    Dernier message: 23/03/2017, 11h45
  2. Vérifier si une variable est divisible par 10
    Par Snigz dans le forum Général Python
    Réponses: 4
    Dernier message: 05/04/2014, 17h04
  3. Comment vérifier si une variable est contenu dans un tableau ?
    Par larffas68 dans le forum Général JavaScript
    Réponses: 14
    Dernier message: 05/01/2011, 23h17
  4. Vérifier q'une variable est numérique
    Par Kishin dans le forum Langage
    Réponses: 6
    Dernier message: 20/04/2009, 17h33
  5. comment tester si une variable est de type indifined
    Par amelhog dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 10/08/2005, 09h32

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo