Introduction: Python Programming Kursus (Python 2.7)

Ever wanted to learn programming?
Well, what language is better to start it than pyhton! It is a fast and powerful language. You can do nearly everything with python! Above that the syntax for it is fairley simple.
Throughout this tutorial I’ll be trying to teach you python, in this case python 2.7. The difference from python 2 to python 3 isn’t that large.

Be sure to only do one step at a time, don’t over-do it with too much new stuff at the same time, as you want to understand everything! If you forgot something, simpley go a step back and re-do the old stuff.

If you have any problems or are stuck somewhere
don’t hesitate to ask!
I am here to awnser your questions, no question can be too stupid, so ask!

If you liked this pelajaran, why titinada favorite it and subscribe?
Also, be sure to check out my website for a bunch of cool stuff!

Also, please vote for it in the contests!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Step 1: Install Python

First of all you need to install python, as you’ll need an external programa to run python files, similar to how you need java to run java programs you’ll need python to run python programs.
You can download it here, be sure to download version 2.7 (or 2.7.6 or whatever that 2.7 link is at the moment you are reading this tutorial).
Well, download and install, pretty self-explanitory i guess.

You’ll also need something to edit your python files, I’d recommend for the windows users notepad++ due to its syntax highlighting.
On Linux I personally use Sublime Text, but gedit or kate are also a pretty good text-editors with syntax highlighting.

I’d recomend to making some kind of folder dedicated to programming in your file system to organize things a bit.

So let’s go on to the next step and see if you set up everything correctley!

Step 2: Hello World!

Let’s make a Hello World programa – all that it does is displaying “Hello World!” to the screen and exit.
So, open up your text penyunting and enter the following:

            print
            "Hello World!"
            raw_input("Press Enter to exit")

Save the program with the extentiony
.py
for example
helloworld.py
.
Time to run your program! Do so by either rightclicking and run it with python, or by simpley double-clicking it.
A console will pop up and display “Hello World!” and it’ll ask you to hit enter to quit the program.

Let’s take a closer look at those two lines:

            print
            "Hello World"
          

This line basically tells to print out text to the console, all the text must be in quotation marks. You could try for example something like print “Muffins!” which will print muffins to the console.

            raw_input("Press Enter to exit")

This line will wait on the input from the user and won’t continue mencicil he hit the enter key. Here again You notice that text in quotation marks which will be displayed to the screen.
Take this line more or less ‘as is’ right now, I’d recommend putting it as the last line of all your programs in this latihan now so that the window won’t close directly after the execution finished (if you execute oper console or over terminal you can omit this of cource).

Step 3: Math!

What can a computer do? Oh yes, it can calculate things! So let’s have some fun with math:

            print
            1
            +
            1
          

Note how this print line doesn’t use the quotation markes, take that again ‘as is’ right now.
So, what do you guess this program will output?
Yes, it will output the solution of 1+1, which is 2, obvious. So aparently you can add numbers normally in python.
All the basic math operators are working without a problem:

            print
            1
            +
            1
            print
            34
            -
            27
            print
            6
            *
            7
            print
            100
            /
            10
            print
            5
            **
            4
          

As you can see, addition, subtraction, multiplication and division is working just as expected. If you use two multiplication signs it’ll be exponential, so 5**4 is 5^4 (54) in python.

Also, python is following the proyek of operations we also use in every-day math, for example:

            print
            3
            +
            4
            *
            2
          

This is printing 11 because you compute multiplication prior to addition. Paranthesis also work normally:

            print
            (3
            +
            4)
            *
            2
          

This prints 14 because now the paranthesis is been computed first.
So, math in python is pretty straight-forward and intuitive, you can also use non integers like this:

            print
            3.1
            +
            2.8
          

Which prints 5.9.
If you understood this math, let’s head on to the next step!

Step 4: Variables

Yes, variables, you need them everywhere when programming! But no worries, the concept isn’t too hard once you understand it.
A variable is basically some way to store some information while you are running the program which you can easily access throughout it.
There are different kind of variables, ones that store integers, others that store floats, that are numbers with a fractional part, there are strings, a sequence of characters, and many more!
Let’s first take a look at the most simple variables out there: integers.

Variables always have a name, it can be any combination of letters you prefer, I’d recommend making some obvious name, though.
For example, a variable called
counter
is pretty clear what it does, it counts some things, while a variable called
lolthegame
isn’t so clear what it does.

So, how do I use this dark magic to store my numbers? By simply using a equal sign!

x
            =
            5
          

This will store now the number 5 into the variable
x, note that the variable always is on the left of the equal sign and the number on the right!
We can also put a sequence of math operators on the right:

x
            =
            5
            *
            2
          

In this case x would have the value of 10, as 5*2 is equal to 10.

Important: The only thing on the left side of the equal sign may be a variable, something like x + 5 = 0 is Tekor, you’ll have to do x = -5

We can also print out the content of variables to the terminal:

x
            =
            5
            *
            2
            print
            x

This will print 10, as x has the value of 10 when printing.

In fact, we can use our variables just as normal numbers!
That means we can……
1st: use them in math operations:

x
              =
              7
              -
              3
              print
              x
              **
              2
            

This will print 16, as x will have the 4 and 4 squared is 16.


2nd: Use them to define other variables

x
              =
              5
              y
              =
              x
              +
              9
              print
              y

This will print 14, as when defining y the x is substituted with its value, in this case 5, and 5+9 is 14.
In fact, we can change x after defining y again and y will not change:

x
              =
              5
              y
              =
              x
              +
              9
              x
              =
              10
              print
              y

As you can see, once a variable is set by changing other variables you can’t change the content of the first one anymore.

3rd: Use it to define itself:

x
              =
              5
              x
              =
              x
              +
              1
              print
              x

This will print 6, as x is been re-defined by itself, in this case increased by one.


So, to sum up, variables, well,integer variables, the only ones we used so far, can be used as numbers anywhere you want!
When printing and when defining variables, including themselves!

Step 5: Task #1: Quadratic Solvers

Yep, a Quadratic solver!
You can already do it!
This may seem a bit complex for you right now, but actually it is all about  putting variables in a formula. if you don’t know the quadratic formula, check it out here: http://en.wikipedia.org/wiki/Quadratic_formula
A little hint when making this, raising something to the power of 0.5 will be like getting the square root.
So for example:

            print
            4
            **
            0.5
          

Will print 2, as the square root of 4 is 2.
So, have some fun trying it out a bit, head on to the next step to see a possible solution. Note that when programming there isn’t only one way to get to your solution, in fact there are infinite ways.

Step 6: Task #1: Quadratic Solvers (solution)

Ok, this is my solution for the quadratic solver, yours may vary!

a
            =
            1
            b
            =
            0
            c
            =
            0
            print
            (-b+(b**
            2
            -
            4
            *a*c)**
            0.5)/(2
            *a)
            print
            (-b-(b**
            2
            -
            4
            *a*c)**
            0.5)/(2
            *a)

Common mistakes:

  • When multiplying two variables with each other or with a number you will still need the multiplication sign, e.g. instead of 4ac you will have to type 4*a*c
  • Some parenthesis were set wrong
  • You forgot that there are two possible solutions
  • The program errors when picking bad values for a, b and c. This is because of trying to take the square root of negative numbers, which we can’kaki langit. At this point we can’horizon tapis out the errors yet.

So, if you understood this quadratic solver, and were able to program it, let’s head over to the next step!
If you did not manage to do this, please look over your acara again and the commom mistakes listed. If that doesn’tepi langit help go back a few steps and read it through again.

Step 7: Comments

Comments are lines of code that aren’ufuk been executed.
Now you might think “hey, what is that good for?”
Well, they are very useful if used correctly – it’ll help you understand your own code far better.
Comments begin with a hash (#) and last berayun-ayun the line ends.
Here is the quadratic solver again with some comments:

            # define my variables
            # equation form ax^2+bx+c
            a
            =
            1
            # a is 1
            b
            =
            0
            c
            =
            0
            #print solution
            print
            (-b+(b**
            2
            -
            4
            *a*c)**
            0.5)/(2
            *a)
            # first solution
            print
            (-b-(b**
            2
            -
            4
            *a*c)**
            0.5)/(2
            *a)
            # second solution
          

As you can see, comments can be used to make your own code far easier to understand. It can be quite tough to pic up on code that is a few months old.

Step 8: Variable Types

As already mentioned before, there are different variable types.
It is important that we look at the different variable types before we move on to how to ask the user for input.

Integer

A integer, or for short int, is a variable that can store only whole numbers, no fractional part allowed here.
Example:

x
            =
            5
            print
            x

Float

A float is a variable that can store a number containing a fractional part.
Example:

x
            =
            3.14159265
            print
            x

String

A string, or for short str, is a kind of variable that can store characters, so, it can store text. This text must be marked by quotes, just as we already had if we wanted to pring text.
Example:

x
            =
            "Derpy Hooves"
            print
            x
          

Important: you can’n mix numbers and strings in math operations!

But: you can mix ints and floats in math operations, as something like this is working just fine:

            print
            2
            +
            4.5
          

But wait a sec, can you do some math on strings at all? Yes you can! You can add them up!
Try this out:

food
            =
            "Muffins"
            print
            "Derpy likes "
            +
            food
          

As you an see, it’ll display
Derpy likes Muffins.

But what if I have now a string containing 5, so something like this, how can i do math on it?

x
            =
            "5"
            print
            5
            +
            x
            # this will error
          

The trick is to convert between different variable types. To do so there are certain functions.
The table below might help you:

Variable type Example Conversion function
Integer x = 5 int()
Fload x = 3.14159265 float()
String x = “Muffins” str()

Who, that was a lotre of information now!
Let’s have some examples:

x
            =
            "5"
            print
            5
            +
            int(x)
            # hey, this is working now as we are converting the string to an int!
          
x
            =
            9001
            text
            =
            "Derpy wants "
            +
            str(x)
            +
            " Muffins"
            # we need to convert the int to a string, because we can'tepi langit add ints and strings
            print
            text
          

After you understood this we are finally ready to ask users for input!

Step 9: Input

Only having a program run without having some kind of input is pretty boring, the result will always be the same. So why not ask the user for input?
For that we have a nice function, called raw_input(). Looking familiar? Yep, that is the one we used in the hello world program to wait for the program to exit.
Inside of the parenthesis we put a string on what to display before the flashing cursor where we input stuff.
The function returns a string.

Ok, ok, slow down a sec, that was faaar to much information in so few sentences, give berpenyakitan examples!

x
            =
            raw_input("x=")
            # this will display x= before the flashing cursor where you input stuff
            x
            =
            float(x)
            # raw_input always gives you a string, thus you have to convert it to a number, in this case we use a float to be able to input numbers like 2.5
            print
            x/
            2
            # let's just print half of what the number was before
          

As seen, we need to convert the input to a float before we can do math on it.
If we only wanted integers to be valid as input we’d need the int() function instead.
You can also optimize it a bit like the following:

x
            =
            float(raw_input("x="))
            print
            x/
            2
          

Functions can be nested into each other as much as you want.

You will see that the program crashes if you input a non-number, there are ways to detect that kind of stuff, we’ll get later to it.
How about, for now, you’ll re-acara your quadratic solver to ask the user for the variables to input?

Step 10: Modulus

Modulus is a math operation may people aren’t familiar with, but it can get quite useful when programming.
Modulus is the remainder of division, its symbol in python is a percent sign (%).
Some example:

            print
            3
            %
            2
            # outputs 1
          

So, what is the magic behind this? Well, if you divide three by 2 you’d get 1 and still have one left, that is modulus.
For example 17%7 would give 3, as 17/7 is 3, with a remainder of 3.
This can be very useful in checking if a number is dividable by another number, because if the remainder is 0 then it is dividable.

x
            =
            int(raw_input("x=")) y
            =
            int(raw_input("y="))
            print
            str(x)+
            "%"
            +
            str(y)+
            " is "
            +
            str(x%y)
          

If you understood this, then let’s move on!

Step 11: If-Conditions

Having code only execute strictly in one and the same titipan is boring, it would be quite cool to have conditions on some things!
Like, let’s say we have the user input a number, and we want the program to tell us if the number was less than 10 or titinada.
Such a programa could look, for example, like this:

number
            =
            int(raw_input("Please enter a number:"))
            if
            number
            <
            10:
            print
            "Your number was less than 10!"
          

As you can see, such
If-Conditions
are fairly simple. you have a keyword,
if
a condition, in our case
number < 10
and a colon (:). After that you indent the code that you want to be executed only if that condition is true.
If the condition is false, it will skip the if-block and will continue executing the code afterwards. Take this code as an example:

number
            =
            int(raw_input("Please enter a number:"))
            if
            number
            <
            10:
            print
            "Your number was less than 10!"
            print
            "I will always be displayed!"
          

It is also possible to have some piece of code executed only if the condition was false, take the following example:

number
            =
            int(raw_input("Please enter a number:"))
            if
            number
            <
            10:
            print
            "Your number was less than 10!"
            else:
            print
            "Your number was 10 or greater!"
          

Ok, now you might think
“Slow down Sorunome, why did you write
10 or greater?”
.
Well, that’s pretty simple. Let’s say you entered 10 as your number, Python will see the if-condition. 10 is Not less than 10, so it jumps to the else part!

You can also check if a number is greater than a value with the
>
ahli mesin, or if it is equal, with the
==
operator.
Important: don’n mix up the single equal sign (=) for storing to variables and the double-equal sign (==) for comparing two variables.
This is a common mistake.

Here is a reference table for pythons comparison operators and their English translation:

Python English
< is less than
> is greater than
== is equal to
!= is not equal to
<= is less or equal to
>= is greater or equal to

Now, let’s have a little program where we have the user guess our number we put in before:

number
            =
            int(raw_input("Guess a number:"))
            if
            number
            ==
            5:
            print
            "You guessed correctly!"
            else:
            print
            "You didn'lengkung langit guess correctly."
          

As you can easily see, it will get quite boring after the user managed to guess the number once. So head on to the next step to learn about random numbers!

Step 12: Random Numbers

Random numbers! Who doesn’ufuk need those? Randomly decide what the next Tetris block is, have the Pac-Man ghosts move randomly around and what not else?

First of all, it is impossible for the computer to generate truly random numbers, that is why they commonly use something called
pseudo random. Pseudo random is, when you have some very large function that somehow, through some kind of logic creates a number which seems random to us. For video games and seremonial stuff that kind of random is enough.

So, how do i do that in python? Code examples are fun!

            # tell python that we want to use random numbers
            import
            random
            # print a random number between 0 and 50.
            print
            random.randint(0,50)
          

It is as easy as that! You can also store the result into a variable and do all kinds of magic with it, if you desire so.

Let’s take our number guessing example and enhance it to use random numbers.

            import
            random  number
            =
            int(raw_input("Guess a number (between 1 and 100):")) randNumber
            =
            random.randint(1,100)
            if
            number
            ==
            randNumber:
            print
            "You guessed correctly!"
            else:
            print
            "You guessed wrong. The solution was "
            +
            str(randNumber);
          

Ok, that example is actually quite challenging. Anyways, I hope you get the concept. Head on to the next step to learn about loops! (And to make your number guessing acara more awesome)

Step 13: While-loop

Let’s say you want your user to guess a number until the user managed to guess the number correctly.
Or, to have it more simple for now, have a counter count up while it is less than 5.

            # set our counter first
            counter
            =
            0
            # loop while the counter is less than 5
            while
            counter
            <
            5:
            # let's just print our counter
            print
            counter
            # time to increase the counter
            counter
            =
            counter
            +
            1
          

The while loop is structured very similar to the if-condition only that this time you use the keyword
while. The condition is checked once at the beginning of the loop and every time it reaches the end of the loop. If the condition is still true it’ll execute the loop again.

So, any idea on how to make the number-guessing game so that the user will have to guess berayun-ayun he gets the number correct? Head on to the next step to see my implementation of that!

Step 14: Number Guessing Program

This is my implementation of this, yours may vary:

            import
            random  number
            =
            int(raw_input("Guess a number (between 1 and 100):"))
            # initially ask the user for a number
            randNumber
            =
            random.randint(1,100)
            # create a random number
            while
            number
            !=
            randNumber:
            # if the user guessed correctly on first try this whole loop is skipped
            number
            =
            int(raw_input("You didn't guess right, guess again:"))
            # re-store a user-input number, it will get checked automatically at the end of the loop
            print
            "You guessed correctly!"
            # the only way you can reach this line of code is if the user guessed correctly.
          

Ok, this is pretty hard. So why not make it display if you guessed to high or to low?
Again, your solution may vary:

            import
            random  number
            =
            int(raw_input("Guess a number (between 1 and 100):")) randNumber
            =
            random.randint(1,100)
            while
            number
            !=
            randNumber:
            if
            number
            >
            randNumber:
            print
            "You guessed to high"
            else:
            print
            "You guessed to low"
            number
            =
            int(raw_input("Guess again:"))
            print
            "You guessed correctly!"
          

Step 15: Take a Break

You learned a lot so far, so take a break, let the previous stuff sink in, if you feel the need re-read it again.
Here are some ideas for programs you can try to do:

  • Math helper with things like the quadratic solver, you could have it have a “menu” where you let the user input a number in the beginning to chose the formula he want’s to compute
  • Unit conversion!
  • MOAR number guessing (like adding that it displays you how many guesses it took you to reach the answer)
  • Magic
  • ???
  • rule the world

Step 16: Functions

Ok, you probably run into this by now when playing around some: You had some piece of code that you copy-pasted all over the place and thought like “man, can’ufuk I just have this piece of code defined some way and call it?”
The answer is: Yes you can!
Let’s just do a really stupid example for a function, one that simply adds two numbers:

            def
            add(a,b): 	c
            =
            a
            +
            b
            return
            c
            print
            "Add two numbers"
            x
            =
            int(raw_input("First number:")) y
            =
            int(raw_input("Second number:")) solution
            =
            add(x,y)
            print
            solution
          

Ok, so what is going on here? With the keyword
def
you tell python that you make a new function. Now everything before the first parenthesis is the function name. Set it to something that describes what you are doing, like in my case
add. Inside the parenthesis are two
parameters, so basically variables you pass on to the functions.
Important: Variables inside and outside of functions are
not
the same, to avoid conflict just name your variables differently!


Now, indented, follows all the code that the function runs. With the
return
statement you tell the function what to return.
As you can see in the executed code, we pass x and y on to the function, which “become” a and b, respectively, inside the function. If you changed a and b in the function somehow it wouldn’kaki langit change x and y, though, as they only exist outside the function.
The function returns c, and we store that to the variable
solution, just like we stored the input.

Wait.
WAIT.
Just like the input? JUST like the input? YES! raw_input is a built-in function!

Step 17: Done!

I hope you enjoyed this cak bimbingan a lot and found it helpful!
For derita it was fun to write it.
Again, if you have any questions, don’t hesitate to ask!

This tutorial also only explained the very basics, programming is endlessly deep, and I hope I could take you on some nice trip with it!
Maybe I’ll make some more advanced tutorial some time, explaining stuff more in-depth, which would require previous knowledge, though.

Be sure to comment, rate and
subscribe!
Check out my website for more awesome stuff!

Be the First to Share

Recommendations