0% ont trouvé ce document utile (0 vote)
5 vues3 pages

Exercices pratiques en Python

Transféré par

eloundoucome1
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
5 vues3 pages

Exercices pratiques en Python

Transféré par

eloundoucome1
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

HE Arc LANCO 2009 – 2010

Exercices en Python

1 Convertisseur de température
On veut écrire un programme python qui convertisse une température des degrés Celsius vers les
degrés Fahrenheit et inversément.
Formules de conversion :
Tc = 59 ∗ (T f − 32)
T f = 95 ∗ Tc + 32
où Tc est la température en degrés Celsius et T f celle en degré Fahrenheit.
Première version Le programme demandera à l’utilisateur la température, puis le sens de la conver-
sion, puis affichera le résultat, avec une précision de deux chiffres après la virgule.
Entrez une température : 12
Convertir vers des degrés (C)elsius ou (F)ahrenheit ? F
Résultat : 53.60
Deuxième version Faites-en une application en ligne de commande, le premier argument étant la
température et le second le sens de conversion.
user@host> python temp_converter.py 12 F
Résultat : 53.60
user@host>

2 Vérificateur d’URLs
Écrire un programme qui teste une URL donnée en paramètre :

C:\dir> python [Link] [Link]


Unknown URL format
C:\dir> python [Link] [Link]
Impossible to load URL
C:\dir> python [Link] [Link]
The URL is valid
C:\dir>

En utilisant [Link]() et les exceptions, c’est très simple !

1/3

distribué sous licence creative common | détails sur [Link]


HE Arc LANCO 2009 – 2010

3 Un clone de strings
La commande Unix strings sert à trouver et afficher les séquences de caractères imprimables
contenues dans un fichier binaire.
Écrire un programme en ligne de commande qui prend un nom de fichier en argument et affiche
toutes les chaînes de caractères imprimables d’une longueur supérieure ou égale à 4.
[Link] pourrait vous être utile

4 Compter les mots


Écrire un programme en ligne de commande qui prend un nom de fichier texte en argument et
affiche, en ordre alphabétique, chaque mot présent dans le fichier accompagné de son nombre d’oc-
currences.
allusion : 1
buisson : 5
définition : 2
...

5 Rot13
Écrire un programme interactif qui demande une chaîne à l’utilisateur et la convertit en codage
rot13 (décalage circulaire de 13 lettres dans l’alphabet). La conversion respectera les majuscules et
les minuscules et ne changera rien aux caractères hors de [A..Z] et [a..z].
Le programme tournera en boucle tant que l’utilisateur n’a pas entré une chaîne vide.
Exemple :
C :\> python [Link]
-> Hello
Uryyb
-> Salut, Dédé !
Fnyhg, Qéqé !
->
C :\>

2/3

distribué sous licence creative common | détails sur [Link]


HE Arc LANCO 2009 – 2010

6 Exercices facultatifs
Pour les plus rapides, les plus motivés. . . ou ceux qui connaissaient déjà python !

6.1 Un petit bug. . .


Vous avez un accès en lecture (et en exécution) au programme suivant, mais pas en écriture :
from random import randint

to_guess = randint ( 0 , 1 0 0 )

guessed = input ( " E n t r e z un nombre ( e n t r e 0 e t 1 0 0 ) : " )

i f guessed == to_guess :
p r i n t " Gagné ! "
else :
print " Perdu ! "

1. Chaque partie côute 10.– Une partie gagnée rapporte 900.–, une partie perdue rien du tout.
Pouvez-vous trouver une manière de vous enrichir à coup sûr ?
2. Le propriétaire du jeu, avant d’être ruiné, vous a engagé pour rendre son code plus sûr. Que
proposez-vous ?

7 Un petit jeu vidéo


Le cours python en ligne “Livewires” ([Link] pro-
pose un module permettant de développer facilement de petits jeux vidéos1 .
1. Installez PyGame ([Link]
2. Récupérez et décompressez l’archive ....
3. Étudiez et testez le code du fichier [Link]
4. Sur la base de cet exemple et de la doc fournie (fichier [Link]), développez un
petit jeu vidéo de votre choix.
Quelques idées pour ceux qui manquent d’inspiration :
– un casse-briques,
– un clone de Space Invaders ,
– ou de Asteroids,
– ou d’un autre jeu cité dans les “most popular games” de [Link]
wiki/Golden_age_of_arcade_games
– ...

1 Il s’agit au fait d’une couche de simplification au-dessus du module PyGame.

3/3

distribué sous licence creative common | détails sur [Link]

Common questions

Alimenté par l’IA

A Python program can verify URL formats using the urllib2 library and exceptions. By attempting to open a URL with urllib2.urlopen(), the program handles exceptions to determine if the URL is well-formed and accessible. If an exception occurs during the opening, the program can conclude the URL is either malformed or unreachable .

PyGame can be used to handle game graphics, sound, and input control, providing a foundation on which beginners can build simple games like brick-breakers or Space Invaders clones. Users can start by studying the example files and documentation available with PyGame to understand the basic game loop and event handling, then modify the code to suit their design plans .

The string.printable module provides a set of characters that are considered printable, which can be used to identify valid sequences within a binary file. This facilitates the extraction of readable text from non-text files. However, its limitation lies in the static definition of 'printable', which might not cover all character sets or languages needed in specific use cases .

Players could theoretically increase their chances by exploiting any predictable patterns in the random number generator, although true randomness should prevent this. To secure the game, the owner could implement more sophisticated randomization techniques or add logging and monitoring to detect patterns in player guesses or reported results .

An interactive Python program for ROT13 cipher can use string translation tables to convert user-input text. The program translates each character by shifting letters by 13 places while preserving case for letters A to Z and a to z, leaving other characters unchanged. It continues to prompt the user for input until an empty string is provided .

Key considerations include using secure random number generators, implementing encryption for sensitive data, ensuring code integrity, and logging transactions for audit purposes. Additionally, securing the code against reverse engineering and implementing input validation can prevent exploits related to monetary transactions .

Challenges include handling different file encodings, dealing with punctuation, and efficiently processing large files. These can be addressed by setting a consistent encoding (e.g., UTF-8), using regular expressions or string libraries to clean and split text into words, and by using data structures like dictionaries or hash maps for counting operations. Additionally, optimizing file reading by using buffers can manage large data efficiently .

The formulas to convert temperatures are Tc = 5/9 * (Tf - 32) for Fahrenheit to Celsius, and Tf = 9/5 * Tc + 32 for Celsius to Fahrenheit. A Python program can be implemented to convert user-input temperatures by first asking the user for the temperature and the desired conversion unit. It then calculates the converted temperature using the appropriate formula and displays the result with two decimal precision .

A command-line Python program can use a dictionary to store word occurrences. By reading the file line by line and splitting each line into words, the program increments the count of each word in the dictionary. Once all words are counted, it sorts the dictionary keys alphabetically and prints each word with its count .

To replicate the Unix 'strings' command in Python, a program would read a binary file and extract sequences of printable characters using string.printable. By iterating over the file content, the program identifies and prints sequences longer than or equal to 4 characters, effectively mimicking the 'strings' command functionality .

Vous aimerez peut-être aussi