adds rot13

This commit is contained in:
waldek 2021-11-03 15:43:18 +01:00
parent 057531b177
commit db2fc0104a
1 changed files with 241 additions and 6 deletions

View File

@ -1220,24 +1220,259 @@ Think of some ways to improve on it.
Can you limit the number of tries? Can you limit the number of tries?
Can you add a feature to let the user play a *second* game after he/she wins or loses? Can you add a feature to let the user play a *second* game after he/she wins or loses?
Coming up with challenges is on of the most *challenging* aspect op learning how to program. Coming up with challenges is on of the most *challenging* aspect op learning how to program.
Your thought process will send you of into unknown territory and will force you to expand you knowledge! Your thought process will send you of into unknown territory and will force you to expand you knowledge.
We'll get back to this thought process later, but if you feel like an extra challenge go for it!
# Lists # Lists
The different built-in objects we've seen until now, such as `str` and `int` are simple [text](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str) and [numeric](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) types.
There are other classes of objects that server different purposes.
One of these *groups* is called [sequence types](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range).
A list in python is pretty much exactly what you think it is.
It is an *object* that groups together *other* objects.
Sounds complicated?
Have a look at the following.
```python3
my_numbers = [1, 2, 44, 60, 70]
print(my_numbers)
```
Easy right?
Compared to [other languages](https://www.cplusplus.com/reference/list/list/) lists in python are *very* flexible.
They can contain objects of different types, and their length can be changed at any time.
Programmers coming from other languages often find this flexibility of python a bug but you should see it as a feature.
```python3
favorite_number = 7
name = "wouter"
date = [1986, 10, 7]
values = [1, date, favorite_number, "hello world", name]
print(values)
```
The code above is just an illustration of the flexibility of lists.
## Creating lists ## Creating lists
## Picking elements Creating lists can be done in two ways, either by using the **square brackets** `[]` or by calling `list`.
When calling `list` it takes **one argument**, which python will iterate over.
For example:
## Slicing lists ```python3
>>> first_list = ["hello", "world", "!"]
>>> first_list
['hello', 'world', '!']
>>> second_list = list("hello world !")
>>> second_list
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '!']
>>>
```
## List methods
As a `list` is a different type of object, it has different methods you can invoke on it.
When using tab complete in the python shell we get the following.
```python3
>>> second_list.
second_list.append( second_list.count( second_list.insert( second_list.reverse(
second_list.clear( second_list.extend( second_list.pop( second_list.sort(
second_list.copy( second_list.index( second_list.remove(
>>> second_list.
```
One of the most used methods is `append`.
It is used to add an element to the end of the list.
The second most used method is the `pop` one.
Read the shell code below and you'll understand immediately what they do.
```python3
>>> first_list
['hello', 'world', '!']
>>> first_list.append("coucou")
>>> first_list
['hello', 'world', '!', 'coucou']
>>> first_list.pop()
'coucou'
>>> first_list
['hello', 'world', '!']
>>>
```
🏃 Try it
---
Look at all the methods you can invoke on a list and try them out.
Remember to read the documentation!
## Picking elements and slicing lists
We can pick elements from the list of slice the list as we please.
A code block speaks more than words.
```python3
>>> long_list
['I', 'am', 'a', 'very', 'long', 'list', 'of', 'words', 'that', 'make', 'little', 'actual', 'sense']
>>> long_list[7]
'words'
>>> long_list[7:9]
['words', 'that']
>>> long_list[7:]
['words', 'that', 'make', 'little', 'actual', 'sense']
>>> long_list[:7]
['I', 'am', 'a', 'very', 'long', 'list', 'of']
>>> long_list[-1]
'sense'
>>> long_list[0]
'I'
>>>
```
⛑ **In programming we start counting at 0 because 0 and nothing are not the same thing.**
🏃 Try it
---
Slice and dice away!
A handy method of the `str` class is `split` which will cut up a string into separate elements.
The result will be a `list` on which you can use `list` methods.
# For loop # For loop
TODO say hello to my friends exercise I mentioned the for loop, which is a loop in space, when we saw the `while` loop.
TODO simple ROT13 cryptography with multiple libs The [keyword](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) in question is, surprise surprise, `for`!
I see it as a loop in space because it will run *for each element in a sequence* which in my mind is something of substance.
Your logical mileage may vary but as long as you understand the following code block we're good.
```python3
import time
friends = ["max", "mike", "alice", "steve", "rosa", "hans"]
print("The door opens and in walk my {} friends!".format(len(friends)))
for friend in friends:
print("Hello {}!".format(friend.capitalize()))
time.sleep(1)
print("{} closes the door behind him...".format(friend.capitalize()))
```
# Coding challenge - Cheerleader chant # Coding challenge - Cheerleader chant
TODO nested for loop exercise Can you make me a program that outputs this type of cheerleader chant?
You can make it *prettier* by importing your `pretty_print` function, plus you can add some `time.sleep` in it to make it more *musical*.
```
Give me an m
M
Give me an a
A
Give me an x
X
Gooooooooo, MAX!
Give me an m
M
Give me an i
I
Give me an k
K
Give me an e
E
Gooooooooo, MIKE!
Give me an c
C
Give me an a
A
Give me an m
M
Give me an i
I
Give me an l
L
Give me an l
L
Give me an e
E
Gooooooooo, CAMILLE!
```
<details>
<summary>Spoiler warning</summary>
```python3
friends = ["max", "mike", "camille"]
for friend in friends:
for letter in friend:
print("Give me an {}".format(letter))
print("{}".format(letter.upper()))
print("Gooooooooo, {}!".format(friend.upper()))
```
</details>
# Coding challenge - ROT13
ROT13 is one of the oldest cryptographic cyphers know to mankind.
It dates back to the Roman empire and is also known as a [Caesar cypher](https://en.wikipedia.org/wiki/Caesar_cipher).
The algorithm is pretty simple, you just shift a letter 13 places in the alphabet so `a` becomes `n` or `x` becomes `k`.
Have a look at [this](https://rot13.com/) website to see the cypher in action.
Now, can you make a program that encrypts a phrase with ROT13?
Something along these lines:
```python3
What's your secret? hello world!
encoded secret: uryyb jbeyq!
```
<details>
<summary>Spoiler warning</summary>
```python3
import string
def encode_rot(msg, rot=13):
msg = msg.lower()
letters = list(string.ascii_lowercase)
coded_msg = []
for letter in msg:
if letter not in letters:
coded_msg.append(letter)
else:
idx = letters.index(letter) + rot
coded_letter = letters[idx % len(letters)]
coded_msg.append(coded_letter)
coded_msg = "".join(coded_msg)
return coded_msg
def decode_rot(msg, rot=13):
pass
if __name__ == "__main__":
clear_message = input("What's your secret? ")
encoded_message = encode_rot(clear_message)
print("encoded secret: {}".format(encoded_message))
```
</details>
🏃 Try it
---
To make things more interesting you can add a decode function.
Plus you could add a prompt that asks how big the shift should be (ROT13, ROT16, ...).
# List comprehension
This is a bit of an advanced topic but I'm putting it here to show you a very unique and powerful feature of python.
# Handling files # Handling files