###Getting Started with Python:
Open your terminal and type python
to open the Python REPL/console.
More info:
- https://www.python.org/doc/
- Python Summarized on StackOverflow
- Python on Wikipedia
- Django Application Framework
Functions (MIND YOUR INDENTATION!)
def say_hello_to(noun):
return "hello " + noun;
say_hello_to("mom")
# 'hello mom'
Index of string:
"hello"[0]
# "h"
Basic for loop over a string (MIND YOUR INDENTATION!):
for char in "hello":
print char
# h
# e
# l
# l
# o
For loop with index:
for (index, char) in enumerate("hello"):
print index, char
# 0 h
# 1 e
# 2 l
# 3 l
# 4 o
Basic list comprehension:
[char for char in "hello"]
# ['h', 'e', 'l', 'l', 'o']
List comprehension + tuples (like an array, but with only two slots):
[(char, ord(char)) for char in "hello" ]
# [('h', 104), ('e', 101), ('l', 108), ('l', 108), ('o', 111)]
Note that ord
or "ordinal" is a like an ASCII Character Code.
Dictionary comprehension:
{char: ord(char) for char in "hello" }
# {'h': 104, 'e': 101, 'l': 108, 'o': 111}
Slicing lists using [start_idx:end_idx]
:
[char for char in "hello"[1:4]]
# ['e', 'l', 'l']
[char for char in "hello"[1:-1]] # negative index
# ['e', 'l', 'l']
Stepping through lists [start_idx:end_idx:step]
:
[char for char in "hello"[0:5:1]]
# ['h', 'e', 'l', 'l', 'o']
[char for char in "hello"[::]] # actually, those are all defaults! start=0, end=-1, step=1
# ['h', 'e', 'l', 'l', 'o']
Filtering with "if":
[char for char in "hello" if char not in "aeiou"]
# ['h', 'l', 'l']
Challenge: Reverse a string! (solution below)
Reverse a string solution:
"hello"[::-1]
# "olleh"
Reverse + slice:
"@dlrow olleh@"[-2:0:-1]
# 'hello world'