(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:
1 2 3 4 5 6 7 |
a = 1 print a b = 2 print b # change the value of the variable a a = 3 print a |
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!)
By 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.
1 2 3 4 5 |
b = a print b a = 5 print a, b # should print 3, 5 |
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!)
1 2 3 |
a = a + 1 print a # should print 6 |
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!):
1 2 3 |
a += 1 # increments by 1 a *= 2 # multiplies by 2 a /= 3 # divides by 3 |
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:
1 2 3 4 |
# this is a single line comment ''' This is not hard to explain. But I used multiple lines. Hope you don't mind!''' |
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
Now type:
1 2 3 4 5 |
a, b = 2, 3 # yes, you can assign like this! c = b / a print c # result 1 print b % a # result 1 print c * a + b % a |
I now it is clear how the whole thing works for integer math.
So in python there are two types of numbers
- Integers: Known as type ‘int’. Type on IDLE: type(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:
- 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!)
- 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:
1 2 3 4 5 |
num1 = -2.5 # shorthand for number 1 num2 = 3 print type(num1), type(num2) print int(num1), float(num2) # >>> -2 , 3.0 |
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:
1 2 |
name = raw_input('What is your name?: ') print "my name is", name |
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:
1 2 |
age = raw_input('What is your age?: ') print "After two yours you will be", age + 2, "years old" |
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:
1 2 |
age = raw_input('What is your age?: ') print "After two yours you will be", int(age) + 2, "years old" |
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
- Take Fahrenheit as input.
- Subtract 32 and multiply with 5/9
- Finally print the result
Simple, right? Let’s try it:
1 2 3 |
fahr = raw_input('Temperature in Fahrenheit: ') cel = (fahr - 32) * 5/9 # see how we can use brackets like math print 'Temperature in degree Celcius', cel |
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
6 Comments
# 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 )
plzzz update the site… waiting for next chapters
Hi,
I am currently traveling. So will take some time. Thanks for your patience.
okk… plz udpate ASAP….. want to learn fast n more n more n more…
Please, vaia write more, please. Bangladesh
plzzzzzzzzzzzzz updateeee