So you want to be a Python programmer? [Vector's Introduction to Python]
#1
For the purpose of this tutorial/intro to python i will be assuming the reader is on a Windows box and has no previous experience with programming.

Welcome noobs to Vector's master class in Python. Today we will be looking at some fundamental features of the Python programming language. Python is objectively the best programming language in the world. Since it is an object oriented language this makes my statement double true.

Well then, without further ado, lets dive right in shall we?

0. In the beginning there was C, and van Rossum said: Let there be Python!


You start by getting everything you need to run and write python. Since i will be assuming the reader is on Windows you should start by downloading Notepad++ https://notepad-plus-plus.org/ next up you download the python interpreter https://www.python.org/ftp/python/2....7.12.amd64.msi

We will be using Python 2.7.

When you get the option to set Python to the environment variables you will click the little box so that it's checked.

After everything is installed you go to a directory, lets say C:\Users\Guest\PythonPractice and you're going to make a new text file. Call it helloworld.py, open it with notepad++ and hammer the following text.

Code:
print "Hello World!"

Type it don't copypasta, you need to remember this. Save the file. Are you ready? Click that fat round windows start icon and search for cmd.exe to open up a commandline. Type in the following command.

Code:
REM 'color a' is essential in this lesson, also ignore this line, in the windows shell REM means REMARK, it's how you comment batch files.

color a

cd C:\Users\[username]\PythonPractice

helloworld.py

If your commandline just spit out "Hello World!" in greentext.

[Image: latest?cb=20131101144820]

Congratulations recruit. You have reached Rank 2 "Skid". It's important to remember that when you are printing text in Python, you always surround it in quotation marks.

1. Managing Modules

Python is like coding with cheat mode on. There's a lot of work that will be done for us, a module is a program that we can borrow functionality from. Sometimes a module is also called a library. For the purpose of this introduction, we will need a module to interact with websites. There's an awesome module for this and it's called Mechanize. To get a module that is not preinstalled with the interpreter setup you downloaded you can use Python's built in package manager called pip.

Open up a commandline and enter the following commands.

Code:
REM 'color a' is optional in this lesson
REM PROTIP: be a rebel today and try color b for a change

cd C:\Python27\Scripts

pip install mechanize

If all went well your commandline will tell you that it has successfully installed the proper module. Vector's top tip of the day: When in doubt about the syntax or functionality of a module, check out the docs for some light reading. https://docs.python.org/2/ If the docs don't have the answer, stackoverflow will https://stackoverflow.com/questions/tagged/python

Remember, if you can think of it, someone else has made a module for it.


2. Import Statements & Syntax


Now we will learn about import statements and some basic syntax. Like mentioned in the previous lesson in Python we use modules to borrow all sorts of functionality for our own program. In IT being lazy is called being efficient, however being efficient doesn't necessarily involve being lazy. To use a module in python we import it or we import parts of it. Make a textfile called importsandstuff.py and open it up in notepad++. Hammer out the following.

Code:
# REEEEE! in python, we comment with hashtags, ignore this line, the interpreter will do so as well
# shebang lines are a special case but you need not concern yourself with that at this point in time

# here we will import our module called datetime
import datetime

# the program would be pretty useless if all we did was import a module so lets do something with it
# lets hammer out a variable called 'timestamp' and assign a value to it.

timestamp = datetime.datetime.now()
print timestamp

Ok hold on to your pants it's about to get technical. The variable 'timestamp' has been assigned the value of datetime.datetime.now(). datetime.now() is a function from the 'datetime' module that returns the current date and time. Makes sense right? So what we are telling the interpreter here is basically this: From the module 'datetime' go to the class called 'datetime' and call the function 'now()'. Once you understand this principle, the world of Python will make a lot more sense.

Ok, so now that you know that go ahead and CD to your PythonPractice directory and run the script.

Code:
cd C:\Users\[username]\PythonPractice

importsandstuff.py

If your commandline just spit out the current date and time everything went well.


Closing notes on import statements.

There are several ways to import things in python. The most common is simply import [module_name]. If you wish to import a specific class from a module you can do the following in example.

Code:
from datetime import datetime

Now you have just the class imported and you could assing your variable thusly: timestamp = datetime.now() Alternatively you can make an alias for your module like so.
Code:
import datetime as dt

Now the syntax is dt.datetime.now(), are you starting to see a pattern? Lastly you can also do wildcard imports.
Code:
from datetime import *

This is bad practice though so don't do it, or you will bring great shame upon your Python dojo. Go ahead and take the code snippet from before and change up the way you do imports to get familiar with it. If you consistently get the date and time when you run the script, then congratulations.

[Image: latest?cb=20131101144820]

3. Logic Operators.

Comparison.


To do anything useful in any programming language you need comparison operators(And other things to do with logic). Basically a comparison operator will check if something evaluates to True or False. Consider the following. If we were to type this into an instance of the Python interpreter we can see an easy to understand example.

Code:
>>>a = 1
>>>b = 2

It may be good to try to remember that when there are three 'greater than' symbols prefacing a bit of code it means we are running this code from an instance of the Python interpreter. You can think of it as a sort of shell. '>>>' is what we input and everything without it is what the interpreter returns.

Code:
>>> a == b
False
>>> a == a
True

In this example the double '=' is the comparison operator. It asks Python to check if the objects referred to by the variables are equal. We also have an 'is' operator. Surely that must do the same right? Actually, it doesn't. 'is' will return True if two variables point to the same object. Consider the following for an example of this functionality.

Code:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

In this example we have made a list of integers(That's just a fancy way of saying numbers in programming lingo) and we have assigned the variable 'a' with the value for this list. Then we assign the variable 'b' with the same value of a. The 'is' operator lets us know here that we referencing the same list object by evaluating to True. Later we assign a different object to 'b' and while the values may remain the same for both objects '[1, 2, 3]' the 'is' operator is now evaluating to False since we are dealing with two different objects even though they have the same value.


WEW!!!

That was pretty complicated. Lets do something more interesting next!

Practical Application of Comparison Operators.

Lets say we have a program and we need to parse some input from the command line. How would we go about it? Say we need to parse a simple yes or no question. We might do something like the following. Feel free to hammer along in a textfile in your PythonPractice directory.

Code:
# Lets start by asking a question first, the 'raw_input' syntax is the easiest way to do this
# we will hammer out a variable and assign it the value of whatever the user inputs on the commandline with -
# the 'raw_input' syntax, lets also import the 'sys' module for the lulz.

import sys

question = raw_input("Would you like to continue? Y/n: ")

# Ok cool, now what? Comparison operators and If/Else statements of course!

if question == 'y':
    print "Continuing"
elif question == 'n':
    print "Aborted"
    sys.exit(0) # This is why we are importing the sys module, so we can have the program exit if we select 'n' to abort
else:
    print "Unhandled Option"
    sys.exit(0)

Alright so here's what's going on. When you start this program from the commandline it will ask you whether you would like to continue or not. The user can then input whatever they desire. But we expect them to either pick Y for yes or N for no. After the user has given their answer we need to check what they picked with python. We do this with our if/else statements and our comparison operator.

Code:
if question == 'y':
    print "Continuing"

With this we check if the user has given Y as input, in case they did, we print "Continuing" if they gave N as input we print "Aborted" and we exit. In case neither Y nor N were given as input the 'else' statement will print that we have encountered an option that is not handled by the program.

Also, it might be interesting to note that whitespaces also known as indentations are really important in Python. A good rule of thumb is to ALWAYS indent if your line ends with a colon ':'.

All kinds of Operators!

Besides comparing we can also do loops. the easiest way to go about this in Python is with the while loop.

Code:
while True:
    # Do stuff we define here, forever, or at least as long as the conditions of the loop are met

Basically this means as long as whatever evaluates to true we are going to do what's in this loop ad infinitum. The way we can stop a loop is with a 'break' statement.

We also have a 'for' loop.

Code:
for x in y:
   # For every item of X in object Y do what we define here

Pretty self-explanatory. We also have Boolean operators. Basically this is just a True or False statement.

Code:
variable = False

if variable == False:
    # Do stuff
else:
    # Don't do stuff (Or do other stuff)

Now we can move on to the 'try' and 'except' operators. Basically, sometimes you can expect a certain operation or part of the program to fail. To direct what the program does after it fails we use the 'try and 'except' operators.

Code:
try:
     # We are doing stuff here, but we know it might fail at some point
except:
    # When the program fails we will decide how to handle it with what we define here

And that's the basics.

4. Recap and go!
 
I know that's a lot of info so lets take a step back. We have now learned about import statements to import functionality from other Python programs, we saw a little bit about lists. We have learned about Comparison Operators and if/else statements. We also learned about loops and how they work at the surface level. Finally we have also learned about 'try' and 'except' operators.

Lets put all this new found knowledge to good use!

Open up a textfile and call it 8ball.py, and lets make a program that incorporates all the things we have learned about up until now. And one new thing.

Code:
# Of course we start with our import statements, we will use the 'random' module in this exercise

import random

# OMG! What's this!? It's a function definition. It's a neat way to organize your code. 'def' tells the interpreter that -
# we're going to define a function now. The name of the function is main()

def main():
   
    # Here is our variable that has the list object assigned
    answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely",
                "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes",
                "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now",
                "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no",
                "My sources say no", "Outlook not so good", "Very doubtful"]
   
    # So far so good, here comes our loop
    while True:
        # We eventually want to be able to break out of this loop, we can interrupt loops by sending CTRL+C
        # But that just kills the program in an ugly way, we are going to do something about that.
        try:
            question = raw_input("Ask the magic Python 8 ball anything!: ")
           
            # if/else and comparison operators

            if question == '':
                print "\nThe magic Python 8 ball did not understand!"
            else:
                result = random.choice(tuple(answers))
                # Here is how we use the random module, from the module we go to a function called choice, have it pick from a tuple(list) and assign which list(answers)
                # What will happen is that it will randomly select one object from the list and assign it's value to the variable 'result' then later we can print this result.
               
                print ""
                print result
                
        # Here we handle our keyboard interrupt
        except KeyboardInterrupt:
            print "\n[!]Critical, user aborted."
            # Break the loop
           break

# Call the function to start the program
main()

What is going to happen is that you can input any question as long as it's not blank and the program will randomly select an answer from the list of answers we defined and will return the result to the commandline for as long as we don't send a keyboard interrupt. Go ahead and try it out.

Code:
REM bear with me now

cd C:\Users\[username]\PythonPractice

8ball.py

If everything went well it should give you a result similar to this:

Code:
8ball.py
Ask the magic Python 8 ball anything!: Is this the best intro ever?

It is decidedly so
Ask the magic Python 8 ball anything!:

Congratz if you got that result.


[Image: latest?cb=20131101144820]

Thank you for taking the time to read my intro! Now go forth my son, you know Python now.

[Image: set-it-all-on-fire.jpg?w=393&h=263]
Reply
#2
Nice tutorial Vector, I can see you put a lot of work in this.
Reply
#3
(02-13-2017, 01:39 PM)Knife Boss Wrote: Nice tutorial Vector, I can see you put a lot of work in this.

Thank you, i did put a lot of work into it. I hope it was an entertaining read as well. I tried to make it more fun to read with some jokes and achievements and such :p
Reply
#4
(02-13-2017, 02:40 PM)Vector Wrote: Thank you, i did put a lot of work into it. I hope it was an entertaining read as well. I tried to make it more fun to read with some jokes and achievements and such :p

It was very well written xD. I was wondering what the main differences are between python 2.7 and python 3. Why do people use over the other?
Reply
#5
(02-13-2017, 05:17 PM)Knife Boss Wrote:
(02-13-2017, 02:40 PM)Vector Wrote: Thank you, i did put a lot of work into it. I hope it was an entertaining read as well. I tried to make it more fun to read with some jokes and achievements and such :p

It was very well written xD. I was wondering what the main differences are between python 2.7 and python 3. Why do people use over the other?

The main difference between the two is that of syntax. Also because 3.x is newer it has different modules than 2.7, it still has the same core libraries though but a lot of the other modules available on 2.7 are being ported to 3.x as well. In the end it comes down to what you prefer, i started with 2.7 so it's generally what i go with. In my experience however, once you know the syntax of either one or the other it is pretty easy to switch between the two when necessary.
Reply
#6
About python imports, I never really thought about this. Besides syntax is there a difference between importing an entire module ("import foo") and importing all the classes of a module ("from foo import *")?

I always thought the star import was bad because it forced you to load more than necessary, but wouldn't the regular import force you to load the same amount?

Anyway nice contribution.

(02-13-2017, 05:17 PM)Knife Boss Wrote: It was very well written xD. I was wondering what the main differences are between python 2.7 and python 3. Why do people use over the other?

I'm sure there are more differences, these are all I ever noticed:
Code:
print "foo"
vs
print("foo")

And
>>> 1/3
0
vs
>>> 1/3
0.3333333333333333
Reply
#7
(02-16-2017, 03:36 AM)StickFigure Wrote: About python imports, I never really thought about this. Besides syntax is there a difference between importing an entire module ("import foo") and importing all the classes of a module ("from foo import *")?

I always thought the star import was bad because it forced you to load more than necessary, but wouldn't the regular import force you to load the same amount?

Anyway nice contribution.

(02-13-2017, 05:17 PM)Knife Boss Wrote: It was very well written xD. I was wondering what the main differences are between python 2.7 and python 3. Why do people use over the other?

I'm sure there are more differences, these are all I ever noticed:
Code:
print "foo"
vs
print("foo")

And
>>> 1/3
0
vs
>>> 1/3
0.3333333333333333

Asterisk imports are generally considered bad practice because it messes with your namespaces. Furthermore, explicit is always better than implicit, asterisk imports are implicit. Here is a good article that goes into detail on why this is important.

https://shahriar.svbtle.com/importing-star-in-python
Reply
#8
That's a very nice introduction to newbies coming from Windows. Thanks for the tutorial man! I've decided to sticky this tutorial so that people can find it easier. Good work, keep it up!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Ebook Collection [89 Files] Insider 15 88,141 08-12-2021, 08:02 PM
Last Post: zzeuss
  NSA Python Training Insider 4 28,787 08-12-2021, 02:14 AM
Last Post: hworth
  Having an issue writing a python script with vim FancyBear 4 22,484 01-03-2021, 11:27 PM
Last Post: FancyBear
  Python Data structures and algorithms resources skinnyj0shua 1 17,332 12-23-2020, 12:52 PM
Last Post: enmafia2