Monday, 9 January 2017

How to Sum two numbers in python


Why Learn Python


print 'hello world!'

Yes, that's all it takes to write your first program in python. True, it is a simple yet powerful language. All those things which you did with batch files, cmdlets, shell scripts, perl scripts can be done in python in a easy way.  And a lot more! Not only scripting, its already proved itself as a server side development language for websites. eg. Big part of Instagram(Django), Quora(Pylons) like sites are written in python. It has already become a hot language for Data science and analysis as it has good modules like scipy\ Pandas etc. And, a heaven for machine learning beginners. It's good to learn python in 2017. It will be there in 2018 and many years to come. So, Happy learning.


Objectives
This is the first Post. I will keep it simple. After reading this post, you should be able to create a very basic python script which takes two numbers and displays their sum.


Code

print 'Enter the first number'
num1 = input()

print 'Enter the second number'
num2 = input()

sum = int(num1) + int(num2)

print 'Sum is {0}'.format(sum)

Open SubLimeText or NotePad++ editor and Save this little code as first.py( any filename).

Then, go to the folder containing the file. Open console and type-
python first.py

This will execute your program. It will ask for two numbers and show the sum.

What have you learned here?

a) Printing a text on screen.
b) Taking input from user using input().
c) Converting a string to a number using int().
d) Showing the formatted output using format().

 Same program can be written in one line as well( You will find people doing this in many places so..)



print 'sum is {0}'.format(int(input('Enter the first number')) + int(input('Enter the second number')))

No comments:

Post a Comment