Play with Python (Part 3): Magic Starts with Variables

(After the previous part: Part 2: Preparing for the Magic)

Summary: Learn about variables, types in python, type changing, input methods, and how to impress friends!

Variables:

Now you can open code in a fancy text editor like a real programmer and show your friends the nicely color coded texts. But how do we to write programs with more than one lines? For that we need to learn the concept of variables.

A variable is nothing but a fancy, geeky name for a box with a label. You can put values (and/or objects) in it and label it by a variable name. It is a good way to keep track of all the numbers you are going to use in a program. These things are called variables because you can vary (change) them anytime. Before I bore you, let’s type up some real examples in IDLE:

Now these a, b each are called a variable. Now with that assignment what computer has done is that is has created two boxes (with labels a, b) in its memory. Then it put the numbers in the box. (One great thing about python, you don’t need to tell the computer about the size of your box. Python is so smart that it can figure out itself!)

3-var-boxBy the way, in python you can write variables with a mix of letters, numbers, and underscore, but no spaces (i.e. num_3 is a valid variable name, but num 3 is not); so they don’t necessarily have to be just one letter. In fact, in future we will try to write meaningful variable names so that the code is easy to read and understand.

Now let’s see what happens when you assign variables to another variable.

So you can see how python copied the value of another variable to b. Then after you changed a, b had the old value of a. (Oh and you can print variables separating with comma. It even adds a space. How nice of python!)

Changing is the value of one variable using the value of itself is a very powerful idea. We will use it so much that python has a shortcut for it! Try (also might want to use print to see values, if you are using text editors!):

More on Commenting:

You already know that we can write one line of comment with a hashtag sign and python ignores when it runs the code. But what if we want to write multiline comments? There is a way too! For that you need to put all the contents within a pair of three quotation marks.

For examples:

Integers and Floats (Data Types):

In IDLE command prompt just type  3 / 2  and see what you get! You get 1, but it should be 1.5, right? What is wrong?
It turns out that because both 3, 2 are integers, when you ask Python to divide it does integer division. So the result is just the quotient (and of course the remainder is 1). If you know some arithmetic then you probably learned at some point that

3-division

Now type:

I now it is clear how the whole thing works for integer math.

So in python there are two types of numbers

  1. Integers: Known as type ‘int’. Type on IDLE: type(2)
  2. Floats: Floating points. The type of numbers are decimal number with ‘points’. For example: 2.0 is a float. Type: type(2.0)

(There is another called ‘long’ type, but it is not really important unless you are working with really large numbers.)

While there are many good reasons why python (and most other languages) does integer division, you can see that the result can make our calculations wrong (for example if it is a bank, it just did not calculate a dollar when dividing–the numbers surely add up!). So the way to do it correctly is to make sure when dividing at least one of the numbers are ‘float’. We can do it in two ways:

  1. Type them as float: Set both a = 2.0 , b = 3.0 or at least one of them with that .0.  (Try all the combinations yourself!)
  2. Or change them to float using float() function: try using  a = float(a) .

The second way is the standard way to do it for long programs because it has hard to make sure that everything we entered are floats. This method also brings us to data-type changing also known as typecasting. So you can interchange between int and float using int(), float() functions. Try:

 Screen input and output:

We have already learned how to output something to screen with  print  function, but you may ask how to enter data to a program. This is done by  raw_input()  function. This is the way the function works:

raw_input('optional: The text you want to show')

Now try:

So the raw input function shows the query text and gives a text object (in fact it is called a string and we will learn about it in the next part).

Now try:

 

Oops! Something is wrong. Python should show '''TypeError: cannot concatenate 'str' and 'int' objects'''. So you made a mistake. This is called a bug. When you are trying to do programming you will see a lot of these, try reading the messages and checking the line number to see where problems and fix those bugs! So here the problem seems to be that python cannot add str and int data objects. The problem is the age value you got is a text string (‘str’ object) and python does not know that it is integer. So you need to change it to integer. Now try:

Fantastic! Now that you know how to enter something to a program, let’s do something that could be useful in real life. This is getting exciting!

Real world application: Temperature Converter:

Assume you have a British friend (with ‘niec ack’cent, of cou’se’!) and you are American. They are big on weather and you want to impress him by talking to him about temperature in degree Celsius instead of Fahrenheit. But it takes a quite a bit of effort to calculate that every time. But now you know how to program. So you can just ask your computer to do it every time!

But before that you need to solve the problem and give it an algorithm (oh, fancy!).

The equation for turning Celsius to Fahrenheit is °C = (°F  -  32)  x  5/9

So basically the algorithm should be

  1. Take Fahrenheit as input.
  2. Subtract 32 and multiply with 5/9
  3. Finally print the result

Simple, right? Let’s try it:

Oops! You see a type error. Remember how we fixed it the last time (hint: typecasting)? Nice!

But still the problem is you will always get 0. What is wrong? The issue is that when you 5/9, python does integer division and gives 0. So the whole thing becomes 0! As explained earlier, you can fix in two ways, but the easiest is changing to

cel = (fahr - 32) * 5.0 / 9.0

Awesome! Now you know how to impress your friends with your coding skills!

Exercise: You need to know the volume of a sphere. You know from math that the answer is  . Write a program like the previous one which asks for radius and gives you the volume.

(Hint: Remember to typecast that 4/3 part!)

Happy coding!

Previous Part: Part 2: Preparing for the Magic

Next Part: Coming…

All parts: Play with Python

This entry was posted in Education, English, Python.

6 Comments

  1. Rafat January 10, 2014 at 5:07 am #

    # Volume Of A Sphere
    radius=float(input(“Enter The Radius Of The Sphere : “))
    volume=( 4.0 / 3.0 ) * ( radius ** 3 ) * ( 3.1416)
    print(“Volume Of The Sphere is : “, volume )

  2. coder January 16, 2014 at 10:36 am #

    plzzz update the site… waiting for next chapters

    • Tarik Adnan Moon January 17, 2014 at 10:22 pm #

      Hi,
      I am currently traveling. So will take some time. Thanks for your patience.

      • coder January 19, 2014 at 2:03 pm #

        okk… plz udpate ASAP….. want to learn fast n more n more n more…

  3. M.d.AbuHasan August 4, 2014 at 8:01 am #

    Please, vaia write more, please. Bangladesh

  4. coder December 1, 2014 at 4:41 pm #

    plzzzzzzzzzzzzz updateeee

Post a Reply to coder

Your email is never published nor shared. Required fields are marked *

*
*