# Intro to Programming with Python – #2

In my last post I started this introduction to computer programming using Python series as a quest to make a large course encompassing major portion of Deep Learning and Machine Learning. This is second post in the series and will be much more important in terms of understanding the basic syntax of python programming language. We will be going over basic program structures, basic types of data and many more things.

So lets begin! 🙂

In last post I also gave you few assignments over python and asked you to try them out. If you got lost trying to understand those assignments, I have uploaded solutions to them here.

## BASIC STRUCTURE OF ANY PROGRAM

Any useful program written in any programming language follows 3 simple rules:

1. Take the input.
2. Process the input.
3. Give back the result. That is just great. Three steps and we are done right? Well kind of! There are many subtleties hidden in these 3 steps which we will uncover in upcoming posts. But for now we can make simple python program to see this flow in action.

Have you ever been stuck on addition or multiplication or division or any other mathematical operation and searched for a calculator? My gut tells me that yes you did! Let us make a simple calculator for ourselves in this post.

What will our calculator be able to do? It will be able to take in 2 numbers and will ask which action we will like to perform – addition, subtraction, multiplication, division or to find remainder of their division, and will subsequently display result in a new line.

To go about making this calculator we will have to first understand the type of data we will be handling! How will we be handling it? How will we be taking the input? And how will we be displaying the result?

Without waiting further let’s have a look at the output of the final program. ## NAMING & IDENTIFYING THE VARIABLES!

Whenever you are given a program to code, first thing you must do is to make sure you try to know how many variables (identifiers to store value of the data you are working with) you might need and give a name to them that truly represent their usage.

Here we will need 3 variables – two for the two numbers which we perform action on and third for the choice we will make (addition/subtraction/multiplication/division/remainder). We can neglect the output variable as we can just print the operation’s output directly, as we will see ahead.

So I named first as my first input number second as my second input number and choice as the menu option number for choice of operation.

The second step will be to understand the type of data that you are expected to get. Before going into this step we first need to understand the data types available to us by Python Programming language.

## DATA TYPES IN PYTHON

Every Programming language you will ever encounter will have their set of rules and data types. Data types define the type of data we can get, work on and output in a programming language. Like any other language python has its own set of data types. But python is special from many static languages like Java or C++, as in case of Python we can dynamically change the type of data stored in a variable without causing any errors.

Data Types In Python
Data Type Meaning Immutable?
bool Boolean Values (True/False) remember 'T' in True and 'F' in False is capital.
int Integer Values of arbitary magnitude
float Decimal values (floating point numbers)
list Sequence of heterogenous (dissimilar) objects
tuple Sequence of heterogenous (dissimilar) objects
str Combination of one of more characters
set unordered set of distinct objects
frozenset immutable form of set
dict associative mapping; mapping one value to other value or values; aka dictionary

Immutable data types are those which cannot be changed after values are assigned to them. Say, we give a value 10 to a variable a, and since 10 is an integer so a is a variable to type integer. We know from above table that integers in python are immutable this means that when we do something like adding 5 to a and saving the value again in a – denoted by the operation a = a + 5, we are essentially making a new value 15 somewhere in memory and asking a to now store that value and forget about 10. We are not changing the value 10 to 15, we are creating a new value in memory.

For those who know about object oriented programming from other programming languages. Data types here are built-in classes and this concept will be discussed in future posts. If you don’t get this line don’t worry we will discuss it in futures posts.

Q. Which data types will we be using?

A. If we look closely we have 9 data types and we will be using 4 of those in our simple calci program (either implicitly or explicitly) – int, float, str and bool. Let us try and understand how we will be using these 4 data types.

Q. Why str?

A. Input in python from cmd or terminal is taken using input() function (Where a function is a program in itself. So it will take something from us do some processing and returning something to us). The syntax of using input() function is as follows. Suppose we want to take a number input from user of program by prompting to the user that ‘Enter a number: ‘ and saving the value to a variable a. We write this as: `a = input(‘Enter a number: ‘)` and result is something as shown below. But there is a catch here – input() function return a str value not an integer value. Same is also proven by the single quotes over the value of a in the image. Q. Why float?

A. As part of simple calculator we need to calculate values on floating points so as to make it a calculator which is not limited to integers alone. To achieve this we convert input from the input() function into float by using another function written as float(). It takes in a string and returns a float if the string is a valid number else it causes a program error. Basic syntax we will be using here will be: `first = float(input(‘Enter first number: ‘))`.

Q. Why int?

A. Choice options available to us are simple integers from 1 to 5. So it is natural to take input of choice and convert it to int using another function int(), which takes string as input and converts it to an integer if string contains a valid integer else it causes a program error.

Q. Why bool?

A. To make a decision on what type of operation to perform we require to have a knowledge of whether the choice is equal to 1 or 2 or … 5 or none. This means we need to have a way to make logical decision based on the choice of the user. Thus we will be comparing choice to 1 if it is True we will perform addition and so on.

Now that we have enough knowledge about our data types and how we take input in python we are ready with enough knowledge to complete first part of the program structure – Taking input. In your text editor open up a file and write the code to take input first number, take input second number, print menu and take input choice option, and save file as simple_calci.py. Before looking at code try it yourself.

```first = float(input('Enter first number: '))
second = float(input('Enter second number: '))

print('2. Subtraction')
print('3. Multiplication')
print('4. Division')
print('5. Remainder')
print('----------------')

```

After saving the file. Try to run it and see if you get similar results: ## MAKING LOGICAL DECISIONS

In this program, we have 6 logical decisions each linked to one variable. If the value of `choice` is 1 then we do addition, if the value of `choice` is 2 then we do subtraction…if the value of `choice` is other than 1 to 5, we display ‘Not a right choice!’. But either way, the value of `choice` can be one out of 6 possible values. For instance, you are giving same instructions to a person in English. You will frame your sentences in such a manner.

1. Take two numbers from user.
3. If the choice is 1 add the two numbers else If the choice is 2 subtract the two numbers else if the choice is 3 multiply the two numbers … else tell user that his choice is not a right one.

Python gives us similar construct (called if-elif ladder) to follow and achieve logical operations in programs. In this case, we are checking if `choice` is equal to a value or not so we will be using == (equality operator).

General syntax of if-elif ladder is as shown:

```if <condition>:
<do something>
...
elif <condition>:
<do something>
...
...
elif <condition>:
<do something>
...
...
...
<as many elif as needed>
else:
<do something>
...
```

How does this work? Our program executes from top to bottom and from left to right. As soon as it reaches the first `if <condition>` python checks if the condition is True or False. If the condition is True then the code indented to right, below the `if <condition>`, is executed and then it jumps outside this construct and no other condition is checked. Otherwise, it moves forward till a condition is met and executes code indented to right below that condition. If none of the conditions are met then python executes code indented below `else`. SOME IMPORTANT POINTS:

1. We replace `<condition>` with some conditional statement like `choice == 1`. We replace `<do something>` and `` with code blocks like `print(first + second)`.
2.  Have a special look at the syntax here!!! Code that has to be executed for a particular if or elif condition is indented to right by a tab or by some spaces (generally 4 spaces). As soon as we indent back to left we mark the end of that code block. Remember to use either tab or spaces you cannot use both.
3. You can use `if-else` if you only have a condition of do this if True else do this. You can also use `if`, if you feel like you need to perform an extra operation when something is true.

### LAST PIECE OF PUZZLE

Now that we have learnt a little bit about if-elif ladder, let’s code the missing logic of our program. The entire hint to do it is present in the if-elif section!! Try to do it yourself before jumping to my code. 🙂

```if choice == 1:
print(first + second)
elif choice == 2:
print(first - second)
elif choice == 3:
print(first * second)
elif choice == 4:
print(first / second)
elif choice == 5:
print(first % second)
else:
print('Not a right choice')
```

Save and run `simple_calci.py` and bullseye you have your simple calculator up and running!! 🙂

### COMPLETE CODE

```first = float(input('Enter first number: '))
second = float(input('Enter second number: '))

print('2. Subtraction')
print('3. Multiplication')
print('4. Division')
print('5. Remainder')
print('----------------')

if choice == 1:
print(first + second)
elif choice == 2:
print(first - second)
elif choice == 3:
print(first * second)
elif choice == 4:
print(first / second)
elif choice == 5:
print(first % second)
else:
print('Not a right choice')
```

This brings us to the end of this post. In the next post we will be going over more powerful coding concepts and will be building much better things. 🙂

Till then dirty your hands with these assignments:

1. Take input an year and print whether it is a leap year or not. Leap Year – years which are multiples of four (with the exception of years divisible by 100 but not by 400).
2. Take input a number and display whether it is even or odd.

## Links to Some Useful Python Books

### This Post Has 4 Comments

1. Wow it’s great !! 😎

1. Thanks Rahul. 🙂 SUBSCRIBE FOR WEEKLY POST UPDATES <3