Toolbending::Python
Sommaire
- 1 Think like a computer scientist?
- 2 Python!
- 3 Types d'erreurs et déboguage
- 4 Syntaxe de programmation
- 5 Liste, tableau
- 6 Concaténer
- 7 Itérations
- 8 Utiliser un fichier externe
- 9 Utiliser des commandes Bash dans Python
- 10 Sélection aléatoire
- 11 User input
- 12 Stocker son script dans un fichier
- 13 All work no play
- 14 All together now
Think like a computer scientist?
Dans le discours traditionnel des acteurs du logiciel libre, la libération de la partie informationnelle que constitue le code permet d’en prendre le contrôle : son ouverture permet son appropriation par les utilisateurs qui peuvent alors redéfinir selon leurs propres critères les modalités et finalités de leurs outils. Mais si l’ouverture du code est une invitation à s’engager dans l’élaboration de nos outils, nous nous rendons compte dans la pratique que cette affirmation évacue le fait que le contrôle se fait toujours au détriment de quelqu’un d’autre. Les programmeurs contrôlent le code ; les designers, le design ; les typographes, la typographie, etc. Dans chaque cas de figure, il faut en premier lieu pouvoir pénétrer la culture qui l’entoure, rentrer dans le cercle. Pour nous, le libre suggère avant tout la volonté d’accepter de perdre un hypothétique contrôle, de lâcher du lest. Cela signifie questionner ses certitudes, au bénéfice de recevoir en retour quelque chose de nouveau. [1]
Python!
Python est un langage portable, dynamique, extensible, gratuit, qui permet (sans l'imposer) une approche modulaire et orientée objet de la programmation. Python est développé depuis 1989 par Guido van Rossum et de nombreux contributeurs bénévoles. [2]
Twenty things to do with a Python script
Python partage beaucoup de principes de programmation avec d’autres langages populaires comme php, javascript ... Une fois qu’on apprend Python, on peut facilement passer à un langage ayant le même paradigme de programmation.
P.S. Cet introduction se base sur La Semaine Python (Stéphanie Villayphiou pour Les Samedies [1]) et How to think like a computer scientist (en français : Apprendre à programmer avec Python [2]).
Console interactive
$ python >>>
Arrêter la console Python:
>>> exit()
A partir d'un fichier
$ python nom_fichier.py
Types d'erreurs et déboguage
Erreur syntaxique
Le programme ne s’exécute pas complètement et donne une erreur.
Il s’agit d’une erreur de syntaxe: orthographe, ponctuation manquante, mauvaise indentation ...
Erreur sémantique ou de logique
Le programme s’exécute entièrement mais le résultat n’est pas celui escompté.
Il y a une erreur dans le raisonnement! Vérifier les résultats de variables et de fonctions aux endroits problématiques
Erreur d’exécution ou d’exception
Apparaît lorsque le programme fonctionne déjà, mais que des circonstances particulières apparaissent.
Ex. un fichier qui n’existe plus, se trouve ailleurs ou a été renommé.
Syntaxe de programmation
'Échapper' les caractères spéciaux:
>>> print "Hello \n World"
'Échapper' les caractères:
>>> print "Hello \\n World"
Chaîne de caractères:
>>> bonjour = "hello" >>> print "bonjour" >>> print bonjour
Par défaut, les nombres sont des nombres entiers par exemple:
>>> 20 / 3 = 6 >>> 20. / 3 = 6.333333335 >>> 20 / 3. = 6.3333333335
Commentaire:
>>> # This is a comment
Liste, tableau
Reconnaissable par ses crochets [ ]
La numérotation des listes commence à 0:
>>> travail = ["washing", "cleaning", "cooking"] >>> print travail[1] Cleaning
Ajouter un élément à la fin d’une liste:
>>> travail.append("preserving") >>> print travail ["washing", "cleaning", "cooking", "preserving"]
Effacer un élément d’une liste en spécifiant son index:
>>> travail = ["washing", "cleaning", "cooking"] >>> del travail[2] >>> print travail
["washing", "cleaning"]
Effacer un élément d’une liste en spécifiant sa valeur:
>>> travail = ["washing", "cleaning", "cooking"] >>> travail.remove("cleaning") >>> print travail ["washing", "cooking"]
Sélectionner une partie d’une liste (attention! le type du résulat obtenu est une liste, même s’il n’y a qu’un seul élément.)
>>> travail = ["washing", "cleaning", "cooking"] >>> print travail[1:2] ["cleaning"]
Variables
Une variable permet de stocker des données.
- Le nom ne peut comporter que des lettres, chiffres et l’underscore _
- Le nom commence forcément par une lettre
- Le nom est sensible à la casse
Liste de mots à ne pas utiliser dans des noms de variables, car ce sont des mots essentiels au fonctionnement de Python:
- and
- assert
- break
- class
- continue
- def
- del
- elif
- else
- except
- exec
- finally
- for
- from
- global
- if
- import
- in
- is
- lambda
- not
- or
- pass
- raise
- return
- try
- while
Concaténer
La concaténation est une liaison de 2 éléments. Concaténation de deux chaînes de caractères:
>>> "bon" "jour" bonjour >>> "bon" + "jour" bonjour
Concaténation de deux listes:
>>> travail = ["washing", "cleaning", "cooking"] >>> travail + travail >>> ["washing", "cleaning", "cooking", "washing", "cleaning", "cooking"]
>>> 3 * "bla" blablabla
Nous ne pouvons pas concatener deux types d’éléments. Pour temporairement transformer un chiffre (integer ou float) dans un texte (string):
>>> nombre = 9 >>> print str(nombre) + " is a number." 9 is a number
Pour temporairement transformer un texte (string) dans un chiffre (integer ou float):
>>> nombre = "9" >>> float(nombre) >>> float str(nombre) * 3 27
Conditions
if attention -- indentation!:
>>> nombre1 = 4 >>> nombre2 = 5 >>> if nombre1 < nombre2: >>> print str(nombre1) + " est plus petit que " + str(nombre2)
if/else
>>> if nombre1 < nombre2: >>> print nombre1 + " est plus petit que " + nombre2 >>> else: >>> print str(nombre1) + " est plus grand que " + str(nombre2)
elif, if, else
if condition: if condition:
If the first statement is true, its code will execute. Also, if the second statement is true, its code will execute.
if condition: elif condition:
The second block will only execute here if the first one did not, and the second check is true.
if condition: else:
The first statement will execute if it is true, while the second will execute if the first is false.
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html
Opérateurs
== égal
!= différent de
< plus petit que
<= plus petit ou égal
> plus grand que
>= plus grand ou égal
and & et
| or ou
not ne pas
Itérations
Boucles avec for
>>> for i in range(1, 5): ... print i 1 2 3 4
While (tant que) : boucle et test en même temps
>>> # on affiche i tant qu'il est plus petit que 10 >>> i = 0 >>> while (i<10): ... i = i + 1 ... print i
Utiliser un fichier externe
Lire un fichier:
>>> fichier = open("chemin_fichier/nom_fichier.txt", "r") >>> for ligne in fichier.readlines(): >>> print ligne >>> fichier.close()
Écrire dans un fichier:
>>> contenu = "Servicing procedures are repeated throughout the duration of the exhibition." >>> fichier = open("chemin_fichier/nom_fichier.txt", "w") >>> fichier.write("contenu") >>> fichier.close()
Utiliser des commandes Bash dans Python
>>> import os >>> commande = "echo 'Bonjour monde'" >>> os.system(commande) Bonjour monde
>>> import os >>> commande = "espeak 'Bonjour monde'" >>> os.system(commande)
>>> import os >>> travail = ["washing", "cleaning", "cooking"] >>> for todo dans travail: ... commande = "espeak "+todo ... os.system(commande)
Sélection aléatoire
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
import random
- input sentence
words = ["i", "love", "you", "very", "much"]
- amount of repetitions
repetitions = 300
- print one random word from the list
print(random.choice(words))
- repeatedly select a random word
for i in range(repetitions):
select = random.choice(words) print select + " *",
</syntaxhighlight>
User input
>>> input_chore = raw_input("Please type your least favorite chore: ") Please type your least favorite chore: "washing dishes" >>> input_name = raw_input("What is your name? ") What is your name? "Femke" >>> input_gender = raw_input("Are you male or female? ") Are you male or female? "Female" >>> if input_gender == "male": ... gender = "boy" ... >>> elif input_gender == "female": ... gender = "girl" ... >>> i = 0 >>> while (i < 100): ... i +=1 ... print ("All " + input_chore + " and no play makes " + input_name + " a dull " + gender) ... All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl All washing dishes and no play makes Femke a dull girl
Stocker son script dans un fichier
Dans un editeur de texte. Sauver sous allworknoplay.py
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_chore = raw_input("Please type your least favorite chore: ") input_name = raw_input("What is your name? ") input_gender = raw_input("Are you male or female? ")
- ERROR SEMANTIQUE FOUND BY LOUISE! IN YOUR PROGRAMME, REPLACE THE SECOND INSTANCE OF if: BY elif:
if input_gender == "male":
gender = "boy"
elif input_gender == "female":
gender = "girl"
elif input_gender == "I am a bird":
gender = "bird"
else: gender="something else"
i = 0 while (i < 100):
i +=1 print ("All " + input_chore + " and no play makes " + input_name + " a dull " + gender)
</syntaxhighlight>
Dans le terminal:
$ python allworknoplay.py
P.S.: N'oubliez pas à ajouter la condition "else" en cas là réponse sera pas exactement comme prévu par ton programme !
<syntaxhighlight lang="python"> else:
# put some action here that will happen in case the answer is not caught by the if statement
</syntaxhighlight>
All work no play
Laurent
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_hello = raw_input("J'aimerais en savoir plus sur toi afin de comprendre pourquoi tu utilises cet ordinateur. ")
input_gender = raw_input("Tu es: homme ou femme?") input_year = raw_input("Quel âge as-tu?") input_social = raw_input("Utilises-tu facebook: oui ou non?") input_status = raw_input("Es-tu en couple: oui ou non?")
if input_gender == "homme" genderanswer = "un homme" elif input_gender == "femme" genderanswer = "une femme" else: yearanswer = "un hermaphrodite"
if input_year == "12, 13, 14, 15, 16, 17": yearanswer = "malgré ses boutons" elif input_year == "18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29" : yearanswer = "malgré ses études " elif input_year == "30, 31, 32, 33, 34, 35, 36, 37, 38, 39" : yearanswer = "malgré ses responsabilités " elif input_year == "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59" : yearanswer = "malgré ses complexes physiques " else: yearanswer = "d'un mystère effrayant"
if input_social == "oui": socialanswer = "cherche désespérément le grand amour sur facebook" elif input_social == "non": socialanswer = "cherche désespérément le grand amour dans les bars" else: socialanswer = "cherche désespérément un coup vite fait"
if input_status == "oui": statusanswer = "alors que son couple bat de l'aile" elif input_status == "non": statusanswer = "voulant mettre fin à sa solitude qui n'a que trop duré" else: statusanswer = "mais attend patiemment que ça tombe du ciel"
i = 0
while (i < 100):
i +=1
print ("Tu es" + genderanswer + ", qui, " + yearanswer +" "+ socialanswer+", "+ statusanswer + ", et ben bravo !" ) </syntaxhighlight>
Arnaud
Aurélien
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_hello = raw_input("Bienvenue, tu as le chance de communiquer avec moi. Je m'appel Pierre et je suis l'esprit d'un caillou. Ne trouves-tu pas cela incroyable ?")
input_gender = raw_input("Ma webcam est en panne, es-tu une fille ?") input_like = raw_input("Tu aimes les cailloux ?") input_homo = raw_input("Formidable, as-tu déjà joué avec des cailloux ?")
if input_gender == "oui": genderanswer = "petite coquine" elif input_gender == "non" : genderanswer = "mon coquinou" else: genderanswer = "petit truc"
if input_like == "oui": likeanswer = "me faire sortir d'ici" elif input_like == "non": likeanswer = "trouver ou ils sont parti" else: likeanswer = "faire quelque chose"
if input_great == "oui" : greatanswer = "qu'on puisse s'amuser toi et moi :-o" elif input_great == "non" : greatanswer = "que je te montre à quoi ça sert un cailloux..." else: greatanswer = "misanthrope"
i = 0 while (i < 100):
i +=1
print ("Alors écoute moi bien" + genderanswer + " tu vas vite " + likeanswer+ " "+ greatanswer + " lol " )
</syntaxhighlight>
Ben
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_hello = raw_input("salut petite perle! Ça Gaze ?")
input_Depardieu = raw_input("On est pas bien la ? hein ? Tu les sens les coussins en cuir ? ") input_depardieu1 = raw_input("Ça fait du bien hein ?") input_phoque = raw_input("Dis moi petite perle ! Tu viendrais pas cassé une petite croute à la maison ?")
if input_Depardieu == "ouai je l'ai sens"or"ouai"or "oui": Depardieuanswer = "ça va ! ferme la maintenant " elif input_Depardieu == "non" or "je sens rien": Depardieuanswer = "Bouge pas j'arrive. Tu vas bientot sentir tout le cuir" else: Depardieuanswer = "qu'est ce qu'on est bien"
if input_depardieu1== "oui": depardieu1answer = "Je t'aime bien toi !" elif input_depardieu1 == "non": depardieu1answer = "Mais si ça fait du bien. Detends toi un peu." else: depardieu1answer = "Y a pas à chié du cul . Je suis bien garé dans le fauteuil"
if input_phoque == "dis ! tu serais pas pédé par hasard ? " : phoqueanswer = "Alors tu viens la cassé cette croute ?" elif input_phoque == "non" : phoqueanswer = "Tu as autre chose prévu ?" else: phoqueanswer = "J'ai fait un bon boeuf bourguignon"
i = 0 while (i < 100):
i +=1
print ("Bon" + Depardieu + " Je te le dis " + depardieu1answer + "sinon "+ phoqueanswer )
</syntaxhighlight>
Hendrick
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_word = raw_input("Please say hello: ") input_name = raw_input("What is your name? ") input_gender = raw_input("Are you real or unreal? ")
if input_gender == "real": gender = "boy" elif input_gender == "unreal": gender = "girl" else: gender = "something else"
i = 0 while (i < 100): i +=1 print ("All " + input_word + " and no play makes " + input_name + " a dull " + gender) </syntaxhighlight>
Benjamin
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_feel = raw_input("Hello, bel informaticien, comment vas-tu ? ")
input_gender = raw_input("Approche toi de ton écran, j'arrive à peine à discerner ton visage \n Est-tu un garçon ou peut etre une fille ? ")
if input_gender == "un garçon": beautiful= " quel bel homme ce " elif input_gender == "une fille": beautiful= " quelle beauté cette " else: beautiful= "autre chose "
input_name = raw_input("Oh, et quel est ton petit nom ? ")
input_know = raw_input("Ah, j'ai connu quelqu'un s'appeler " + input_name + beautiful + input_name + " Entre nous... Il est des choses qui ne sont pas faciles à avouer mais depuis le départ de " + input_name + " j'ai beaucoup de mal.... Tu es toujours là ?")
("Oh, j'ai tant besoin d'amour !" + input_name + " ! Partons vite !!! Je t'aime tant. Partons, n'importe où, où tu veux !!! Vite. Caracas, Lima, Bratislava. Q'importe si nos petits coeurs restent réunis")
i = 1
while (i < 1000):
i +=1
print "Je t'aime !! <3 ",
</syntaxhighlight>
Etienne
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_intro = raw_input ("Hey! J'imagine que si tu es ici c'est que t'as pas de temps a perdre je m'trompe?") input_intro2 = raw_input ("Alors dans ce cas on va faire fissa ") input_color = raw_input ("Pour commencer, il me faudrait une couleur qui te fait gerber:") input_gender = raw_input ("Good! Maintenant faut que tu me dises si tu te vois plutot (1) avec une barre de fer dans chaque main a casser du facho pendant tes insomnies ou bien, (2) a tagger les murs de ta ville, de jour, de nuit, tu t'en fou t'facon tu te fais jamais choper! ")
if input_gender =="1":
gender = "mais sois tranquile tu vas le fumer peper cet ours en pluche" input_gender = raw_input ("Et si ce Faf que t'eclaterais s'etait un monstre, tu le verrais comment?")
if input_gender =="2":
gender ="par contre je srai toi, je commencerai a courir tout de suite meme si, malin comme t'es t'auras surment une bonne idee pour t'en depetre!" input_gender = raw_input ("Et si la ville c'etait une creature, tu prefererais poser ton blaz sur quel genre de raclure?")
input_name = raw_input ("Bon ca m'a pas l'air mal tout ca, c'est quoi ton nom au fait? ")
i = 0 while (i < 2):
i +=1 print ("T'es un-e vrai-e corriace " + input_name + " on dirait bien que t'as la haine des " + input_gender +" "+ input_color +" "+ gender)
</syntaxhighlight>
Joseph
<syntaxhighlight lang="bash">
MacBook-Pro-de-Joseph:~ Joseph$ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> input_chore = raw_input ("Quand est ce que tu as travaillé sur python ? ") Quand est ce que tu as travaillé sur python ? "Hier" >>> input_name = raw_input ("Cela fait de toi un ? ") Cela fait de toi un ? "Enfoiré" >>> input_gender = raw_input ("De première ou de seconde zone ? ") De première ou de seconde zone ? "première" >>> i = 0 >>> while (i < 100): ... i +=1 ... print ("Tu as travillé sur python " + input_chore + " t'es le plus gros " + input_name + " de l'histoire de la zone " + input_gender) ... Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "première" </syntaxhiglight>
<syntaxhighlight lang="bash"> MacBook-Pro-de-Joseph:~ Joseph$ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> input_chore = raw_input ("Quand est ce que tu as travaillé sur python ? ") Quand est ce que tu as travaillé sur python ? "Hier" >>> input_name = raw_input ("Cela fait de toi un ? ") Cela fait de toi un ? "Enfoiré" >>> input_gender = raw_input ("De première ou de seconde zone ? ") De première ou de seconde zone ? "de première" >>> i = 0 >>> while (i < 100): ... i +=1 ... print ("Tu as travillé sur python " + input_chore + " t'es le plus gros " + input_name + " de l'histoire de la zone " + input_gender) ... Tu as travillé sur python "Hier" t'es le plus gros "Enfoiré" de l'histoire de la zone "de première" </syntaxhighlight>
Louise
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_hello = raw_input("Bonjour! A qui ai-je l'honneur s'il vous plait? ")
input_want = raw_input("Voulez-vous aller faire les courses aujourd'hui? oui ou non : ")
if input_want == "oui":
liste = ["pomme","poire","tomates","lait","oeuf","poulet","salade","jambon","pain","sel"] for chose in liste: print chose input_fait = raw_input ("Maintenant que vous avez la liste, voulez-vous faire autre chose? oui ou non : ") if input_fait == "oui" : input_joke = raw_input ("Voulez-vous entendre une blague? oui ou non : ") if input_joke == "oui" : print "\nMonsieur et Madame Talu ont quatre fils, comment s'appellent-ils?\n....\nIls s'appellent tous les quatre Jean.\n Les Quatre Jean Talu !" elif input_joke == "non" : input_dontwant = raw_input ("Peut-etre preferez-vous aller vous promener et prendre l'air. oui ou non : ") if input_dontwant == "oui": print "Eh bien... BOUGE TES FESSES DE CET ORDINATEUR\n NONDIDJU VA!!!" import os commande = "say -v Amelie Eh Bien ... BOUGE TES FESSES DE CET ORDINATEUR NONDIDJU VA &" commande2 = "osascript -e 'set volume 7'"
os.system(commande) os.system(commande2) elif input_dontwant == "non" : input_god = raw_input ("Alors " + input_hello + " vous voudriez eventuellement parler a un dieu? oui ou non : ") if input_god == "oui" : input_lequel = raw_input ("Quel est le dieu auquel vous voudriez parler? Dieu, Bouddha, Shiva ou Allah : ") if input_lequel == "Dieu" : print "Mais Dieu n'existe pas" elif input_lequel == "Bouddha" : print "Bouddha est en toi. Deeper" import os bouddha = ["Bouddha est en toi","deeper"] for todo in bouddha: commande = "say -v Albert "+todo os.system(commande) elif input_lequel == "Shiva" : input_shiva = raw_input ("Hello, I am Shiva. What do you want to talk about?") if input_shiva == " " : print input_hello + " apprends a ecrire" else : print "Actually, I don't really give a shit, I'm kinda busy with my six arms. See you in your next life" import os commande = "open -a Firefox http://www.dailymotion.com/video/x11zust_shivashtkam-lord-shiva-devotional-3d-animation-god-bhajan-songs-maha-shivaratri-special_music" os.system(commande) elif input_lequel == "Allah" : input_allah = raw_input ("Je vous ecoute, de quoi voulez vous discuter?") if input_allah == " " : print input_hello + " apprends a ecrire" else : print "Allah Wekbar" import os commande = "open -a Firefox&" commande1 = "say -v Ralph Allah Wekbar" os.system(commande) os.system(commande1) else : print input_hello + " apprends a ecrire" elif input_god == "non" : print "Foutu ahteiste, " + input_hello else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" elif input_fait == "non" : input_ennui = raw_input (input_hello + " me trouvez-vous ennuyant que vous ne veuillez pas passer plus de temps avec moi? oui ou non : ") if input_ennui == "oui" : print "Je suis extremement vexe! Au revoir " + input_hello elif input_ennui == "non" : input_q = raw_input (input_hello + ", je suis heureux de savoir que vous ne me haissiez pas. Qu'en pensez-vous? ") input_joke = raw_input ("Voulez-vous entendre une blague? oui ou non : ") if input_joke == "oui" : print "\nMonsieur et Madame Talu ont quatre fils, comment s'appellent-ils?\n....\nIls s'appellent tous les quatre Jean.\n Les Quatre Jean Talu !" elif input_joke == "non" : input_dontwant = raw_input ("Peut-etre preferez-vous aller vous promener et prendre l'air. oui ou non : ") if input_dontwant == "oui": print "Eh bien... BOUGE TES FESSES DE CET ORDINATEUR\n NONDIDJU VA!!!" import os commande = "say -v Amelie Eh Bien ... BOUGE TES FESSES DE CET ORDINATEUR NONDIDJU VA &" commande2 = "osascript -e 'set volume 7'"
os.system(commande) os.system(commande2) elif input_dontwant == "non" : input_god = raw_input ("Alors " + input_hello + " vous voudriez eventuellement parler a un dieu? oui ou non : ") if input_god == "oui" : input_lequel = raw_input ("Quel est le dieu auquel vous voudriez parler? Dieu, Bouddha, Shiva ou Allah : ") if input_lequel == "Dieu" : print "Mais Dieu n'existe pas" elif input_lequel == "Bouddha" : print "Bouddha est en toi. Deeper" import os bouddha = ["Bouddha est en toi","deeper"] for todo in bouddha: commande = "say -v Albert "+todo os.system(commande) elif input_lequel == "Shiva" : input_shiva = raw_input ("Hello, I am Shiva. What do you want to talk about?") if input_shiva == " " : print input_hello + " apprends a ecrire" else : print "Actually, I don't really give a shit, I'm kinda busy with my six arms. See you in your next life" import os commande = "open -a Firefox http://www.dailymotion.com/video/x11zust_shivashtkam-lord-shiva-devotional-3d-animation-god-bhajan-songs-maha-shivaratri-special_music" os.system(commande) elif input_lequel == "Allah" : input_allah = raw_input ("Je vous ecoute, de quoi voulez vous discuter?") if input_allah == " " : print input_hello + " apprends a ecrire" else : print "Allah Wekbar" import os commande = "open -a Firefox" commande1 = "say -v Ralph Allah Wekbar" os.system(commande) os.system(commande1) else : print input_hello + " apprends a ecrire" elif input_god == "non" : print "Foutu ahteiste, " + input_hello else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!"
if input_want == "non":
input_joke = raw_input ("Voulez-vous entendre une blague? oui ou non : ") if input_joke == "oui" : print "\nMonsieur et Madame Talu ont quatre fils, comment s'appellent-ils?\n....\nIls s'appellent tous les quatre Jean.\n Les Quatre Jean Talu !" elif input_joke == "non" : input_dontwant = raw_input ("Peut-etre preferez-vous aller vous promener et prendre l'air. oui ou non : ") if input_dontwant == "oui": print "Eh bien... BOUGE TES FESSES DE CET ORDINATEUR\n NONDIDJU VA!!!" import os commande = "say -v Amelie Eh Bien ... BOUGE TES FESSES DE CET ORDINATEUR NONDIDJU VA &" commande2 = "osascript -e 'set volume 7'"
os.system(commande) os.system(commande2) elif input_dontwant == "non" : input_god = raw_input ("Alors " + input_hello + " vous voudriez eventuellement parler a un dieu? oui ou non : ") if input_god == "oui" : input_lequel = raw_input ("Quel est le dieu auquel vous voudriez parler? Dieu, Bouddha, Shiva ou Allah : ") if input_lequel == "Dieu" : print "Mais Dieu n'existe pas" elif input_lequel == "Bouddha" : print "Bouddha est en toi. Deeper" import os bouddha = ["Bouddha est en toi","deeper"] for todo in bouddha: commande = "say -v Albert "+todo os.system(commande) elif input_lequel == "Shiva" : input_shiva = raw_input ("Hello, I am Shiva. What do you want to talk about?") if input_shiva == " " : print input_hello + " apprends a ecrire" else : print "Actually, I don't really give a shit, I'm kinda busy with my six arms. See you in your next life" import os commande = "open -a Firefox http://www.dailymotion.com/video/x11zust_shivashtkam-lord-shiva-devotional-3d-animation-god-bhajan-songs-maha-shivaratri-special_music" os.system(commande) elif input_lequel == "Allah" : input_allah = raw_input ("Je vous ecoute, de quoi voulez vous discuter?") if input_allah == " " : print input_hello + " apprends a ecrire" else : print "Allah Wekbar" import os commande = "open -a Firefox" commande1 = "say -v Ralph Allah Wekbar" os.system(commande) os.system(commande1) else : print input_hello + " apprends a ecrire" elif input_god == "non" : print "Foutu ahteiste, " + input_hello else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!" else : print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!"
else :
print input_hello + " ecrire oui ou non ca n'est quand meme pas complique nondedjeu!!!"
</syntaxhighlight>
Nelson
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_hello = raw_input("Coucou j'aimerais t'insulter mais je ne te connais pas. Veux-tu bien repondre a mes questions afin de t'insulter avec qualite? ")
input_gender = raw_input("t'es quoi: homme ou femme ?") input_god = raw_input("tu crois en Dieu?") input_ego = raw_input("tu crois en toi?") input_homo = raw_input("Tu kiffes plus les jeunes ou les vieux?")
if input_gender == "homme": genderanswer = "de macho" elif input_gender == "femme" : genderanswer = "de feministe" else: genderanswer = "d'erreur de la nature"
if input_god == "oui": godanswer = "naif" elif input_god == "non": godanswer = "tetu" else: godanswer = "abruti"
if input_ego == "oui": egoanswer = "egocentrique" elif input_ego == "non": egoanswer = "suicidaire" else: egoanswer = "handicape"
if input_homo == "jeunes" : homoanswer = "pedophile" elif input_homo == "vieux" : homoanswer = "necrophile" else: homoanswer = "misanthrope"
i = 0 while (i < 100):
i +=1
print ("Espece de putain " + genderanswer + " " + godanswer +" "+ egoanswer+" "+ homoanswer + " de merde !!!" )
print (" .-. ")
print (" |U| " )
print (" | | ")
print (" | | ")
print (" _| |_ ")
print (" | | | |-. ")
print (" /| ` | ")
print (" | | | ")
print (" | | ")
print (" \ / ")
print (" | | ")
print (" | | ")
</syntaxhighlight>
Pierre
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
list = ("lion ","dog ","unicorn ","whale"," monkey","tiger","buffalo","cat ","pinguin","beaver","rooster" )
input_animal = raw_input ("what animal are you ?") print input_animal input_really = raw_input("how do you know you are a " + input_animal +"? " + "please press ENTER") input_choose = raw_input("let me check it... press ENTER key") input_animal = raw_input ("choose another animal ?") input_fake = raw_input("i think you rather look like a little goat" +" don't you think so ?") input_well = raw_input("well done press..... press ENTER key") input_well =raw_input("i thougth you were a human being but if you do insist i surrender ok ?")
if input_animal in list:
print "animal in list let's move on"
else:
print "animal not in list sorry quit the program big liar" animal="animal"
if input_fake == "input_fake": fake = "input_animal" else: animal="animal"
i = 0 while (i < 100):
i +=1 print ("you are right " + input_animal + " seems to be " + " a brave " + animal)
</syntaxhighlight>
Quentin
<syntaxhighlight lang="python">
>>> input_chore = raw_input (« le pire moment de l’annee « ) Le pire moment de l’annee « Janvier » >>> input_name = raw_input (« le pire prenom de l’annee « ) Le pire prenom de l’annee « Quentin » >>> input_day = raw_input (« le pire moment de cette journee ») Le pire moment de cette journee « la soiree » >>> if input_chore == « Janvier » : … chore = « cotations » … >>> if input_name == “Quentin”: … name = “L’Homme” … >>> if input_day == “la soiree”: … day = “la veille” … >>> i = 0 >>> while (i < 100): … i +=1 … print (input_name + “qui travaillait” + input_day + « de ses » + input_chore) … L’Homme qui travaillait la veille de ses cotations
</syntaxhighlight>
Sarah
<syntaxhighlight lang="python">
input_word = raw_input("Please say hello:") input_name = raw_input("What is your name? ") input_gender = raw_input("Are you real or unreal? ") if input_gender == "real":
gender = "boy"
elif input_gender == "unreal":
gender = "girl"
i = 0 while (i < 100):
i +=1 print ("All " + input_word + " and no play makes " + input_name + " a dull " + gender)
</syntaxhighlight>
Laurent
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
input_hello = raw_input("J'aimerais en savoir plus sur toi afin de comprendre pourquoi tu utilises cet ordinateur. ")
input_gender = raw_input("Tu es: homme ou femme?") input_year = raw_input("Quel âge as-tu?") input_social = raw_input("Utilises-tu facebook: oui ou non?") input_status = raw_input("Es-tu en couple: oui ou non?")
if input_gender == "homme" genderanswer = "un homme" elif input_gender == "femme" genderanswer = "une femme" else: yearanswer = "un hermaphrodite"
if input_year == "12, 13, 14, 15, 16, 17": yearanswer = "malgré ses boutons" elif input_year == "18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29" : yearanswer = "malgré ses études " elif input_year == "30, 31, 32, 33, 34, 35, 36, 37, 38, 39" : yearanswer = "malgré ses responsabilités " elif input_year == "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59" : yearanswer = "malgré ses complexes physiques " else: yearanswer = "d'un mystère effrayant"
if input_social == "oui": socialanswer = "cherche désespérément le grand amour sur facebook" elif input_social == "non": socialanswer = "cherche désespérément le grand amour dans les bars" else: socialanswer = "cherche désespérément un coup vite fait"
if input_status == "oui": statusanswer = "alors que son couple bat de l'aile" elif input_status == "non": statusanswer = "voulant mettre fin à sa solitude qui n'a que trop duré" else: statusanswer = "mais attend patiemment que ça tombe du ciel"
i = 0
while (i < 100):
i +=1
print ("Tu es" + genderanswer + ", qui, " + yearanswer +" "+ socialanswer+", "+ statusanswer + ", et ben bravo !" )
All together now
Open a webpage
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
import os
question = raw_input("What are you looking for? ") commande = "firefox https://duckduckgo.com/?q="+question os.system(commande) </syntaxhighlight>
MacOSX
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
import os
question = raw_input("What are you looking for? ") commande = "open -a firefox https://duckduckgo.com/?q="+question os.system(commande) </syntaxhighlight>
Read a sound
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
import os travail = ["washing", "cleaning", "cooking"] for todo in travail: commande = "espeak "+todo os.system(commande) </syntaxhighlight>
Write to a file
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
name = raw_input('Enter name of text file: ')+'.txt' fichier = open(name,'a+') contenu = raw_input('Type something to write to the file: ') fichier.write(contenu + '\n') fichier.close() </syntaxhighlight>
Read from a file
<syntaxhighlight lang="python">
- -*- coding: UTF8 -*-
- ! /usr/bin/env python
text = "hello.txt" text = open(text, 'r') </syntaxhighlight>
- ↑ OSP, ReLearn http://ospublish.constantvzw.org/blog/wp-content/uploads/osp-bat-10-10-1.pdf
- ↑ Stéfane Fermigier dans http://www.inforef.be/swi/download/python_notes.pdf