Skip to content

Variable Types

Farrokh Karimi edited this page Jan 27, 2019 · 4 revisions

[Home Page]
[Previous Page]

Variables are nothing but reserved memory locations to store values. It means that when you create a variable, you reserve some space in the memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, decimals or characters in these variables.

Assigning

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

Example:

#!/usr/bin/python3

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print (counter)
print (miles)
print (name)

Result:

100
1000.0
John

Multiple Assignment

Python allows you to assign a single value to several variables simultaneously.

Example:

a = b = c = 1
d, e, f = 1, 2, "john"

Python Data Types

Python has five standard data types:

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Numbers

Number data types store numeric values.

Example:

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement.

Example:

del var1

Python supports three different numerical types:

  • int (signed integers)
  • float (floating point real values)
  • complex (complex numbers)

All integers in Python3 are represented as long integers. Hence, there is no separate number type as long. A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are real numbers and j is the imaginary unit.

Number Type Conversion

Python converts numbers internally in an expression containing mixed types to a common type for evaluation. Sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

  • Type int(x) to convert x to a plain integer.
  • Type long(x) to convert x to a long integer.
  • Type float(x) to convert x to a floating-point number.
  • Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
  • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions.

Mathematical Functions

Python includes the following functions that perform mathematical calculations.

abs(x) # The absolute value of x: the (positive) distance between x and zero.

math.ceil(x) # The ceiling of x: the smallest integer not less than x.

cmp(x, y) # -1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3. Instead use return (x>y)-(x<y).

math.exp(x) # The exponential of x: ex

math.fabs(x) # The absolute value of x.

math.floor(x) # The floor of x: the largest integer not greater than x.

math.log(x) # The natural logarithm of x, for x > 0.

math.log10(x) # The base-10 logarithm of x for x > 0.

max(x1, x2,...) # The largest of its arguments: the value closest to positive infinity

min(x1, x2,...) # The smallest of its arguments: the value closest to negative infinity.

math.modf(x) # The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

math.pow(x, y) # The value of x**y.

round(x [,n]) # x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

math.sqrt(x) # The square root of x for x > 0.

Random Number Functions

Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes the following functions that are commonly used.

random.choice(seq) # A random item from a list, tuple, or string.

random.randrange ([start,] stop [,step]) # A randomly selected element from range(start, stop, step).

random.random() # A random float r, such that 0 is less than or equal to r and r is less than 1

random.seed([x]) # Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

random.shuffle(lst) # Randomizes the items of a list in place. Returns None.

random.uniform(x, y) # A random float r, such that x is less than or equal to r and r is less than y.

Trigonometric Functions

Python includes the following functions that perform trigonometric calculations.

math.acos(x) # Return the arc cosine of x, in radians.

math.asin(x) # Return the arc sine of x, in radians.

math.atan(x) # Return the arc tangent of x, in radians.

math.atan2(y, x) # Return atan(y / x), in radians.

math.cos(x) # Return the cosine of x radians.

math.hypot(x, y) # Return the Euclidean norm, sqrt(x*x + y*y).

math.sin(x) # Return the sine of x radians.

math.tan(x) # Return the tangent of x radians.

math.degrees(x) # Converts angle x from radians to degrees.

math.radians(x) # Converts angle x from degrees to radians.

Mathematical Constants

The module also defines two mathematical constants:

pi # The mathematical constant pi.

e # The mathematical constant e.

Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows either pair of single or double quotes.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.

Example:

#!/usr/bin/python3

str = 'Hello World!'

print (str)          # Prints complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string

Result:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Accessing Values in Strings

To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring.

Example:

#!/usr/bin/python3

var1 = 'Hello World!'
var2 = "Python Programming"

print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

Result:

var1[0]:  H
var2[1:5]:  ytho

Escape Characters

Escape characters are non-printable characters that can be represented with backslash notation. An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash notation 	Hexadecimal character 	Description
-----------------------------------------------------------
\a 			0x07 			Bell or alert
\b 			0x08 			Backspace
\cx 						Control-x
\C-x 						Control-x
\e 			0x1b 			Escape
\f 			0x0c 			Formfeed
\M-\C-x 					Meta-Control-x
\n 			0x0a 			Newline
\nnn 						Octal notation, where n is in the range 0.7
\r 			0x0d 			Carriage return
\s 			0x20 			Space
\t 			0x09 			Tab
\v 			0x0b 			Vertical tab
\x 						Character x
\xnn 						Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

Formatting Operator

One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family.

Example:

#!/usr/bin/python3

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

Result:

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with %:

%c 	character
%s 	string conversion via str() prior to formatting
%i 	signed decimal integer
%d 	signed decimal integer
%u 	unsigned decimal integer
%o 	octal integer
%x 	hexadecimal integer (lowercase letters)
%X 	hexadecimal integer (UPPERcase letters)
%e 	exponential notation (with lowercase 'e')
%E 	exponential notation (with UPPERcase 'E')
%f 	floating point real number
%g 	the shorter of %f and %e
%G 	the shorter of %f and %E

Triple Quotes

The syntax for triple quotes consists of three consecutive single or double quotes.

Example:

#!/usr/bin/python3

para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)

When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes.

Result:

this is a long string that is made up of
several lines and non-printable characters such as
TAB (    ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
 ], or just a NEWLINE within
the variable assignment will also show up.

Example:

#!/usr/bin/python3

print ('C:\\nowhere')

Result:

C:\nowhere

Now let's make use of raw string. We would put expression in r'expression':

Example:

#!/usr/bin/python3

print (r'C:\\nowhere')

Result:

C:\\nowhere

String Methods

Python includes the following built-in methods to manipulate strings:

capitalize() # Capitalizes first letter of string

center(width, fillchar) # Returns a string padded with fillchar with the original string centered to a total of width columns.

count(str, beg = 0,end = len(string)) # Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.

replace(old, new [, max]) # Replaces all occurrences of old in string with new or at most max occurrences if max given.

split(str="", num=string.count(str)) # Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.

# And many others

Example:

#!/usr/bin/python3

str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.capitalize())

Result:

str.capitalize() :  This is string example....wow!!!

Example:

#!/usr/bin/python3

str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

Result:

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

Lists

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]).

Example:

#!/usr/bin/python3

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print (list)          # Prints complete list
print (list[0])       # Prints first element of the list
print (list[1:3])     # Prints elements starting from 2nd till 3rd 
print (list[2:])      # Prints elements starting from 3rd element
print (tinylist * 2)  # Prints list two times
print (list + tinylist) # Prints concatenated lists

Result:

['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.

Example:

#!/usr/bin/python3

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])

Result:

list1[0]:  physics
list2[1:5]:  [2, 3, 4, 5]

Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator.

Example:

#!/usr/bin/python3

list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])

list[2] = 2001
print ("New value available at index 2 : ", list[2])

Result:

Value available at index 2 :  1997
New value available at index 2 :  2001

Basic List Operations

Python Expression 				Results 				Description
len([1, 2, 3]) 					3 					Length
[1, 2, 3] + [4, 5, 6] 				[1, 2, 3, 4, 5, 6] 			Concatenation
['Hi!'] * 4 					['Hi!', 'Hi!', 'Hi!', 'Hi!'] 		Repetition
3 in [1, 2, 3] 					True 					Membership
for x in [1,2,3] : print (x,end = ' ') 		1 2 3 					Iteration

Methods

Python includes the following list methods:

list.append(obj) # Appends object obj to list

list.count(obj) # Returns count of how many times obj occurs in list

list.extend(seq) # Appends the contents of seq to list

list.index(obj) # Returns the lowest index in list that obj appears

list.insert(index, obj) # Inserts object obj into list at offset index

list.pop(obj = list[-1]) # Removes and returns last object or obj from list

list.remove(obj) # Removes object obj from list

list.reverse() # Reverses objects of list in place

list.sort([func]) # Sorts objects of list, use compare func if given

Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis. Tuples can be thought of as read-only lists.

Example:

#!/usr/bin/python3

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple)           # Prints complete tuple
print (tuple[0])        # Prints first element of the tuple
print (tuple[1:3])      # Prints elements starting from 2nd till 3rd 
print (tuple[2:])       # Prints elements starting from 3rd element
print (tinytuple * 2)   # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

Result:

('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

Dictionaries

Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

Example:

#!/usr/bin/python3

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values

Result:

This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.

Example:

#!/usr/bin/python3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

Result:

dict['Name']:  Zara
dict['Age']:  7

Note: There are some methods for Dictionaries too.

Data Type Conversion

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type-names as a function.

int(x [,base]) # Converts x to an integer. The 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.

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.

chr(x) # Converts an integer to a character.

ord(x) # Converts a single character to its integer value.

eval(str) # Evaluates a string and returns an object.

hex(x) # Converts an integer to a hexadecimal string.

oct(x) # Converts an integer to an octal string.

[Next Page]

Clone this wiki locally