Skip to content

Instantly share code, notes, and snippets.

@nathanallen
Last active August 29, 2015 14:24
Show Gist options
  • Save nathanallen/72ed5a672827f0c1ccb8 to your computer and use it in GitHub Desktop.
Save nathanallen/72ed5a672827f0c1ccb8 to your computer and use it in GitHub Desktop.
A taste of Python

###Getting Started with Python:

Open your terminal and type python to open the Python REPL/console.

More info:


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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment