Author

Topic: [ANN] Free python lessons (a week and a half to get you started) (Read 430 times)

copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
The programming challenges solved, if there are any questions, I'm going to make a new thread for answering those and for code reviews.

1. (easy) Make a loop that will print every whole number from 1 until 100.
Code:
for loop in range(1,101):
    print(loop)
I think I made this one more challending than I expected to with it having to start at 1 and not 0.
Anyway, this works by saying that for every item in a list from 1 until 100, print that item from the list.



2. (easy) try to get someone to input a whole number between 0 and 9 and keep asking until you get one.
Code:
n = int(input("Please input a number between 0 and 9: "))
while (n <= 0 or n >= 9):
    n = int(input("Please input a number between 0 and 9: "))
print("Thanks you inputted a valid number")
This take an input and sets it to n from the user (where n is an integer).
It then says that while n is less than or equal to zero and greater than or equal to nine we want to keep the code going so that we can get a valid number.
If the number inputted is accurate to start with, the code inside this loop won't run and the user will be told they've inputted a correct number.

3. (medium) make code for the classic fizz-buzz game (this is what you would be asked to do if you wanted to become a software engineer, they like to ask it at interviews - or so I've been told). Essentially, take your code from question 1 and if the number is divisible by three to give a whole number print fizz, if it is divisible by five to give a whole number print buzz, and if it is divisible by both print "fizzbuzz" (hint, the % modulo symbol helps you find the remainder: 5%3=2, 1%3=1, 6%3=0.
Code:
fizz = 3
buzz = 5
for loop in range(1,101):
    if (loop % fizz == 0 and loop % buzz == 0):
        print("fizzbuzz")
    elif (loop % fizz == 0):
        print("fizz")
    elif (loop % buzz == 0):
        print("buzz")
    else:
        print(loop)

3. (medium) make a "guess my number" game. Get the computer to generate a random number between 1 to 100. Then ask the user to input a number, if the number is greater than compNumber then tell them that and if it's less than or equal to then tell them that. They have 10 attempts to guess the right number otherwise they lose and the number is revealed to them.

Code:
from random import randint
myNum = randint(1,101)
print("I've thought of a number between 1 and 100, can you guess it?")
for guesses in range(3,0,-1):
    guess = int(input())
    if guess > myNum:
        print("Lower, you have "+guesses+" guesses left")
    if guess < myNum:
        print("Higher, you have "+guess+" guesses left")
    else:
        print("You are correct!")
        break

4. (hard) make a rock, paper scissors game (user v computer)

Code:
from random import randint
choices = ["rock","paper","scissors"]
n = True
while n:
    choice = choices[randint(0,2)]
    n = False
    userChoice = input("Choose rock, paper or scissors: ")
    if userChoice.lower() == "rock":
        if choice == "paper":
            print("You win!")
        elif choice == "scissors":
            print("You lose!")
        else:
            print("We drew!")
    if userChoice.lower() == "paper":
        if choice == "rock":
            print("You win!")
        elif choice == "scissors":
            print("You lose!")
        else:
            print("We drew!")
    if userChoice.lower() == "scissors":
        if choice == "rock":
            print("You lose!")
        elif choice == "paper":
            print("You win!")
        else:
            print("We drew!")
    else:
        n = True
    if n == False:
        userChoice = input("Do you want to quit y/n?")
        if userChoice.lower == "y":
            n = True
        else:
            n = False



I made a buggy infinite loop in this last one. I'll fix it in a few days but here's the first four solutions for now. I think the final one should be achievable from here.

Edit Fixed the errors in the last solution.
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
In this part of the course we'll be looking at object orientation (an object is a data structure that can hold different types of variables, when we move onto java or c# it'll make more sense but for now we're in python).

We'll first look at how subroutines/methods work.
Follow this example
Code:
def printThis(data):
    print(data)

printThis("Hi")
printThis("I'm a function!")
This example doesn't particularly make sense because print is already a function however it's a good start as to what we will be getting onto. Alter around the strings that are printed or even what happens to the string (i.e. you can use [::-1] to reverse the string in the print statement on line 2).


Let's look at a program we've already covered, we'll take this one as an example
Code:
n = 1
while n <= 4:
    print(n)
    n += 1
Attempt to convert this into using a method (if you're stuck see below but it will be helpful to try it yourself).

Code:
def loop(n):
    print(n)
    return n+1

n = 1
if n <= 4:
    loop(n)

You'll notice that while this makes the code more complex, it makes it easier for a programmer to read and maintain (especially if the code within the loop function is particularly long).




In the console we'll use the following code:
Code:
class User:
    def __init__(firstName, lastName, userID, email):
        self.__firstName = firstName
        self.__lastName = lastName
        self.userID = userID
        self.__email = email
   def getUserData(self):
        return (self.__firstName, self.__lastName, self.userID, self.email)
I'll explain this bit before we continue:
Line one: we make a class (a series of data entries) and give it a name we can use to refer to it.
Line two: this is the class that will be called in order to generate a new user.
Line three until six (inclusive) are lines that define the variables passed to our function.
Line seven is a way of getting the data we have juse entered.
In line 8 we finally return this data in a friendly tuple (it's like a list but you can't edit it and it's dipslayed in python inside brackets ().

I did say I wasn't going to cover private, public and protected in this part of the cours but I feel like I have to do at least private and public:
Private - accessible to only that object (in this example user) - these veriables begin with a __
Public - accessible to anything universally within the program while that variable is being used (such as methods to get the information).

However, in python this doesn't actually happen as python likes to store variables a bit differently (and form its objects differently too).

Going back to the previous code we are now going to make our first object (hit enter until you get back the three ">" and you're ready).
Type
Code:
j = User("jack","g",50,"[email protected]")
satoshi = User("satoshi","nakamoto",2,"[email protected]")

Now run dir(j) and it will show you every command you can run on j (we're only interested in the ones that don't begin with an underscore _ as they're the ones we're legally aloowed to edit [under law of me]).

run print(j.userID())
and then print(satoshi.getUserData())



Two of the nicest structures to represent in classes are stacks and queues (these will be much slower in python but are much faster in c# and java if you only want limited functionality).

A stack is a lifo data structure. The Last piece of data In is the First piece of data Out.

We can do too main things to a stack:
POP this takes the last piece of data and outputs it
PUSH this adds an extra item to the stack.

(Disclaimer: I don't have python installed on my computer so this might be a nice debugging exercise for those of you who try this)
Code:
class node: # this will store each piece of data in the stack
    def __init__(self, data):
        self.__data = data
        self.pointer = 0
    def getData(self):
        return self.__data

class stack: #creates our stack variable
    def __init__(self):
        self.__height = 0
        self.__top = 0
    def POP(self):
        if self.__height > 0:
            print(self.__top.getData())
            self.__top = self.__top.pointer
        else:
            print("Stack underflow: nothing to remove")
    def PUSH(self, data):
        tmp = self.__top
        self.__top = node(data)
        self.__top.pointer = tmp
        self.__height += 1

theStack = stack()
n = 0
while n != "-1":
    action = input("Push or pop?")
    if action.upper() == "PUSH":
        pushWhat = input("what would you like to push?")
        theStack.PUSH(pushWhat)
    elif action.upper() == "POP":
        theStack.POP()
    n = input("would you like to continue, type -1 for no or anything otherwise")

I will leave this here as I feel that last bit of code will take a while to digest. Please pm me or bump the discussion thread if you don't understand anything,, principles of stacks are confusing (I'll check the code runs within about 10 minutes of posting it if you want to wait).



EDIT: broken code has been fixed!
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
I am going to take you through file handling in this exercise, first we'll start off with the common permissions.
'r' - is read from a file
'w' - overwrite to a file (as in it deletes anything before the file was opened)
'a' - is append to the bottom of a file
'r+' is a combination of a and w

We will make a simple file so open a program called "basicFileFiddle.py", and use the folowing code
Code:
file = open("hello.txt","w")
file.write("Hello")
file.close()
file = open("hello.txt","r")
print(file.read())
file.close()

Then run this program and it will output "hello" the regular convention on most media is that you close a file once you have finished writing to it. I like to close it no matter what, if you forget to close it it mihgt not cause a difference once or twice but if python doesn't pick it up it could damage that sector of the hard drive until you next format it.


The newline character "\n" adds a line break to the end of the file (it's not really very interesting what it actually adds though.

This time we will use the same code as last time but we want to print on two lines so we do this:
Code:
file = open("hello.txt","w")
file.write("Hello \n world")
file.close()
file = open("hello.txt","r")
file.close()
print(file.read())


We can then append each line of this file to a list
Code:
file = open("hello.txt","w")
file.write("Hello \n World")
file.close()
file = open("hello.txt","r")
myList = []
for line in file:
    myList.append(line)
file.close()
print(myList)


Now we're going to look at comma separated variable files (csv) - just because python has a built in library for them.

Code:
import csv
file = open("csvFile.csv","a")
n = csv.writer(file)
myList = ["hello","world"]
n.write(myList)

Now we'll read from this file
Code:
import csv
file = open("csvFile.csv","r")
fileContents = []
for line in file:
    fileContents.append(line)
print(fileContents)


As an extra challenge as the ones I gave yesterday. I'd like a program that can give a output of a duodecimal timetables grid to a csv file.
PM submissions to me and a bitcoin address and there may be a $10 prize for one of the submissions (I want to see if anyone's actually been following these tutorials or not). Deadline will be 72 hours from this edit, anti plagiarism tests will be done. You can get hints via pm.
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
As per request, today is also going to include some coding exercises. Once you have done them, send me a pm of your work and I can offer you a review (I'll post solutions on the support thread in a few days if you get stuck on one of them). If you don't understand how to do one of them also send me a pm and I'll help!

Loops allow us to go back over a stage that we have previously done.
There are two types of loops in python FOR loops and WHILE loops each of these have their preferred implementation.

First of all, you may find it helpful to go back and look at the range function from day 2 to understand how for loops work.
In python for loops work by taking a list and iterating over every object of the list, to start with we want to print out every number from one until four.

Code:
n = [1,2,3,4]
for item in n:
    print(item)
You'll notice this prints out every item from 1 until 4
Code:
for item in range(1,5):
    print(item)
This does the same however:
Code:
for item in range(4):
    print(item)
Gives a very different output...



A while loop works differently to this and works like an if statement. If the condition is true, the loop runs. If the condition is not then it doesn't.

Code:
n = True
k = True
while k:
    if n:
        n = False
        print("n changed")
    k = False
    print("k changed")

This changed k and n individually so the loop is run twice.

Code:
n = True
k = True
while k:
    if n:
        n = False
        break
        print("n changed")
    k = False
    print("k changed")

We can also use a break statement if we want to check a condition part way through the while loop.

The while implementation of the for loop earlier to print values from 1 to 4 will look something like this:
Code:
n = 1
while n <= 4:
    print(n)
    n += 1
OR like this:
Code:
n = 1
while n < 4:
    print(n)
    n += 1


Programming challenges

1. (easy) Make a loop that will print every whole number from 1 until 100.
2. (easy) Like yesterday code, try to get someone to input a whole number between 0 and 9 and keep asking until you get one.
3. (medium) make code for the classic fizz-buzz game (this is what you would be asked to do if you wanted to become a software engineer, they like to ask it at interviews - or so I've been told). Essentially, take your code from question 1 and if the number is divisible by three to give a whole number print fizz, if it is divisible by five to give a whole number print buzz, and if it is divisible by both print "fizzbuzz" (hint, the % modulo symbol helps you find the remainder: 5%3=2, 1%3=1, 6%3=0.
3. (medium) make a "guess my number" game. Get the computer to generate a random number between 1 to 100 (starting with:
Code:
from random import randint
compNumber = randint(1,101)
This will generate the number. Then ask the user to input a number, if the number is greater than compNumber then tell them that and if it's less than or equal to then tell them that. They have 10 attempts to guess the right number otherwise they lose and the number is revealed to them.
4. (hard) make a rock, paper scissors game (user v computer)
5. (hard) add validation to number 3 to make it so they can only input a number. Treat the number as a string and fetch each element based on its index.
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
This will be quite a short exploration into these statements and how these are used

Firstly, if and elif statements take a single boolean value (0 or 1) in order to determine they can be run.
A logical operator (AND, OR, NOT, etc) can be used for these.
Such that:
1 AND 1 = 1
1 AND 0 = 0
0 AND 0 = 0
0 AND 1 = 0

For an OR operator:
1 OR 1 = 1
1 OR 0 = 1
0 OR 1 = 1
0 OR 0 = 0

NOT 0 = 1
NOT 1 = 0


To understand how what we are going to be doing works better, we want to open up our consoles and run a few tests
Try run the following:
Code:
print(1 == 1)
print(1 == 0)
print(0 == 1)
print(0 == 0)

Now try something a bit different and do
Code:
 
print(not(1==0 and 1==1))
print(not (1==0 and 1==1) or 1)
print(not(1==0 and 1==1) == not(1==0 and 1==1))

In the console try running:
Code:
if (1 == 1):
    print("hello")
After the if statement you'll notice that the >>> is replaced with a ... this means you need to add an indent to the level of code you want to run (this will become clear further down). It is technically called whitespace and is very important to python (sadly). Generally we like to indent at 4 spaces when sharing code but personally you can do as many as you want. For these examples I will do 4 spaces but I'm no stranger to doing 1 or 2.

We can use these in python to compare variables but we'll start with a simple if statement:
Make a new python file and call it "ifSimpleExample.py" or something similar:
Code:
k = 1
if k == 0:
    print("k is zero")
else:
    n = int(input("Please enter a number, 1 or 0"))
    if str(n) == 1 or str(n) == 0:
        print("Thank you")
    else:
        print("You tried to break me!")

Try running this code and you'll see how it works, we can improve this by saying that we want to remove the int and compare them individually to the numbers as a string:
Code:
k = 1
if k == 0:
    print("k is zero")
else:
    n = input("Please enter a number, 1 or 0")
    if str(n) == "1" or str(n) == "0":
        print("Thank you")
    else:
        print("You tried to break me!")

We can make this more productive by saying we want to make a list of acceptable inputs and use that to compare with value inputted with instead.
Code:
k = 1
acceptable = ["1","0"]
if k == 0:
    print("k is zero")
else:
    n = input("Please enter a number, 1 or 0")
    if str(n) in acceptable:
        print("Thank you")
    else:
        print("You tried to break me!")

For each iteration of the code above try running it, we'll write some different code now...
In the same file (or different if you'd like under any file name) try adding the following code
Code:
k = input("Please enter a 1 or a 0")
if str(k) == "1":
    print("Thanks you entered a one")
elif str(k) == "0":
    print("Thanks that's a 2!")
else:
    print("Wha...")
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
Today's topic will be quite small as there isn't much to inputs, you're just taking in a string for the most part.

The way people should learn to take an input is by doing something like the following:
1. Open up a new file in either vi/nano or the python idle and call it "inputName"
This will be a simple program where you input a string if your name and print hello and your name to the console.

Code:
print("What is your name? ")
name = input()
print("hello "+name)

As you'll notice this is three lines of code and looks obvious as to how you would code this however the more efficient method is to do the following
Code:
 
name = input("what is your name")
print("hello "+name)

This is now much shorter in code than the previous one and is much easier to store and review.


We are going to do the same as before but with age instead of your name:

Code:
age = int(input("How old are you?"))
print("age")
Try adding this to the last number and print your name and your age to the screen (only you can see your age unless you have a virus but go ahead and put 21 if it makes you feel younger Grin).

It's helpful to notice that if you do it this way then the program is easier to break so it isn't recommended unless there's something you can use to move on if the user inputs "A" instead of a number (or any other string).
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
In the second day of our tutorial we will focus on variable assignments and printing these variables in python:

Enter your python console either by running the python idle (in the gui) or by typing python in your cli.
type
Code:
n = "hello world"
now since we're in the console you can either write
Code:
n
or
Code:
print(n)
in order to print our new variable.

(hint, if you're in the console you need to place the cursor so that it starts at >>> if it isn't there by default)

This is making a simple string element which gets assigned (a string is a string/series of characters)

Now we're going to make a list of items so in the console type
Code:
myList = [1,2,3,4]

Have a go at printing myList to the console using:
Code:
print(myList)
Now you'll notice it appears just as it is assigned above, we need to understand how the data is stored if we want to pull out individual items (if you want a more advanced explanation then I can give one but for now we can focus on it simply).
The first index/address of the first element is 0 (think of it as we are at the start of the list and we need to go nowhere to get to the first item in the list - potentially the best way I can describe it simply and similar to how a complex explanation of it would be)
The second index is then 1 because we move one place along in the list, and so on until we get to the last item which is the number total of items -1.
Try these:
Code:
print(myList[0])
print(myList[2])
and try to print the items of your list

We can then take a look at other functions with lists such as:
Code:
print(myList[0:4:-1])
print(myList[0:4:2])
print(myList[0:2])

The syntax above takes the following approach:
print(myList[start index: the item to stop at: how many times to move after each iteration]))

Try running the same code again but instead of using the code we have here, use variable we set for n of "hello world", as a challenge, print the whole string backwards.

We can also take our n value and print "hello world" on two lines by saying:
Code:
print(n[0:5]+"\n"+n[6:11])
The "\n" parameter merely tells the operating system to start a new line in our console.

You may have noticed that doing an assignment of a list like this will become a bit tedious if you ever need to make a larger list of consecutive numbers (this may come in handy as for a proof to something and it is helpful for when we move onto loops later on to understand their structure). Instead we can write this:
Code:
myList = range(1,5)


Try the functions above for myList (you'll notice some of the outputs seem a bit weird but this is normal as it's python's way of saving space). You can still select individual elements from this.

assign the variable n to be the range of 0 to 100
Code:
n = range(0,100)

Now we're going to take the first element of n (n[0]) and we'll change its type to bool:
Code:
bool(n[0])
A bool is a value that can either be True or False. As you'll notice from the output here it will return a False, if you do the same with index 1 it will return True.

If we now do the same with any other number above 1 it will also return True (I assume this is to make coding some problems easier, if you want code to stop when the value equals zero for example you can do this quite easily - although it wouldn't be recommended just in case the python developers change this in the future).


I will end the tutorial here for now if there's anything I've missed then send me a pm or use the discussion thread I posted the link to in my OP.
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
For windows: search for python in the start menu by going to all programs or using the search input (if this doesn't work type start+r and write pythonw in the box).
Type in the shell that opens up (at the line that starts with a >>> )
Code:
print("hello")
.
Then go to file>new and a window will open up. Type in that window:
Code:
print("hello, world!")
Now go to file>save as and call your file "helloWorld.py" now hit F5 and check the program runs.

For linux (desktop):
If using the gui follow how windows works.
If using the coinsole we're going to be used a text editor on the console so check you have nano or vi installed on your computer (vi is pronounced VI it is NOT 6 Grin).
If you don't have either of these installed then install them.
If you have nano, it is a bit easier
[size=15]nano:[/size]
From the command line type nano "helloWorld.py"
Enter into the text editor that opens print("Hello, world!")
Hit control+x and then enter and then it will leave the editor and you have created your first program (it will give you a prompt if not you probably hit control+z, so type fg and enter, and then try again).
[size=15]vi[/size]
From the command line type vi "helloWorld.py" and press i
Type in "print("helloWorld")" (without the speech marks).
Then press escape and key in ":qw" (without speech marks)

After making your code run python helloWorld.py and your code should print an output to the console.

For linux (mobile):
Open up your python app and click "Editor"
Then you will want to type in print("hello, world!")
And click the save button at the bottom (it looks like an SD card symbol) and save it as helloWorld.py (if you miss the .py it won't run).
Then press run (it looks like a play button).
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
For today we will do basic console output and also set everything up.

Windows 10, 8.1, 8: Navigate to python.org and go to the "downloads" bit at the top and download the latest version of python
Good windows, 7 (xp and vista probably work the same way): the latest release of python may not work (you may want to try it first though). In case it doesn't, look for previous releases and go with python 3.5. Follow the instructions on the terminal.



Unix & linux:
Python should already come installed, if it does go to the terminal and type Python and it will tell you if it's installed or not. We will need this console again but just hit control+z to escape out of it for the moment.
if it isn't installed:
Debian: to install python on debian type:
Code:
sudo apt-get install python
on the command line and hit enter and it will install - if it asks you for a password put in your password. The sudo is optional but will be needed for debian and less for ubuntu.
Red hat: for red hat, you're going to want to type
Code:
yum install redhat
with an optional "sudo" at the start.


In android and ios search "Python3" in the app store/play store and install it.
copper member
Activity: 2856
Merit: 3071
https://bit.ly/387FXHi lightning theory
As mentioned earlier I'm going to start trying to teach python here there are a few important things to consider:
1. I don't really like python, I've been using it for about 7 years but the "everything is an object" methodology can make you sloppy at programming and make it difficult to move onto another programming language, you may well want to wait until I have done a java/C# course before scrolling any further (but it's up to you).
2. Python is a good language to get started on for beginners however being a programmer does not make you a software engineer. Everyone should be able to be a programmer to make you a good software engineer or Computer Scientist but it is not the entire package...

The days will be split up as follows:
1. Getting and setting up software needed/printing to the console
2. Variable assignments
3. Inputs
4. If, else, else if
5. loops
6. file handling
7. Object orientation (it's horrible in python but it is potentially a good thing to learn).

Every day I will hyperlink one of these up to the post where I explain it, I will have to make two posts for today for day one as I'll do one for Windows and one for Linux (including debian, red hat, android, ios and most other unix distros),

Local rule: if you want to comment on this topic, we have a thread here https://bitcointalksearch.org/topic/m.50235300 do not reply to this thread directly.

I was asked to add a tipping address:
bc1qdj5v2q8p398rdy6sexc0fapk4hcq0p54xz56ez

Feel free to ask for a lightning invoice via pm to send a few Satoshi my way. Sats go a long way in fees!
Jump to: