Thursday, August 25, 2016

Home


This little corner is for my children. Have fun guys!
 
Enter Raspberry PI
First Step in Python
Variables
Taking Input 
What if
Lather, Rinse, Repeat 
Dissecting a Loop 
Coding Warm Up 1 


Raspberry PI Picture
Raspberry Pi
.

Coding Warm Up 1

Previous | Home | Next

Before we start talking about while-loop, little

Coding Warm Up

Write a code to that ask user for a number and returns information weather the number was even or odd (hint: use modulo operator %). Don't check the below code unless you are completely stuck!

Let's say that we name the program even-odd.py and  when program runs it could show this:

pi@tron ~ $ python3 even-odd.py 
Please enter a number: 5
The number, 5 is ODD.
Nice talking to you. Bye!
pi@tron ~ $ python3 even-odd.py 
Please enter a number: 4
The number, 4 is EVEN.
Nice talking to you. Bye!
pi@tron ~ $


If you are stuck here's an example of code that does it:

number = int(input("Please enter a number: "))
if number % 2 == 0:
    print("The number,", number, "is EVEN.")
else:
    print("The number,", number, "is ODD.")

print("Nice talking to you. Bye!")

First, using function input() we ask user for a number. Remember that function input() will take a string (characters), not actual number. That is why we wrap this input with int(), which converts string into actual number that can be used for calculation. Try to do this without int and see what happens!

Then we check (true/false), if the number is evenly divided by 2 (no remainder). Then, remainder is equal to 0, which triggers first block of code (after semicolon):


print("The number,", number, "is EVEN.")

If there is reamineder, the value of the remainder is NOT zero! the block after else: is executed!

print("The number,", number, "is ODD.")

You can see the in my output above what it looks like!

That concludes the if statement. Program proceeds to the next line which gives us a final 'bye!'.
 
 Previous | Home | Next

Wednesday, August 24, 2016

Dissecting a Loop


Okay! The last thing with this loop thing is a bit confusing. Explain it!

I agree. So, let's try to see how it works, step by step.

Here's this loop:
for n in range(1, 21):
    print(n, "squared is", n * n)

First, let me remind you again, that when we use loops, if statements, or create our own functions (wait for them), we use statement followed by semicolon. Consider our loop here:

for n in range(1, 21):
What must follow is a block of code (statements) that will be repeated the number of times specified in the range(1, 21).
Step 1
Assign first number from the range (1) to variable n. In other words now n = 1.
Step 2
Check if n is grater than 20 (remember 21 - 1 is the last number in the range). NO! it is still in the range specified. Then proceed to step 3.
Step 3
Execute all statements in the block of code (indented by 4 spaces). We have only one statement here:
print(n, "squared is", n * n)
This will print value stored in variable n (comma means make a space and print the next item: squared is (comma means make a space and print next item which is value of multiplying n by n). That will print the following:

1 squared is 1
Step 4
Since current value of variable n is still in range (between 1 and 20), Python jumps back to for statement and uses the next value in the range (2) and assigns it to variable n. Now n = 2.

Step 5
The variable n is still in range, then it executes all statement in the block of code:

print(n, "squared is", n * n)

Now n = 2, so this print statement displays the following (n * n = 2 * 2 = 4):

2 squared is 4

Variable n = 2 that is still in range (1 - 20) jump back to for n statement. There, for statements assigns next value in range to variable n. Now, n = 3.

Step 6
The variable n is still in range, then it executes all statement in the block of code:

print(n, "squared is", n * n)

Now n = 3, so this print statement displays the following (n * n = 3 * 3 = 9):

3 squared is 9

Variable n = 2 that is still in range (1 - 20) jump back to for n statement:


Round and round it goes like that, until variable n is no longer in range (1 - 20). Then it leaves this block of indented statements and proceed to the next line of code. There is no next line of code in our little program. Python terminates the program as our list of task is now completed!

Problem Solving

Write a code that displays something like this:

pi@tron ~ $ python3 loop-again.py 

Using variable i in the loop.
Let's go!

Iteration 0 - variable i = 0
Iteration 1 - variable i = 1
Iteration 2 - variable i = 2
Iteration 3 - variable i = 3
Iteration 4 - variable i = 4
Iteration 5 - variable i = 5

Program terminates! Bye!
pi@tron ~ $


Tuesday, August 23, 2016

Lather Rinse and Repeat


When we have to repeat something boring we hate it. Computers have no problem with that. They have no emotions. And man are they fast!

Let's start with Python range() function.

Eeeh, function?!

Consider this as a name for bunch of instructions that do something useful but we do not know (or care) how it does what it does. All we care about is how to use it and what it produces. More on functions in the future.

list(range(number))
produces numbers form 0 to the last number you typed - 1.

list(range(start_number, end_number))
produces list of numbers from start_number to end_number - 1


Let's open our python interpreter in our terminal to see those in action 
pi@tron ~ $ python3
>>> numbers = list(range(1,10))
>>> print(numbers)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Wow! What just happened?!

We created a list of numbers (more on lists in the near future) and saved it under name numbers

Notice, that the range starts at 1, but ends with ... 9, not 10. Remember that.

Let's try to build another list this way:  
>>> butterflies = list(range(11))
>>> print(butterflies)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>

See how it works? This time in function range() I did not specify the beginning number this time. It started automatically with 0 and ended with the number: 11 - 1. Eleven subsequent numbers: from 0 to 10. 

Let's try another one:

>>> even = list(range(2,11,2))
>>> print(even)
[2, 4, 6, 8, 10]
>>>

Now, Python created range of numbers that start at 2, end with 11 - 1, with increments of 2!

Why this range() function is important?

Let's make our computer repeat something.
How about creating a short program that produces square of the first 20 numbers.

Open Leafpad text editor and type in the program as shown below, and save it as loop.py

Watch out for the 4 spaces following the line that ends with semicolon (:). We talked about this in my previous post. What follows semicolon is a block of statements that must always be indented with the same number of spaces (4 recommended). Here is our short program:

loop.py
print("**********************************")
print("*** Program Calculating Square ***")
print("***   of the first 20 numbers  ***")
print("**********************************")

for n in range(1, 21):
    print(n, "squared is", n * n)

And when run, here is what it does. Analyze this program and its result (don't worry if you find it difficult to understand as we are going to dissect it in our next chat).
pi@tron ~ $ python3 loop.py
**********************************
*** Program Calculating Square ***
***   of the first 20 numbers  ***
**********************************
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100
11 squared is 121
12 squared is 144
13 squared is 169
14 squared is 196
15 squared is 225
16 squared is 256
17 squared is 289
18 squared is 324
19 squared is 361
20 squared is 400
pi@tron ~ $

Did you see how quickly it did the job? And your Raspberry PI is never going to complain that it is boring!

Isn't that sweet?

Problem Solving


Write a code that calculates cube of first 20 numbers (hint: n * n * n).

Write a code that prints your name 5 times.

Write a code that does the following:
  • Ask you your name and store it in variable name
  • Then it should ask your for the number and store it in variable number.  
  • Finally, it should use the for-loop to write your name on the screen the specified number of times. 
You can add something to this line besides your name if you like it. It should work like this program below:
pi@tron ~ $ python3 loop-name.py 
What is your name?
Neila
Enter a number (not to big please!):
4
Hello Neila I am Raspberry PI and I love working with you!
Hello Neila I am Raspberry PI and I love working with you!
Hello Neila I am Raspberry PI and I love working with you!
Hello Neila I am Raspberry PI and I love working with you!
pi@tron ~ $ 
 

In our next lesson, we will analyze the loop.py program step by step in order to fully understand how it works.

Monday, August 22, 2016

What if



Think how often your mind goes like this:

"If it's sunny we're going to zipline. If it's raining we'll play Tombraider."

"If something is true then we'll do this, otherwise we'll do something else.

"If ... then ..."

Computer programs work the same way. Computers operate just like people, because it is people who created them in the first place!

So, how do we use it in Python?

Let's see what is true and what is false in computer's brain and how they can compare things.

First something that can look familiar (operators and their meaing):

== equal to
!= Not equal to
<  Less than
>  Greater than
<= Less or equal to
>= Greater or equal to

Notice, that to compare equality of two objects we use double equal sign (==). One equal sign (=) is assigning value to a variable, remember?
 

Now, enter python interpreter to have some fun with those.

pi@tron ~ $ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>&g 'python' == 'python'
True
>>> 'python' == 'Python'
False
>>> 8 < 100
True
>>> 'car' != 'bike'
True


This quality of comparing can be used in many programs. Try a simple one like shown below. Pay attention to colon at the end of if and else line (:) and indentation (4 spaces) that follow them in the next line. Write exactly this content into a leafpad and save it as if.py

print("What is your name?")
name = input()
if name == 'Natalie':
    print("Hello, Natalie! It's so good to see you again!")
else:
    print("Nice to meet you", name, "!")

In Python, if statement ends with a colon (:). The next line is so called block of code that must be indented by a number of spaces (preferred 4 spaces). Try to write it yourself (don't copy that from the screen). Run it, and see what happens. Try your name first, then run it again and try to introduce yourself as Natalie.

You can follow me along. Look below:  
club.py
pi@tron ~ $ python3 if.py
What is your name?
Jimmy
Nice to meet you Jimmy !
pi@tron ~ $ 
pi@tron ~ $ python3 if.py
What is your name?
Natalie
Hello, Natalie! It's so good to see you again!
pi@tron ~ $

And now, try to figure out what this one is going to do. I named this file above club.py

Another example below:
if-statement.py
i = 8;
if i > 8:
    print("Variable i is greater than 8.")
    print("These two print statements won't be printed!")
else:
    print("Variable i is not greater than 8.")
    print("Program ends!")

When you run the above code (if-statement.py), here's what will be printed:
pi@tron ~ $ python3 if-statement.py 
Variable i is not greater than 8.
Program ends!
pi@tron ~ $


Program checks the conditions:


i   ==   8     # true if i is equal to 8.
i   !=   8     # true if i is not equal to 8.
i   >    8     # true if i is greater than 8.
i   >    8     # true if i is less than 8.
i   <=   8     # true if i is less or equal to 8.
i   >=   8     # true if i is greater or equal to 8.

In a nutshell if the condition is true, the block of code will run
Else
We run different block of code.

Problem Solving

Type it in you the leafpad and save like mine. Then run it few times giving different age (first 9, then 14, then 19) See what happens each time!

print("*******************************")
print("*** Welcome to Python Club  ***")
print("*******************************")
print("What is your name?")
name = input()
print("How old are you?")
age = int(input())

if age < 9:
    print("We love young adventurers in our Python club!")
elif age < 16:
    print("Welcome young apprentice. You're goint to love Python!")
else:
    print("Python will be your second nature in no time!")

Write similar program about different ages allowed to see the movie in the cinema or similar to this.