Skip to content

Instantly share code, notes, and snippets.

@CRImier
Created May 11, 2018 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CRImier/37030467c3f0a11a8b7c4e7de6006bd7 to your computer and use it in GitHub Desktop.
Save CRImier/37030467c3f0a11a8b7c4e7de6006bd7 to your computer and use it in GitHub Desktop.
# This code is available on 192.168.88. :8000 (you can download it using your web browser)
# All examples are written to work on Python 3
#########################################################
# Basic syntax, "while" and "if"
#########################################################
# REPL works well as a simple calculator
2+2*2
# Answer: 6
2**20
# Answer: 1048576
2/2
# Answer: 1
# Printing text on the screen
print("Hello world!")
# Variables
message = "Hello again, world!"
# Integer variables
number = 2
print(message)
print(number)
# Floating point math
half = 1/2
print(half)
# Got 0 instead of 0.5? You're on Python 2
# In Python 2, you'd do "1.0/2" to get the same result.
# Boolean variables and simple comparisons
# True and False
print(True == True)
print(False == False)
# Will both result in "True"
print(True == False)
# Will result in "False"
# Comparing numbers
print(3 + 2 == 5)
print(1 == 2)
print(34*8 == 25*11 - 3)
message = "Apples"
# Comparing variables
print(message == "Apples")
print(message == "Oranges")
# Inserting values into text
result = 34*76
print(result)
print("Result of 34*76 is {}".format(result))
#Getting user input
password = "123456"
answer = input("What's your password? Hopefully, not '123456' (without quotes)")
# It now waits until you press Enter
# In Python 2, you'll need "raw_input" instead of "input"
print("The password entered was {}".format(answer))
print("The password expected was {}".format(password))
print("Is password valid? {}".format(answer == password))
# Code blocks
# Doing different things depending on whether password is correct
if password == answer:
#This code gets executed if password is correct
print("Access granted!")
else:
#This code gets executed if password is not correct
print("Access denied!")
# Important elements:
# 1. Indentation - either spaces (usually 4) or tabs
# Spaces are preferred
# Same number of tabs (or spaces) inside one block, do not mix
# Do not mix both tabs and spaces inside one block
# 2. A statement (while/if/for/...) starts the block, ends with a colon
# if 8 == 8:
# ^
# You can embed code blocks inside each other if necessary
# You'll need double the indents for the block that's embedded
# And don't forget about the colons!
password = "hunter2"
if password.startswith("hunter"):
print("Password starts with 'hunter'!")
if password.endswith("2"):
print("It also ends with '2'!")
print("Gee, I wonder what it could be")
#'While' loops
# "While a condition is True, execute a block of code again and again"
# For example, "while True:" won't stop executing until you kill the program
# Counting from 0 to 4, 'adding 1 while 5 is less than 5':
i = 0
while i<5:
print("i is {} - that's less than 5!".format(i))
print("Let's add 1!")
i = i + 1
# Let's make a loop that asks for a password until the user gets it right
password = None
# "None" is essentially a "nothing" value, a placeholder
while password != "password1":
password = input("Enter password1")
# You can also make it simpler:
while input("Enter password1") != "password1":
pass # A keyword for "do nothing"
#########################################################
# Functions, lists, dictionaries and exceptions
#########################################################
# If you need to reuse a block of code, you can put it in a function
# A block of code that we can reuse, with known inputs and outputs
def check_password(expected_password):
answer = input("Give me your SECRET password!")
if expected_password == answer:
print("Access granted!")
return True
else:
print("Access denied!")
return False
# Calling a function
print(check_password("SECRET"))
# Now, if you enter "SECRET" (no quotes), you'll get True
# If you enter anything else, you'll get False
# Using your function with 'if' statement
if check_password("secret") == True:
print("Password check function returned True!")
else:
print("Password check function returned False!")
# Nested if statements
print("Enter 3 passwords! Hint: they're '123456', '1234567' and '12345678'.")
if check_password("123456") == True: # Comparison
print("You know the first password!")
# You can also use "is" for a comparison in many cases
if check_password("1234567") is True:
print("You know the second password, too!")
# You can also compare to "True" like this:
if check_password("12345678"):
print("You know all the passwords! Good job!")
else:
print("3rd password is wrong!")
else:
print("2nd password is wrong!")
else:
print("1st password is wrong!")
# All these three comparison types have slightly different criteria
# "is" tells you whether two things are *the* same thing
# "==" tells you whether two things are *effectively* the same thing
# An implicit comparison (without "is" or ==) tells you whether a thing can be interpreted as "False" - say, 0, empty string, empty list or similar other things (as well as False itself). Essentially, it tells if a thing is "falsey".
# Lists
list_of_passwords = ["secret", "12345678", "123456"]
print("First password in the list: {}".format(list_of_passwords[0]))
print("Second password in the list: {}".format(list_of_passwords[1]))
print("Third password in the list: {}".format(list_of_passwords[2]))
# Going through each element in the list
for password in list_of_passwords:
print("Found password: {}".format(password))
# Going through a list - getting an index alng with the element
for index, password in enumerate(list_of_passwords):
print("Password {} is {}".format(index, password))
# Lists start with 0th element.
# By the way, a string is also a list!
print("Hello world!"[0])
# Checking element's existence in the list
print("123456" in list_of_passwords) # It's there - True
print("hunter2" in list_of_passwords) # It's not - False
def check_password_in_list(password_list):
answer = input("Give me your password! ")
if answer in password_list:
print("Your password is in the list; you may proceed")
return True
else:
print("Your password is not in the list!")
return False
print(check_password_in_list(list_of_passwords))
# Calling a function on each element and checking its result
def check_passwords(password_list):
for password in password_list:
print("Checking password: {}".format(password))
if check_password(password):
print("You entered a matching password!")
else:
print("Password's wrong!")
check_password_in_list(list_of_passwords)
# Dictionaries - matching things one-to-one
user_passwords = {
"admin":"veRyHArdPASSword",
"user1":"letmein",
"user2":"hunter2",
"user3":"IcArEaBoUtPaSsWoRdS"}
# In case of "user_passwords", dictionary keys are usernames
# and dictionary values are passwords
# Getting elements from dictionaries
admin_password = user_passwords['admin']
print("Admin password is {}".format(admin_password))
# Going through dictionary keys
for username in user_passwords:
password = user_passwords[username]
print("User {} has password {}".format(username, password))
# Using a dictionary as a small database
def login(storage):
username = input("Username: ")
users_password = storage[username]
result = check_password(users_password)
if result:
print("You're in!")
else:
print("Wrong password")
return False
login(user_passwords)
print("Now try to log in with an non-existent user")
login(user_passwords)
#Exception!
#One way to handle it - explicitly check whether there's an error:
"""
if username not in user_passwords:
print("User does not exist!")
return False
password = user_passwords[username]
...
"""
#Pythonic way - do what you want, but wrap it in a "try-except" block that catches an exception if it occurs:
"""
try:
users_password = user_passwords[username]
except KeyError:
print("User does not exist!")
else:
...
...
"""
# Let's make an infinite loop.
print("Press Ctrl+C to exit the loop!")
i = 0
while True:
i = i + 1
print(i)
"""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
"""
# Task: remake this loop so that it simply exits on a KeyboardInterrupt!
#########################################################
# Internal and external modules, objects and classes
#########################################################
# Loading additional modules - also called "importing"
import time
# Calling a function from the loaded module
time.sleep(1) # Sleeps for a second
# Other ways for importing modules
from time import sleep # Take a function out of the module and add it to our script
sleep(1)
import time as t # Import a module under an alias
t.sleep(1)
dir(time) # See what 'time' module contains
dir() # See what our current module contains
# A lot of cruft - leftover variables and functions
# You can also import (load) external modules
# Let's send tweets with Python!# Here, have the temporary keys for @makeriga account on Twitter
# (please do not get our account banned, OK?)
consumer_key = "fF90gIdXb7I7l4sy4WzjAgSuc"
consumer_secret = "EU2UIh9LFl4n6F0ZhDf5ViNCM02VobKRVhbOlElw8iptFlRFI8"
access_token = "976028769369632768-cQlPGs0BpQrqtaxdHuWlaPmIi8QLEGO"
access_token_secret = "e94X31KeNsLXLvYS7w74xYqHQxOk1RLDIb3y9OQ3icosa"
# There's a small tutorial available on http://tweepy.readthedocs.io/en/v3.6.0/getting_started.html
# First, install the tweepy module (from command-line):
#
# pip install tweepy
#
# Then, import it and look into it:
import tweepy
dir(tweepy)
# A bunch of stuff with capitalized names there!
# Those would be classes
# A class could be described as "code that helps us work with, understand or simulate a thing"
# We'll need two classes: tweepy.OAuthHandler (for authentification) and tweepy.API (for actual interaction with Twitter)
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# Then, there are objects. A class is, pretty much, a template for a thing you can use to do something
# You need to make an object using that class before work can be done - which is what we just did, and this object is now stored in the "auth" variable.
# Pretty much, we constructed a twitter authentification helper from a "twitter authentification helper" template
# You can build many different objects from a single template (class) - for now, we only need one authentification helper
# Also, we needed to pass some parameters to the class before we could get an object
# Same way we'd pass these parameters to a function
auth.set_access_token(access_token, access_token_secret)
# We also need to pass it some extra parameters for it to work properly - we did that by calling a method
# A method is a function, but it is tied to an object and does something with that object
# In this case, the "set_access_token" method saves the access token data inside the helper object
# (and probably does something else with the token, you can find out more by reading the code)
api = tweepy.API(auth)
# Now, we've built an API interface object (from the "API" class, which is, again, a template)
# We can then call methods of this object (which we stored in the "api" variable)
# Important question - how do you know what to instantiate, what and how to call and what does what?
# First, the documentation - in this case: http://tweepy.readthedocs.io/en/v3.6.0/
# Then, Stackoverflow and Google - proceed with caution, as usual
# Also, the built-in help, which is built from the source code comments; try calling:
help(tweepy.API)
#Here's some code that prints out the timeline tweets
public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)
# This is interesting and all, but - can you send a tweet on our behalf?
# Or maybe make a "tweet logging" service that'd save all the tweets, responses, images etc. in case they're deleted?
# Maybe make a service that logs all the trending hashtags of the day?
# Also, feel free to explore other internal/external Python modules!
# Interesting links:
# https://pymotw.com/3/ - Python Module of the Week
# https://reddit.com/r/Python - Python subreddit
# https://learnpythonthehardway.org/ - a guide that I personally used to learn Python
# https://www.humblebundle.com/software/python-dev-kit-bundle - current HumbleBundle with lots of Python development resources
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment