Crash Course
First install the latest version of python:
We’ll also install the community (FREE) edition of the PyCharm IDE:
When you create a new project, ensure the base interpreter is set to the latest version of Python that was just installed..
We’ll now create our first line of Python code, “Hello World”, and run the program so that it prints to our PyCharm terminal
Comments
writing comments in Pytrhon is the same as Ruby, using #
# here is a comment
You can also use ‘’’ at the top and bottom for multi-line comments:
'''
here is a multi-line
comment
that won't be shown
'''
typically though, most people just use # on each line.
Python Variables
Python variables can be written as follows:
character_name = "John"
character_age = "35"
print("Hello my name is " + character_name)
print("My age is " + character_age)
If you want to create a new line inside a string you could do this…
print("Hello, \nmy name is Bob")
//returns
Hello,
my name is Bob
You can convert strings to uppercase using .upper()
phrase = "Hello, \nmy name is Bob"
print(phrase.upper())
//returns
HELLO,
MY NAME IS BOB
You can get the length of a string with len()
phrase = "Hello, \nmy name is Bob"
print(len(phrase))
//returns
22
If I want a string character at a particular index returned, I can request the index value in square brackets.
phrase = "Hello, \nmy name is Bob"
print(phrase[0])
//returns
H
If I want to return the index value of the first instance of a string, then I can use .index()
phrase = "Hello, \nmy name is Bob"
print(phrase.index("l"))
//returns
2
You can replace characters in a string with .replace() which takes two parameters…
phrase = "Hello, \nmy name is Bob"
print(phrase.replace("Bob", "John"))
//returns
Hello,
my name is John
I can convert numbers into strings by using str()
print(str(5))
More on Numbers
I can use pow() to raise a number by its power
print(pow(2,3))
//returns
8
I can get the biggest number using max()
print(max(2,4,7,4,8,15,22,4,18))
//returns
22
min() will get the smallest number.
I can use round() to round a number.
To use some of the more advanced math functions, we need to import them…. So for example, to use the floor() function we would import the math module:
from math import *
print(floor(3.82))
print(ceil(5.02))
//returns
3
6
Getting input from users
When we want a user to enter information, we use use input(), and we usually store the input provide into a variable.
name = input("what is your name?")
we can simply use that variable to print back to the user:
name = input("what is your name?")
print("hello " + name)
If we want the user to input number, and actually use them as numbers, then we should use float() to convert them so that they can be used correctly.
For example:
num1 = input("enter your first number: ")
num2 = input("enter your second number: ")
result = float(num1) + float(num2)
print("the two numbers added together are " + str(result))
Arrays
You can reference array values by index:
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
print(friends[2])
//returns
Chris
You can also grab multiple values, when you specify the start value and the end value, although the end value itself is not printed.
For example
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
print(friends[2:4])
//returns
Chris
John
You can also modify values in arrays:
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
friends[2] = "Frank"
print(friends[2:4])
//returns
Frank
John
You can append one array to the end of another array with .extend()
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
numbers = [1,2,3,4,5]
friends.extend(numbers)
print(friends)
//returns
['Bob', 'Sue', 'Chris', 'John', 'Mark', 'Andrew', 1, 2, 3, 4, 5]
You can also append elements to an array with .append()
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
friends.append("Jamie")
print(friends)
//returns
['Bob', 'Sue', 'Chris', 'John', 'Mark', 'Andrew', 'Jamie']
You can insert elements at a particular position with .insert()
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
friends.insert(3, "Jamie")
print(friends)
//returns
['Bob', 'Sue', 'Chris', 'Jamie', 'John', 'Mark', 'Andrew']
you can also remove an element in the array at a particular position
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
friends.remove("Sue")
print(friends)
//returns
['Bob', 'Chris', 'John', 'Mark', 'Andrew']
You can clear all items in the list with .clear()
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
friends.clear()
print(friends)
//returns
[]
You can remove the last item with .pop()
You can count the number of instances an element appeared in an array with .count()
friends = ["Bob", "Sue", "Chris", "John", "Mark", "Andrew"]
print(friends.count("Bob"))
//returns
1
You can sort elements in an array with .sort()
You can reverse elements in the array with .reverse()
You can copy an array with .copy()
Tuples
Tuples are pairs of values and cannot be changed, they are immutable:
coordinates = (4,5)
Functions
Functions in Python start with def (same as Ruby) however you don’t end the function with the “end” word like Ruby…instead, Python infers that the function is finished because you no longer indent the code within the function. This is one of the key differences with Python….you MUST indent your code in the function, and best practice is to indent in multiples of four, as well as leaving two blank spaces at the end of the function.
You also provide a colon after the parentheses that come after the function name.
Also python best practice is that function names are all lower case, and use an underscore to separate words in the function name.
Typical syntax for a basic function would be as follows:
def say_hi():
print("Hi there!")
say_hi()
Rather than specifying print() inside the function, you could use return, which can then print the information as well…
def say_hi():
return "Hi there!"
print(say_hi())
Note that you cannot reference any more code after the return statement in the function.
If statements
If statements are also indented:
is_male = False
if is_male:
print("You are a male")
else:
print("You are a female")
//returns
You are a female
In Python, the “else if” option is typed out as “elif”
Also for not, we actually type “not”, as opposed to ! for other programming languages like JavaScript and Ruby.
python
Copy code
is_male = False
is_tall = True
if is_male and is_tall:
print("You are a tall male")
elif not is_male and is_tall:
print("You are a tall female")
elif is_male and not is_tall:
print("You are a short male")
else:
print("You are a short female")
//returns
You are a tall female
Python Dictionaries
Python dictionaries are pretty much objects, with key/value pairs.
month_conversion = {
"jan": "January",
"feb": "February",
"mar": "March",
"apr": "April",
"may": "May",
"jun": "June",
"jul": "July",
"aug": "August",
"sep": "September",
"oct": "October",
"nov": "November",
"dec": "December"
}
You can reference values based on key:
month_conversion = {
"jan": "January",
"feb": "February",
"mar": "March",
"apr": "April",
"may": "May",
"jun": "June",
"jul": "July",
"aug": "August",
"sep": "September",
"oct": "October",
"nov": "November",
"dec": "December"
}
print(month_conversion["mar"])
//returns
March
You can also do the same thing with .get() however with .get, you can provide a default value:
month_conversion = {
"jan": "January",
"feb": "February",
"mar": "March",
"apr": "April",
"may": "May",
"jun": "June",
"jul": "July",
"aug": "August",
"sep": "September",
"oct": "October",
"nov": "November",
"dec": "December"
}
print(month_conversion.get("mov", "invalid key specified"))
While loops
As long as a condition is true, the loop will keep running….
i = 1
while i <= 10:
print(i)
i = i + 1
// returns
1
2
3
4
5
6
7
8
9
10
For Loops
We often use for loops to loop through strings, arrays and dictionaries…
for letter in "My String":
print(letter)
// returns
M
y
S
t
r
i
n
g
2D Lists
2D Lists are essentially arrays inside of an array. By doing this you can reference a value based on it’s row and column:
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
print(number_grid[1][2])
//returns
6
Try/Except
A try/except block can help deal with errors.
try:
number = int(input("please type in a number: "))
print(number)
except:
print("you didn't type in a number!")
Reading from external files
We use the read command to read from external files:
Let’s say we have a txt file called employees.txt residing in the same folder as our python file, and the contents of the text file are as follows:
Jim - Sales
Mark - IT
Sally - Marketing
Chris - Finance
Bob - CEO
we could then read open this file using the following:
employee_file = open("employees.txt", "r")
there is also “w” for write, “a” for append and “r+” which provides read/write functionality.
Whenever you open a file, you should also close it.
employee_file = open("employees.txt", "r")
employee_file.close()
you can show all of the information in the file with .read()
employee_file = open("employees.txt", "r")
employee_file.read()
employee_file.close()
You can use readline() to read the first line in the file
If you wanted to show the first two lines, you’d just do it twice
employee_file = open("employees.txt", "r")
employee_file.readline()
employee_file.readline()
employee_file.close()
Modules and pip
If I created a .py file called useful_functions.py that included useful functions and variable, then I could import this into another .py file.
Let’s say I have a useful_functions.py file with the following:
special_number = 10
def convert_to_uppercase(word):
uppercase_word = word.upper()
print(uppercase_word)
name = "Bob"
I could now reference these as follows:
import useful_functions
print(useful_functions.name)
You can also install external modules using “pip install [module name]” where the module will be installed into the Lib/site-packages folder.
you can also uninstall modules with “pip uninstall [module name]”
Classes and Objects
We can create custom data types (class) and then create instances of that data-type (object)
In order to do this, we first create our custom class. Let’s create a file called Student.py
class Student_class:
def __init__(self, "name", "major", "gpa", "is_on_probation"):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
We can now import this class and create object instances from it
from Student import Student_class
student1 = Student("Jim", "Art", 2.3, False)
student2 = Student("Sally", "Finance", 3.2, True)
print(student1.name)
Note how in Python we say from [file] import [class]
In other languages it’s usually import [class] from [file]