Tutorial/Lesson 1

From HandWiki

Lesson 1. Variables and Numbers

Let us start. First, you should run DataMelt, which will look as a simple text editor.

It should be said that even this editor runs inside Java. Now we will write a file where we will put a simple programming code that will be run by Java. Simple go to the menu "File" (upper part) and then select "Save as" and replace "Undefined" by the file name "example.py". Then click save.

Now you see that you can edit a new file "example.py". The last ".py" tells Java that we will a code using the Python language.

So, lets write our first code:

bag=1

and do not forget to save it ("File-Save"). This is what is call a "code". "Bag" is an "object" that keeps number one. You can replace 1 with any other number. And "bag" can be any word! You can also type:

dog=2


The important thing that the work on the left takes the value from the script. Then you can forget about the values and use "bag" and "dog" as if they were numbers. We can add them together:

bag=1
dog=2
sum=bag+dog

as you can imagine, "sum" is 3.

How do we know this? We can print it on the screen. Add these lines to the file

bug=1
dog=2
sum=bag+dog
print sum

and then save it. Then let Java to apply it by clinking the green running man from the toolbar. The program will print "3" at the bottom.

So, "sum" is a "bucket" that keeps the result of our calculations. We call it "variable". In our example, "bug", "dog" and "sum" are variables. During the completion of the last script, the statement "bug + dog" are replaced by the actual Values "1 + 2" and the result becomes 3. Numbers on the right are "values". This is how the whole thing looks like:

Dmelt1.png?

What is important? You can always change the numbers on the right and rerun the code. It will generate different answer.


Elementary math

We used "+" to add variables that keeps numbers. You can also subtract ("-) multiply ("*") and divide numbers. Here is an extension of the example above:

bug=1
dog=2
ans=bug+dog*doc-2
print ans

Here we have a new variable "ans" that simply means "1+2*2-2". The answer is "3". You can also see that we mix variables and the actual numbers.

In Python you have the following arithmetic operators:

Symbol Name
+
Addition
-
Subtraction
*
Multiplication
/
Division
''
Floor division
%
Modulo
'''
Power

Now, let's try to use Python as a calculator. We will calculate $3*8/6$:

print 3*8/6

Here are a few more examples:

a=10; b=3;
print a/b
print a*b
print a'''b # power
print a%b  # find the reminder of the division