Tuesday, December 24, 2019

Getting started with simple programs

Welcome Friends,

Today we are going to write some simple programs. Let's open pycharm and create a python file with name as sum.py. Our first program will add two numbers and then it will display the sum of these two numbers. 

  a = 10  
  b = 20  
  total = a + b  
  print("Sum of two numbers is: " + str(total))

now, to run this, right-click and click on "Run sum.py". It will display a message as 


Sum of two numbers is: 30


Let's take another example to add two numbers that are provided by users. To get value from user, input() function will be used. This input function will get the value as a string, so we need to convert it into an integer.

  a = input("Enter the first number: ")
  b = input("Enter the second number: ")
  total = int(a) + int(b)
  print("Sum of two numbers is: " + str(total))

if we run this we will see a message something like this:


Enter the first number: 20
Enter the second number: 15
Sum of two numbers is: 35


Now, instead of displaying "Sum of two numbers is" if we display the actual numbers in the statement, it will make more sense. Also, to convert the number from string to int, we will do this when we are getting the value from the user. Let's have a look at this now:


a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
total = a + b
print("Sum of " + str(a) + " and " + str(b) + " is: " + str(total))


Result will be
Enter the first number: 20
Enter the second number: 30
Sum of 20 and 30 is: 50

So far so good. Let's now find the largest of 2 given numbers provided by a user. For now, we will assume the two numbers will not be the same. To compare numbers we use logical operators:
  <   smaller than
  >   greater than
  <= smaller than or equal to
  >= greater than or equal to
  == equal to


a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

if a > b:
    print(str(a) + " is greater than " + str(b))
else:
    print(str(b) + " is greater than " + str(a))


Note: In python, indentation is very important. In the above example, if and else are reserved words and at the end of these lines, we have to put a colon(:). Now, let's run this

Enter the first number: 10
Enter the second number: 20
20 is greater than 10


Hope you have enjoyed programming it. In our next post, we will play around with more controls. Stay tuned.

No comments:

Post a Comment