Variables, data types and operators - Python Programming Made Easy (2016)

Python Programming Made Easy (2016)

Chapter 2: Variables, data types and operators

Variables are reserved memory locations to store values. A variable has a name, a type and a value.

In languages like C, C++ or Java we need to explicitly declare variables Python variables need not be explicitly declared. The declaration happens automatically when we assign a value to a variable.

Ex:

Name = “India” # A string

(Name value Type)

We can assign multiple values to multiple variables in a single statement.

a,b,c = 1, 2.0 , “Hello”

Example 2.1: What are the values of x and y after the code is executed.

x=3

y=4

z=x+y

z=z+1

x=y

y=5

print x, y,z

After these four lines of code are executed, x is 4, y is 5 and z is 8.

1. x starts with the value 3 and y starts with the value 4.
2. In line 3, a variable z is created to equal x+y, which is 7.
3. Then the value of z is changed to equal one more than it currently equals, changing it from 7 to 8.

4. Next, x is changed to the current value of y, which is 4.

5. Finally, y is changed to 5. Note that this does not affect x.
6. So at the end, x is 4, y is 5, and z is 8.
Rules for naming variables

1. Variable names can contain a-z, A-Z , 0-9 and ‘_’(underscore)

2. Variable name should not begin with a digit

3. It should not be a keyword

4. It can be of any length

5. Variable names cannot contain spaces.

6. Case matters—for instance, temp and Temp are different.

Example 2.2: Which of the following variable names are invalid? Justify.

a) try b) 123Hello c )abc@d d)sum

Ans:

a) try – It’s a keyword and can’t be used as a variable name

b) 123Hello – Variable names can’t start with a digit

c) abc@d – Special characters aren’t allowed in variable names.

A mutable object exhibits time-varying behavior. Changes to a mutable object are visible through all names bound to it. Ex: lists

An immutable object does not exhibit time-varying behavior. The value of immutable objects cannot be modified after they are created. They can be used to compute the values of new objects. Ex: strings, tuples

Keywords

Fig 2.1: Python keyword list

Data types

Data type is a set of values and the allowable operations on those values. Python has a great set of useful data types. Python's data types are built in the core of the language. They are easy to use and straightforward.

Fig 2.2:Python Datatypes

Ø Numbers can be either integers or floating point numbers.

Ø A sequence is an ordered collection of items, indexed by integers starting from 0. Sequences can be grouped into strings, tuples and lists.

o Strings are lines of text that can contain any characters. They can be declared with single or double quotes.

o Lists are used to group other data. They are similar to arrays.

o A tuple consists of a number of values separated by commas.

Ø A set is an unordered collection with no duplicate items.

Ø A dictionary is an unordered set of key:value pairs where the keys are unique

Data type conversions

There are several built-in functions to perform conversions from one type to another.

Function

Description

int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

float(x)

Converts x to a floating-point number.

complex(real [,imag])

Creates a complex number.

str(x)

Converts object x to a string representation.

repr(x)

Converts object x to an expression string.

eval(str)

Evaluates a string and returns an object.

tuple(s)

Converts s to a tuple.

list(s)

Converts s to a list.

set(s)

Converts s to a set.

dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.

frozenset(s)

Converts s to a frozen set.

chr(x)

Converts an integer to a character.

unichr(x)

Converts an integer to a Unicode character.

ord(x)

Converts a single character to its integer value.

hex(x)

Converts an integer to a hexadecimal string.

oct(x)

Converts an integer to an octal string.

Table 2.1: Python Data conversion functions

Example 2.3: Program that computes the average of two numbers that the user enters.

num1 = int(raw_input ('Enter the first number :'))

num2 = int (raw_input ('Enter the second number : '))

print ('The average of the numbers you entered is ', (num1+num2)/2)

For this program we need to get two numbers from the user. We get the numbers one at a time and give each number its own name. All multiplications and divisions are performed before any additions and subtractions, so we have to use parentheses to get Python to do the addition first.

Operators

Operators are special symbols which perform some computation. Operators and operands form an expression.

Python operators can be classified as given below.

Fig 2.3: Python operator types

Let’s explore each of these operators in detail

Arithmetic Operators

Arithmetic operators help us to perform various arithmetic calculations. The arithmetic operators are explained in the table below. Let’s assume value of a=2 and b=3

Operator

Description

Example

+

Addition - Adds values on either side of the operator

a + b results in 5

-

Subtraction - Subtracts right hand operand from left hand operand

a –b results in -1

*

Multiplication - Multiplies values on either side of the operator

a * b results in 6

/

Division - Divides left hand operand by right hand operand

a/b results in 0

%

Modulus - Divides left hand operand by right hand operand and returns remainder

a %b results in 2

**

Exponent - Performs exponential (power) calculation on operators

a**b results in 8

//

Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed.

11//2 results in 5

11.0//2.0 results in 5.0

Table 2.2: Python arithmetic operators

Relational/Comparison Operators

These operators help us to make decisions based on certain conditions.

Operator

Description

Example

= =

Checks if the value of two operands are equal or not, if yes then condition becomes true.

(a == b) is not true.

!=

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(a != b) is true.

< >

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

(a <> b) is true. This is similar to != operator.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(a > b) is not true.

<

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(a < b) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(a >= b) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(a <= b) is true.

Table 2.3: Python relational operators

Assignment Operators

These operators assign the right side value to the left side variable.

Operator

Description

Example

=

Simple assignment operator, Assigns values from right side operands to left side operand

c = a + b will assign the value of a + b into c

+=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

c += a is equivalent to c = c + a

-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

c -= a is equivalent to

c = c – a

*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

c *= a is equivalent to c = c * a

/=

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

c /= a is equivalent to c = c / a

%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

c %= a is equivalent to c = c % a

**=

Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand

c **= a is equivalent to c = c ** a

//=

Floor Division AND assigns a value, Performs floor division on operators and assign value to the left operand

c //= a is equivalent to c = c // a

Table 2.4: Python assignment operators

Bitwise operators

Bitwise operator works on bits and perform bit by bit operation. Assume if a = 65; and b = 12; Now in binary format they will be as follows:

a = 0100 0001

b = 0000 1100

a&b = 0000 0000

a|b =0100 1101

a^b = 0100 1101

~a = 1011 1110

Table 2.5: Bitwise operations

The table below lists the bitwise operators in Python. Let’s assume a=65 and b=12 for this example.

Operator

Description

Example

&

Binary AND Operator copies a bit to the result if it exists in both operands.

(a & b) results in 0 (0000 0000 )

|

Binary OR Operator copies a bit if it exists in either operand.

(a | b) results in 77 which is 1001101

^

Binary XOR Operator copies the bit if it is set in one operand but not both.

(a ^ b) results in 77 which is 1001101

~

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~a ) results in -66 which is 10111110.

<<

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

a << 2 results in 260 which is 100000100

>>

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

a >> 2 results in 16 which is 10000

Table 2.6: Python bitwise operators

Logical Operators

There are following logical operators supported by Python language.

Operator

Description

Example

and

Logical AND operator. If both the operands are true then then condition becomes true.

a=5 b=10

(a and b) is true.

or

Logical OR Operator. If any of the two operands are non zero then then condition becomes true.

(a or b) is true.

not

Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

not(a) is false.

Table 2.7: Python logical operators

Membership Operators

Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators explained below:

Operator

Description

Example

In

Evaluates to true if it finds a variable in the specified sequence and false otherwise.

Y = []

If x in y:

return 1 if x is a member of sequence y.

not in

Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

Y = []

If x not in y:

here not in results in a 1 if x is not a member of sequence y.

Table 2.8: Python membership operators

Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators explained below:

Operator

Description

Example

Is

Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.

x is y, here is results in 1 if id(x) equals id(y).

is not

Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.

x is not y, here is not results in 1 if id(x) is not equal to id(y).

Table 2.9: Python identity operators

Operator precedence

The following table lists all operators from highest precedence to lowest.

Operator

Description

**

Exponentiation (raise to the power)

~ + -

Complement, unary plus and minus (method names for the last two are +@ and -@)

* / % //

Multiply, divide, modulo and floor division

+ -

Addition and subtraction

>> <<

Right and left bitwise shift

&

Bitwise 'AND'

^ |

Bitwise exclusive `OR' and regular `OR'

<= < > >=

Comparison operators

<> == !=

Equality operators

= %= /= //= -= += *= **=

Assignment operators

is , is not

Identity operators

in not in

Membership operators

not or and

Logical operators

Table 2.10: Operator precedence

Example 2.4: The following example illustrates operator precedence in Python.

a = 1

b = 2

c = 3

d = 4

e = 0

e = (a + b) * c / d #( 3 * 3 / 4) = 9/4

print "Value of (a + b) * c / d is ", e

f = ((a + b) * c) / d # ( 3 * 3 ) / 4 = 9/4

print "Value of ((a + b) * c) / d is ", f

g = (a + b) * (c / d); # (3) * (3/4) = 0

print "Value of (a + b) * (c / d) is ", g

h = a + (b * c) / d; # 1 + (2*3) / 4 = 1 + 6/4 = 10/4

print "Value of a + (b * c) / d is ", h

Input and output

Python takes the data entered by the user using 2 functions

è raw_input(): raw_input( [prompt])

è input(): input([prompt])

raw_input()

The function takes exactly what is typed from keyboard, converts it to string and stores it in the variable.

>>> x = raw_input("Enter your name")

Enter your name

If we need to get numeric values from the user, we need to use int().

>>> y = int(raw_input("Enter the roll no."))

Enter the roll no

The function int() converts the string to integer.

input()

input() evaluates the input typed at the prompt and it expects a valid python expression. If the input provided isn’t correct then either a syntax error or exception is raised by Python.

print()

print() communicates the program’s result to the end user. It evaluates the expression before printing it on the monitor.

print() moves to the next line after printing one statement.

>>> print 4+6

10

To print in the same line we can use comma’s

print "I",

print "Love",

print "Python"

Fig 2.4: print()

Comments

Program notes which explain the purpose of a program are known as comments. In Python, comments can be

è single line : starts with “#”

# calculate simple interest

è multi line: starts with ‘’’’’’

“”” calculate simple interest

Using formula (pnr)/100 “””

Solved Questions

1. Write a program to get the side of a square from the user and print its area.

Ans:

side = int(raw_input("Enter the side of a square"))

area = side * side

print "Area of square =",area

2. Write a program to calculate simple interest.

Ans:

principal = float(raw_input("Enter the principal amount"))

years = float(raw_input("Enter the no. of years"))

rate = float(raw_input("Enter rate of interest"))

si = (principal * years * rate) / 100

print "Simple Interest=",si

3. The following program is not giving the intended output. Input given is 4 and the expected output is 16. Find the error.

N = raw_input(“Enter number”)

S = N * N

print S

Ans:

The number is treated as a string. So, if we convert it to integer we will get the desired output.

N = int (raw_input(“Enter number”))

Practice Problems

1. Write a code that asks two people for their names; stores the names in variables called name1 and name2; says hello to both of them.

2. Write a program to get a temperature in Celcius and convert it into Farenheit using the formula F = C * 9/5 + 32.

3. Predict the output

a) print 4 * 5 + 9 * 2 – 8%3 + 9

b) print 8.7 //2 – 1 + 4 or not 2 == 4 and not 2 **4 > 6 * 3