Python in eleven steps

I’ve never been a fan of python, until about a week ago when I started a big Machine Learning project. Because most modern Machine Learning API’s utilize Python, I had to learn about it, and as a result, decided to share my knowledge of the entire programming language, in one tutorial.

This tutorial will approach learning in an interactive, step-by-step method. After every step, you should type out the same code that I have written into your IDE to better understand it. You can run your code after every step!  

At the bottom of this page is a “syntax” section, where you can review all syntax without going through this interactive tutorial.

 

Take your time to understand this tutorial. This is almost a year’s worth of material in one blog post!

Step One: Install python. Go to www.python.org/downloads/ and get yourself a copy of the latest version. Go through the installation process as if you were downloading a normal application.

Screen Shot 2018-01-04 at 9.13.10 PM.png

Step Two: Get an IDE. Here we will be using PyCharm, which is available at https://www.jetbrains.com/pycharm/. An IDE is simply the application you use to edit and write code on, similar to Android Studio for Android, Eclipse for Java, or Visual Studio for C#. Open it up and create a new project, it should look like this:Screen Shot 2018-01-04 at 9.23.47 PM.png

I was shocked when I downloaded this, since it looks exactly like Android Studio! That’s because it was made by the same people, JetBrains.

Step Three: Create a python file. Simply right-click the root file and make a python file:

 

Screen Shot 2018-01-04 at 9.27.55 PM.png

Notice the .py extension of the file. That indicates a python file!

Step four: Guess what this code does. 

print("Hello World")

You’re right! It will print hello world! Add that to your file that you created, and click RUN!Screen Shot 2018-01-04 at 9.32.26 PM.png

Whoo Hoo! You just ran some python code!!

 

You can also create variables pretty easily:

name = "ruchir"

print(name)

will print my name, Ruchir. Notice I don’t have to write “string” before the name of the string.  Also note that I can use either double quotes or single quotes, and the result will be the same.

Step Five: Let’s make a list!

list_of_things_i_like = ["pizza", "blogging", "android"]
print ("first item is ", list_of_things_i_like[0])

Simple example, important concept. Notice how this list, unlike an ArrayList in Java, is defined with square brackets, and how printing the list is as simple as putting a comma (rather than a plus sign). That code prints the following

first item is pizza

Now if I want to add “coding” to the list, all I need to do is use append

list_of_things_i_like.append("coding")

There are also other functions related to lists that I have defined in the syntax reference below. What if we want to make the list final and immutable? Well, unlike Java, python doesn’t have final, but you can use a tuple, defined by parenthesis.

similarToFinal = (1, 3 , "another list value", 3, 5, "this list aint changing")

NOTE: this list does not only hold one data type. It can hold other lists, strings, ints, etc. Let me say that again. This list is not limited to data types. 

Step Six: Let’s make a hashmap…er…dictionary

There are no mappings here! If you want a key-value pair, you need to use a dictionary:

pairings = {"themillibit", "thebestblog"}
print(pairings[themillibit"]

And you get the value pair “thebestblog”.

Step Seven: if(readingthemillibit){ happy }

Sometimes you only want to execute some code sometimes. Then you use conditionals!

if(blogName == "themillibit"):
    print("best blog!")
else :
    print("idk about this blog...")

I want you to notice the subtle differences in syntax. We are not using curly braces here, and instead, use the colon. Also, notice that we use == not = in conditionals. If we want to check if something is not equal, we put not after the if or else, like so:

if not(blogName == "themillibit")

Just like in every day English, you can also the words and and or in your conditionals. Similar to && and ||  in Java, we can simply type in the word and or or:

myNumberOne = 1
myNumberTwo = 2
if(myNumberOne==1 and myNumberTwo==2):
    print("Nice!")

Here, we get an output of Nice!, because myNumberOne equals one and myNumberTwo equals two. However, if just one of those statements was incorrect, we wouldn’t get the output of Nice!.

myNumberOne = 0
myNumberTwo = 2
if(myNumberOne==1 and myNumberTwo==2):
print("Nice!")

Here, we still get an output of Nice! because at least one of the conditions are met.

Step Eight: Loop loop loop loop loop… (x10)

Sometimes, we need to loop our code. Similar to a for loop in Java, we can perform a task multiple times until a condition is met:

for x in range(0, 11):
    print("The value of x is ", x)

Can you guess what this code does? It takes values from 1-10 (since remember, when we start at an index of zero, we are really starting at one) and prints the value at every iteration:

The value of x is 0
The value of x is 1
The value of x is 2
The value of x is 3
The value of x is 4
The value of x is 5
The value of x is 6
The value of x is 7
The value of x is 8
The value of x is 9
The value of x is 10

You can do the same for a list by doing for x in myList: or for x in [2, 3, 5]: and the same iteration would work.

 

You can also use a while loop if you don’t know how many times you will need to loop to meet a requirement. For example:

import random
randomNumber = random.randrange(1, 1000) 
while (randomNumber != 7): 
    print("still not 7", randomNumber)

Notice the import random statement. That allows us to use the random.randrange function, which generates a random number from 1-1000. While that number is not 7, we print a message with the number, and as its value becomes seven, it will stop printing. Note, you can force out of a loop with break in your code. Try it out!

Step nine: Let’s make a method…er…function

Yes, they are called functions in python. Basically, a function is a piece of code that is in one chunk and can be called multiple times just by referencing the function. A function is defined by def. For example, if I want a function that subtracts two numbers (which I pass into the function as parameters), I can do the following:

def subtractnumber(numberone, numbertwo): 
    return numberone-numbertwo #this function returns a subtraction


print(subtractnumber(1, 2)) #I'm passing in 1 and 2 as numberone and numbertwo

Awesome!

Step ten: Get user feedback!

You’ll need to import sys, and you can use the readline function to see what the user types:

import sys

print("enter a food")

place = sys.stdin.readline()

print("I love ", place)

Now, in the console, you can actually type!

Screen Shot 2018-01-04 at 10.37.21 PM.png

Step Eleven: Dealing with files

One of the best parts of python is how easy it is to create files and reference files. This is called I/O, or input/output.

test_file = open("test.txt", "wb")
test_file.write(bytes("this will be in the file", "UTF-8")) #dont worry about utf 8, its for character encoding
test_file.close()

Screen Shot 2018-01-04 at 10.45.59 PM.png

Notice the path at the bottom of the screenshot above. You just created a file on your computer in three lines of code! How cool is that?

Step Twelve: Objects

Coming from Java, understanding objects will be extremely easy. Quite simply, we can define classes, which are blueprints of objects. Any object can have its own attributes. For example, a car can have the attribute of an engine, wheels, brand, etc. You can define these attributes in a class and then set those attributes to individual objects. If you are not familiar with Object Oriented Programming, this may be a little harder to grasp.

class Dog:
    name = ""
    sound = ""

    def set_breed(self, namePassedIn): #self means it will set the name of the class it is in, which in this case is dog
        self.name = namePassedIn #self.name is similar to this.var in java, it is referencing name in class Dog

    def set_sound(self, soundPassedIn):
        self.sound = soundPassedIn

    def whatsMyDogLike(self):
        return "my dog is a " +self.name +" that can make the sound " +self.sound


#this large space break signifies that the class is over


poodle=Dog()
poodle.set_breed("poodle")
poodle.set_sound("bork")
print(poodle.whatsMyDogLike())

In the beginning, I define a class called dog. In this dog, we can set a sound or a breed (these are functions) that will modify the value of name and sound in dog. We can also get a return value by calling the method whatsMyDogLike, and it will simply the values name and sound.

After the class, I create a new dog, by saying poodle = Dog() and I set the values for its breed and sound. Finally, I call whatsMyDogLike() and get the following output:

Screen Shot 2018-01-04 at 11.04.50 PM.png

This is a pretty confusing concept, so I suggest you research OOP (object-oriented programming) if you don’t understand how this example works.

 

That’s it! Obviously, this tutorial has not covered everything about Python, but those are the basics!

 

Syntax REFERENCE:

Comments

# this is a single line comment
``` this is a

multiline comment ```

 

Arithmatic: Remember the order of operation matters! (PEMDAS)

Operator Description Example
+ Addition Adds a + b = 30
– Subtraction Subtracts a – b = -10
* Multiplication Multiplies a * b = 200
/ Division Divides b / a = 2
% Modulus Returns remainder b % a = 0
** Exponent Exponenets a**b =10 to the power 20
// Rounds down, no remainder, no decimals. 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0

String essentials:

%s - Turns something into a String (or any object with a string representation, like numbers). For example:

# This prints out: A list: [1, 2, 3] EVEN THOUGH MYLIST IS NOT A STRING
mylist = [9, 3, 4]
print("A list: %s" % mylist)

%d - Turns something into Integers

%f -Turns something into Floating point numbers

 

Operator Description Example
+ Concatenation – Adds values on either side of the operator a + b will give HelloPython
* Repetition – Creates new strings, concatenating multiple copies of the same string a*2 will give -HelloHello
[] Slice – Gives the character from the given index a[1] will give e
[ : ] Range Slice – Gives the characters from the given range a[1:4] will give ell
in Membership – Returns true if a character exists in the given string H in a will give 1
not in Membership – Returns true if a character does not exist in the given string M not in a will give 1
r/R Raw String – Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter “r,” which precedes the quotation marks. The “r” can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. print r’\n’ prints \n and print R’\n’prints \n
% Format – Performs String formatting See at next section

(table from tutorialspoint)

List essentials:

METHODS
list.append(obj)
Appends object obj to list
list.count(obj)
Returns count of how many times obj occurs in list
list.extend(seq)
Appends the contents of seq to list
list.index(obj)
Returns the lowest index in list that obj appears
list.insert(index, obj)
Inserts object obj into list at offset index
list.pop(obj=list[-1])
Removes and returns last object or obj from list
list.remove(obj)
Removes object obj from list
list.reverse()
Reverses objects of list in place
list.sort([func])
Sorts objects of list, use compare func if given

(table from tutorialspoint)

 

 Built In  Python  Functions!
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()