Programming Basics

Variables and data types in python

In our last article, we wrote our first program but it was very limited.

Now everyone knows that you are learning python, so your neighbour bakery needs your help with programming a billing system for their bakery.

Here are requirements from the bakery chef-

  • The program prompts the salesman to enter the customer name and greets the user with a hello message
  • The program prompts the salesman to enter the total products taken.
  • Calculate total bill for total numbers of products bought (To keep things simple, the bakery has decided to keep each product 5 Rs. each) and show the final bill amount.

Do you think you can make this program?

In this chapter we will dive deeper in Python basics and learn concepts like user inputs, variables and datatypes to help the chef.

Input function

To prompt user for input python has inbuilt function ‘input()’.

Wondering what a function is?

Function may sound like something from your math class, but for now you can think of it as just a way to call upon built-in functionality provided by Python.

Here is code snippet to use input() function to get user input.

input("Hey! What is your name? ")

Input function looks very similar to print function. Right?

First run print function and check that how your terminal responded?

Now run your input() function code snippet on console.

Do you see any difference ?

Check image no 2, on console interpreter prints the message and there is an arrow symbol on the next line. This means that the program has executed and execution completed.

But in image 3, the interpreter prints a message on the screen but that orange arrow symbol is not printed on the next line. This means that the program has not terminated yet and is waiting for something. In this case, the program is waiting for the user to input something. So let’s just enter the value and hit enter.

When I entered input and hit ‘enter’ key, program has terminated, as you can see orange icon on the next line.

Do you know whats happening in the background?

  • When you run your program and the python interpreter sees that you are using the input() function, it takes your prompt text(String value between parentheses) and displays it for the user in the Python Shell.
  • Now interpreter then waits for the user to type in a response, which the user completes by entering text and pressing the Return key.
  • So whatever was typed by the user, will be passed to your program now.

Variables

We use variables when we want computer to remember something while our program is running.

Variables is like a ‘bucket’ to store data. They’re used to store data for safe keeping.

The easiest way to think about variable is a placeholder in memory.

So when you define a variable, Computer will allocate some space for data to be stored and used.

Now when next time you are ask it for variable you defined, it knows exactly, that from where it should look for the values.

This is how you use variable in python

count = 1;

You’ve just defined the variable “count” to be a variable that holds the number 1,

Of course, you can change variables, so if you later wrote:

count = 10;

So now if you ask computer for variable ‘count’, it will give you value 10.

Let’s write a program to test how variables work.

count = 1
print(count)

count = 2
print("count")

count = "None"
print(count)

In above example I have used count variable and reassigned it twice later. Each time its value was changed, and program last assigned value on the console for variable.

Rules for Using Variables

When you’re using variables in Python, you need to adhere to a few rules and guidelines.

  • Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number.
  • Spaces are not allowed in variable names, but underscores can be used to separate words in variable names
  • Do not use predefined Python keywords and function names as variable names
  • User short but descriptive variable names

Giving variables descriptive names makes it easier to understand what a program does. Imagine if you were moving to a new house and you labeled every moving box “Stuff”. That wouldn’t be helpful at all!

Now let’s change our ‘hello python’ program to use variables.

message = "hello python!"
print(message)

Program will print ‘hello python!’ on the console.

Now check the following code snippet

message = "hello python!"
print(massage)  

Do you find anything with above code?

Run the program and you will get an error on console.

Compiler is telling the user that ‘massage’ is not defined. Now in this I have willingly mistyped variable name.

In line 1 we have defined variable ‘message’ but on 2 lines we use ‘massage’. So because of our type, python can not understand it and throws an error on the console.

Now that you understand variable. We will use a variable to capture user input

name  = input("What is your name?")
print("Hello "+name)

DataTypes in Python

So with ‘variables’ we can store some data and can use it later in the program. We can store different kinds of data types and different types can do different things.

so let’s just see what data types we have in python.

Strings

A string is simply a series of characters. We can use single quotes or double quotes to represent strings.

So anything inside single or double quotes will be considered as string by python.

Here is an example for using strings.

s = "This is an example of String"
print(s)

s = 'Example for String with single quotes'
print(s)

For string concatenation we can use plus symbol(+).

So if you need to combine two strings, you can use + operator to combine them.

So if you have two variables having values for ‘First name’ and ‘Last Name’. We can get full name by adding these two strings.

firstName = "Sachin"
lastName = "Tendulkar"
print(firstName+lastName)

Now if you this program. This will print ‘SachinTendulkar’ on console. But how do we add a space between both strings?

Lets just append a string with space in it. So lets just add a space by appending ” ” in between.

firstName = "Sachin"
lastName = "Tendulkar"
print(firstName+" "+lastName)

And we will get required output ‘Sachin Tendulkar’ on console.

In Python, the numeric data type represents the data that has a numeric value. A numeric value can be integer, floating number, or even complex numbers. These values are defined as intfloat and complex class in Python.

Now you know about using Strings in your python programs. But what about using numbers in Python?

Numbers are used quite often in programming to keep score in games, represent visualisation data , store information for different users and so on.

So now you know how to use strings. But what about numbers?

So lets understand Numeric types.

Integers

This value is represented by int class. It contains positive or negative whole numbers (without fraction or decimal). In Python there is no limit to how long an integer value can be.

Python interprets a sequence of decimal digits without any prefix to be a decimal number.

You can add (+), subtract (-), multiply (*), and divide (/) integers in Python.

print(5 + 3) #addition
print(5 - 2) #subtraction 
print(5 * 3) #multiplication
print(5 / 3) #division
print(5**3) # 5*5*5

Float

Any number with a decimal point a float. This term ‘floar’ refers to the fact that a decimal point can appear at any position in a number.

It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.

Operators work kind of same as they did for integers. But understand a thing, that handling floating points is difficult for computers. So most of the time python will give precise outputs for operators but few times you can see some extra digits after few decimal points.

We will cover this in detail in later articles and will link these articles here.

Boolean Types

The Boolean data type is a simple one; it has only two values, they are True and False.

Unlike numbers and strings, Booleans are named after a person, George Boole, a 19th-century mathematician who formalized much of the logic we use with computers today

You can treat Booleans like any other type in that you can store them in a variable, print them, or use them in expressions.

Booleans are generally used with conditional expressions. In conditional expression, we use conditional operators to test a condition and on basis of that, we decide the flow for the program.

Complex Numbers –

Complex number is represented by complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j

Those are just the basics of types. We have a lot more types in Python:

  • complex for complex numbers
  • bool for booleans
  • list for lists
  • tuple for tuples
  • range for ranges
  • dict for dictionaries
  • set for sets

We will get into details of these datatypes as we progress

So now we know how to handle numbers. Great!

So you now understand about basic python data types and user input. So lets help our neighberhood chef with his billing system.

Lets first implement chef’s billing requirements in python program.

name = input("Hello! Please enter your name ")
print("Welcome "+name+"! \\n")

totalProducts = input("Please enter total product purchased ")

billingAmount = totalProducts*5
print("Your total is billamount is "+billingAmount)

Everything makes sense? Right?

So let’s run the program and check the output.

User entered 10 and each product is 5rs, so total bill amount should be 50rs.

But output is 1010101010. It seems super wrong,can you find issue with the program?

We multiplied user input value for no. of products with price per unit. Per result is something what we not expected. If you look output again it ’10 10 10 10 10′ 10 repeated 5 times, this is somehthing which * operator does with string.

So is it possible that python took totalProducts variable value as string?

How do we confirm type of this variable?

Python has a inbuilt function ‘type‘ to check type of an object. So lets just learn about it and get back to program.

type function

If you are working with a variable in a program, and you are not sure that what type of variable is that?

There are two built-in pythons functions that help you identify the type of an object. You can use type() if you need the exact type of an object, and isinstance() to check an object’s type against something.

type() method returns class type of the argument(object) passed as parameter.

In the following code snippet I have taken 4 variables of different types.

Lets use type() operator to find out their types.

name = "Abhijeet"
age = 30
ageString = "30"
ifStudent = False

print(type(name))
print(type(age))
print(type(ageString))
print(type(ifStudent))

First is a string, second is an integer type, 3rd variable is a string(as number 30 is inside double quotes) and 4th variable is of boolean type.

So lets check type of variable totalProducts using type operator.

So python terminal takes input from terminal as String. But we want it in numeric format to do apply mathematic operations on it.

So how do we change one data type to other datatype in python. Answer is ‘Typecasting’.

Type casting or type Conversion

Type casting is the mechanism of forcing an object into a particular type.

The process of converting one data type to another data type is called Typecasting or Type Conversion.

Python has two types of type conversion.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python interpreter automatically converts one data type to another data type internally and there is no need of user intervention.

Let’s add two Python variables of two different data types and check resulting variable type.

a = 10
b = 23.5
sum = a + b
print (sum)
print(type(a))
print(type(b))
print (type (sum))

And here is the output. Which you will get on running this program

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of the item to needed data type.

We use the predefined roles such as int(), float(), str(), etc to execute explicit type conversion.

We use predefined in-built functions like:

  1. int()
  2. float()
  3. complex()
  4. bool()
  5. str()

For example:

#cast to int
print(int(123.654))
print(int(False))
print(int("10"))
print("\\n")

#cast to Float
print(float(2))
print(float(30.0))
print(float("20"))
print("\\n")

#cast to Float
print(str(2))
print(str(30.0))
print(str("20"))

So now we understand typecasting. So lets just correct our billing system program and delver it to chef.

name = input("Hello! Please enter your name ")
print("Welcome "+name+"! \\n")
totalProducts = input("Please enter total product purchased ")
billingAmount = int(totalProducts)*5 #typecasted string type to int type

print("Your total billamount is "+str(billingAmount)) #typecasted billingAmount to string, So we concatenate it with string message

Lets just check what output we get from the program.

Everything looks perfect as per requirement of the chef. So lets just deliver program to the chef.

It was great knowing about variables, data types and typecasting. Right?

But remember, clients keep coming with modifications in projects. So chef might get back with more difficult topics soon.

So keep learning with us.

In next chapter chef would be back with few changes and we will dive deeper in python and lean about loops and control flows.

Leave a Reply

Your email address will not be published. Required fields are marked *

Worth reading...
Introduction to Programming in Python