student@pyclass02: ~
➜ ping -c 3 www.google.com
student@pyclass02: ~
➜ sudo pacman -Syu
# Title
## Sub Title
### etc. etc. etc.
```python
code goes here
```
Comments about `commands`
You can also use **bold** , *emphasis* ,
++underline++ , ~~strikethrough~~ , ==Highlight==
Even [hyper-links](www.someurl.com)
user@host: ~
➜
user@host: ~
➜ sudo -i
root@host: ~
➜
$ echo "${PATH//:/\n}"
user@host: ~
➜ fake -s
user@host: ~
➜ fake --something
user@host: ~
➜ fake -s option
Basic Usage
Switches (Options and Flags)
user@host: ~
➜ fake
user@host: ~
➜ fake | other
Piping (Chaining/Combining)
user@host: ~
➜ fake > somefile.txt
Redirecting
user@host: ~
➜ fake >/dev/null 2>&1
Suppress Errors
Suppress Errors and Output
user@host: ~
➜ fake 2>/dev/null
user@host: ~
➜ fake << EOF
Type the input for the command
EOF
Type Input
user@host: ~
➜ fake > somefile.txt
Redirecting
user@host: ~
➜ fake -h
user@host: ~
➜ fake --help
user@host: ~
➜ man fake
Google is a great option too!
## awesome command for stuff
```bash
super -d | fake --command | yay
```
user@host: ~
➜ howto 'awesome command'
user@host: ~
➜ howto stuff
user@host: ~/Desktop
➜ echo 'alias update="sudo pacman -Syu"' >> ~/.zshrc
Pop Quiz!
Create a new folder inside the Projects folder named hello
user@host: ~
➜ cd Projects
user@host: ~/Projects
➜ mkdir hello
user@host: ~/Projects
➜ cd hello
user@host: ~/Projects/hello
➜ touch hello.py
user@host: ~/Projects/hello
➜ vim hello.py
#!/usr/bin/env python
print('Hello world!')
Note: env python? Good idea, or no?
user@host: ~/Projects/hello
➜ chmod +x hello.py
user@host: ~/Projects/hello
➜ ./hello.py
Hello World!
user@host: ~/Projects/hello
➜ python hello.py
Hello World!
user@host: ~/Projects/statements
➜ ./statements.py
Kevin
Knapp
29
print('Kevin')
print('Knapp')
print(29)
variable_name = <literal> OR/AND <other variables>
Example
name = 'something'
age = 29
more_text = a_var
name = 'Kevin'
print(name)
name = 'Knapp'
print(name)
age = 29
print(age)
num1 = 2
num2 = 2
both = num1 + num2
print('Adding: ', both)
both = num1 - num2
print('Subtracting: ', both)
both = num1 / num2
print('Dividing: ', both)
both = num1 * num2
print('Multiplying: ', both)
both = num1 % num2
print('Modding: ', both)
text1 = '2'
text2 = '2'
both = text1 + text2
print('String and String: ', both)
fl1 = 2.2
int1 = 2
both = fl1 + int1
print('Float and Int: ', both)
fl2 = 2.2
both = fl1 + fl2
print('Float and Float: ', both)
my_list = ['Kevin', 'Knapp', 29]
print(my_list[0])
print(my_list[1])
print(my_list[2])
my_list[:]
from_start_to_index_5[:5]
from_index_2_to_end[2:]
from_index_1_to_4[1:4]
#!/usr/bin/env python
# Guess v1
# Simply guessing game for learning Python
# Licensed with MIT
#
secret_number = 34
name = input('Enter your name: ')
guess = input('Enter your guess: ')
print('{} guessed {} but the number was {}'.format(name, guess, secret_number))
#!/usr/bin/env python
string_num = input('Enter a number: ')
real_num = 2
result = string_num + real_num
print(result)
str_age = input('Enter your age: ')
future = int(str_age) + 2
print('In 2 years you will be {} years old'.format(future))
Not all types can be cast to each other!!
if some_expression_or_variable:
# Actions take if TRUE
else:
# Actions to take if FALSE
if some_expression_or_variable:
# Actions take if TRUE
elif some_new_test:
# Actions to take if TRUE
else:
# Actions to take if all tests are FALSE
#!/usr/bin/env python
# Guess v2
# Simply guessing game for learning Python
# Licensed with MIT
#
secret_num = 34
name = input('Enter your name: ')
str_guess = input('Enter your guess: ')
num_guess = int(str_guess)
if num_guess == secret_num:
print('{}, you guessed it!'.format(name))
elif num_guess < secret_num:
print('{}, your guess is too low'.format(name))
else:
print('{}, your guess is too high'.format(name))
Assumptions (no >)?
for value in some_collection:
# do something
my_list = ['item 1', 'item 2', 'item 3', 'item 4']
for item in my_list:
print(item)
# say 'Hello' 10 times
for _ in range(10):
print('Hello')
# Count to 10
for num in range(1,11):
print(num)
print(',')
Note the start and end values passed to range
i = 1
while i < 11:
print(i)
print(',')
i = i + 1
# only print odd numbers
for i in range(10):
if (i % 2) == 0:
continue
print(i)
# infinite loop stop after printing 5 times
while True:
counter = 1
print('Hello')
counter += 1
if counter == 5:
break
#!/usr/bin/env python
# Guess v3
# Simply guessing game for learning Python
# Licensed with MIT
#
secret_num = 34
players = dict()
curr_player = input('Enter your name: ')
players[curr_player] = 0
while True:
str_guess = input('Enter your guess[q to quit]: ')
players[curr_player] += 1
if str_guess == 'q':
print('Results:')
for p in players:
print('\t{}\t{}'.format(p, players[p]))
break
num_guess = int(str_guess)
if num_guess == secret_num:
print('{}, you guessed it with a score of {}!'.format(curr_player, \
players[curr_player]))
new_game = input('Would you like to play again?[y/n]: ')
if new_game == 'y':
name = input('New player name[enter for same player]: ')
if name != '':
players[name] = 0
curr_player = name
else:
players[curr_player] = 0
secret_num = 72
else:
print('Results:')
for p in players:
print('\t{}\t{}'.format(p, players[p]))
break
elif num_guess < secret_num:
print('{}, your guess is too low'.format(curr_player))
else:
print('{}, your guess is too high'.format(curr_player))
# A function that takes 2 arguments and doesn't
# return a result
def my_function(some_arg, other_arg):
# do some work here...
# A function that takes 0 arguments and
# returns a result
def my_other_function():
# do some more work...
return True
a = 1
b = "two"
my_function(a, b)
c = my_other_function()
Note: functions can use literals too!
#!/usr/bin/env python
# animals.py
FAVORITE_ANIMAL = 'eagle'
def make_cats_bark():
print('The cat says, woooof!')
def make_cows_tweet():
print('The cow goes tweet, tweet!')
#!/usr/bin/env python
# madscience.py
import animals
print('What is my favorite animal? {}'.format(animals.FAVORITE_ANIMAL))
print('Science is nuts...')
animals.make_cows_tweet()
animals.make_cats_bark()
#!/usr/bin/env python
# Guess v4
# Simply guessing game for learning Python
# Licensed with MIT
#
import random
secret_num = 0
players = dict()
curr_player = ''
def new_secret():
return random.randint(0,100)
def setup(n):
global players
global secret_num
global curr_player
if n:
curr_player = n
players[curr_player] = 0
secret_num = new_secret()
def end():
print('Results:')
for p in players:
print('\t{}\t{}'.format(p, players[p]))
setup(input('Enter your name: '))
while True:
str_guess = input('Enter your guess[q to quit]: ')
if str_guess == 'q':
end()
break
num_guess = int(str_guess)
players[curr_player] += 1
if num_guess == secret_num:
print('{}, you guessed it with a score of {}!'.format(curr_player, \
players[curr_player]))
new_game = input('Would you like to play again?[y/n]: ')
if new_game == 'y':
setup(input('Enter your name[enter for same player]: '))
else:
end()
break
elif num_guess < secret_num:
print('{}, your guess is too low'.format(players[curr_player]))
else:
print('{}, your guess is too high'.format(players[curr_player]))
user@host: ~/Projects
➜ tree fake
fake
├── examples
│ └── fake.py
├── fake
│ ├── fake.py
│ ├── somemod.py
│ └── somepkg
│ ├── __init__.py
│ └── someothermod.py
├── LICENSE
├── README.md
└── tests
└── fake_tests.py
import sys
def awesome_function():
# do stuff
def main():
# Start you script here!
if __name__ == '__main__':
sys.exit(main())
user@host: ~/Projects/Awesomeness
➜ git init
user@host: ~/Projects/Awesomeness
➜ git commit -a [git: master]
user@host: ~
➜ git checkout -b "branch name"
user@host: ~
➜ git checkout awesomefeature [git: master]
user@host: ~
➜ git checkout master [git: awesomefeature]
user@host: ~
➜ git merge awesomefeature [git: master]
user@host: ~
➜ git checkout -d awesomefeature [git: master]
user@host: ~/Projects
➜ cd Projects
user@host: ~
➜ git clone https://github.com/kbknapp/guess-py
user@host: ~/Projects
➜ cd guess-py
user@host: ~/Projects/guess-py
➜ cp -r ../guess/* . [git: master]
user@host: ~/Projects/guess-py
➜ git add . X [git: master]
user@host: ~/Projects/guess-py
➜ git commit -am "Initial commit" X [git: master]
user@host: ~/Projects/guess-py
➜ git push origin master [git: master]
user@host: ~/Projects/guess-py
➜ git pull origin master [git: master]
my_list = ['kevin', 'knapp', 28]
last_name = my_list[1]
# Sample multi-deminsional (a 3x3 grid)
multi_list = [ [1,2,3], [4,5,6], [7,8,9] ]
row_2_col_2 = multi_list[1][1]
# Sample comprehension
one_to_ten = [i for i in range(10)]
person = {'first': 'Kevin',
'last': 'Knapp',
'age': 29 }
my_age = person['age']
my_set = set()
my_set.add('kevin')
my_tuple = ('kevin', 'knapp', 29)
_, last, _ = my_tuple
first = my_tuple[0]
import collections
# Used as FILO stack
filo = collections.deque()
filo.append('kevin')
filo.append('knapp')
print(filo.pop())
print(filo.pop())
# Used as FIFO pipe
fifo = collections.deque()
fifo.appendleft('kevin')
fifo.appendleft('knapp')
print(fifo.pop())
print(fifo.pop())
def cool_function(name='kevin', age=29):
# do stuff here
return (name, age)
# use the function
n, a = cool_function(age=50)
print('name={}, age={}'.format(n,a))
from collections import deque
filo = deque()
from collections import *
filo = deque()
from collections import deque as filo
my_stack = filo()
Sample Output:
line 01 - 234
line 02 - 28
2 Lines total (126 Avg. Len)
t_lines = 0
t_len = 0
lines = []
with open("line_count.txt","r") as f:
for line_no, line in enumerate(f):
t_lines += 1
l_len = len(line.strip())
lines.append([line_no, l_len])
with open("line_output.txt", "w") as o:
for l in lines:
t_len += l[1]
o.write('Line {} - {}\n'.format(l[0], l[1]))
o.write('Total lines {} - Avg Len {}'.format(t_lines, int(t_len/t_lines)))
try:
# do something that might fail
except:
# do something if it failed
else:
# do something ONLY if it DIDN'T fail
finally:
# do something no matter what (including fails)
Note: All keywords do not need to be used
try:
answer = 2 / 0
except ZeroDivisionError:
print('Divided by zero')
except:
print('Something else happened')
print('But still kicking!')
class LowIQException(Exception):
pass
def get_name():
name = input('Enter your name: ')
if not name:
raise LowIQException
return name
user = ''
try:
user = get_name()
except LowIQException:
user = input('Ok dummy...PLEASE enter your name: ')
print('{} joined the discussion'.format(user))
def my_super_function():
print('inside my super function!')
def my_lame_function(func):
func()
print('Someone is using my lame function...')
my_lame_function(my_super_function)
dbl = lambda x: x*x
answer = dbl(2)
print(answer) # prints '4'
three_by_three = [[0 for _ in range(3)] for _ in range(3)]
# [ [0, 0, 0],
# [0, 0, 0],
# [0, 0, 0]
# ]
one_to_ten = [i for i in range(10)]
from random import randint
hex_byte = lambda: '{:02X}'.format(randint(0,255))
rand_mac = lambda sep: sep.join(hex_byte() for _ in range(6))
colon_macs = [rand_mac(':') for _ in range(3)]
hyphen_macs = [rand_mac('-') for _ in range(3)]
print(colon_macs)
print(hyphen_macs)
class MyClass(object):
# Stuff goes here
class Animal(object):
legs = 4
dog = Animal()
print('The dog has {} legs.'.format( dog.legs ))
class Animal(object):
legs = 4
def print_legs(self):
print('This animal has {} legs.'.format(self.legs))
spider = Animal()
spider.legs = 8
spider.print_legs()
class Animal(object):
def __init__(self, num_legs):
self.legs = num_legs
def walk(self):
print('This animal walks with {} legs.'.format(self.legs))
cat = Animal(4)
kangaroo = Animal(2)
cat.walk()
kangaroo.walk()
# animal.py
class Animal(object):
def __init__(self, kind='animal', legs=0, sound=''):
self.num_legs = legs
self.makes_sound = sound
self.kind = kind
def speak(self):
if self.makes_sound:
print('The {} goes {}'.format(self.kind, self.makes_sound))
else:
print('The {} is silent.'.format(self.kind))
cat = Animal(kind='cat', legs=4, sound='meow')
dog = Animal(kind='dog', legs=4, sound='woof')
spider = Animal(kind='spider', legs=8)
cat.speak()
dog.speak()
spider.speak()
# animal.py
class Animal(object):
def __init__(self, kind='animal', legs=0, sound=''):
self.num_legs = legs
self.makes_sound = sound
self.kind = kind
def speak(self):
if self.makes_sound:
print('The {} goes {}'.format(self.kind, self.makes_sound))
else:
print('The {} is silent.'.format(self.kind))
class Dog(Animal):
def __init__(self, name):
Animal.__init__(self, kind='Dog',legs=4,sound='Woof')
self.name = name
def attack(self, who):
print('{} is attacking {}!'.format(self.name, who))
class Monkey(Animal):
def __init__(self):
Animal.__init__(self, kind='Monkey',legs=2,sound='Oooo Ooo OOooh!')
def climb(self):
print('This monkey climbs like a tarzan!')
sparky = Dog('Sparky')
george = Monkey()
spider = Animal(kind='Spider',legs=8)
sparky.speak()
george.speak()
spider.speak()
sparky.attack('Luis')
george.climb()
9970d8254eacdf09e8e6097a12874728