Python Fast Boot Camp For Dummies , Understanding Variable , numbers, tuple , list , dictionary , python data structure.

What is variable ?

Variable is a label for a location in memory . Variable make us easy to understand as programmer.

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Let’s take a look on each of them.

Number Data Type in Python

Python supports integers, floating point numbers and complex numbers. They are defined as intfloat and complex class in Python.

# note variable is always at the left and we assign it with = to something like integer and float
# example we name our variable i for integer and f for float
i = 7
f = 3.5
# print the value of i and f to command prompt
print (i)
print (f)
# we can use type function to determine what is variable i and f is
print (type(i))
print (type(f))
## We can covert between the type to by using int and float function
print (float(i))
print (int(f))

Below are example of number type.

intfloatcomplex
100.03.14j
10015.2045.j
-786-21.99.322e-36j
08032.3+e18.876j
-0490-90.-.6545+0J
-0x260-32.54e1003e+26J
0x6970.2-E124.53e-7j
Number SystemPrefix
Binary‘0b’ or ‘0B’
Octal‘0o’ or ‘0O’
Hexadecimal‘0x’ or ‘0X’

Complex numbers are an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary numbers are real multiples of the imaginary unit (the square root of -1), often written i in mathematics or j in engineering. Python has built-in support for complex numbers, which are written with this latter notation; the imaginary part is written with a j suffix, e.g., 3+1j. To get access to complex equivalents of the math module, use cmath. Use of complex numbers is a fairly advanced mathematical feature. If you’re not aware of a need for them, it’s almost certain you can safely ignore them.

Complex numbers are stored as a pair of machine-level double precision floating point numbers.

x = 3+1j
y = 3+2j
z = 3+3j
x = x + y + z
print (x)
print(type(x))
print(type(y))
print(type(z))

Below are Operation that we can do with number type.

OperationMeaning
<strictly less than
<=less than or equal
>strictly greater than
>=greater than or equal
==equal
!=not equal
isobject identity
is notnegated object identity

Cheat Sheet For Number

OperationResultNotesFull documentation
x + ysum of x and y
x - ydifference of x and y
x * yproduct of x and y
x / yquotient of x and y
x // yfloored quotient of x and y(1)
x % yremainder of x / y(2)
-xx negated
+xx unchanged
abs(x)absolute value or magnitude of xabs()
int(x)x converted to integer(3)(6)int()
float(x)x converted to floating point(4)(6)float()
complex(re, im)a complex number with real part re, imaginary part imim defaults to zero.(6)complex()
c.conjugate()conjugate of the complex number c
divmod(x, y)the pair (x // y, x % y)(2)divmod()
pow(x, y)x to the power y(5)pow()
x ** yx to the power y(5)

String Data Type

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. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 to the end.

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

#### Declare Variable str and assign string to it
str = "Welcome to Python String Tutorial"
print (len(str))     # Prints length of the str
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 + " More Text") # Prints concatenated string
print (str.lower())  # Prints to lower
print (str.upper())  # Prints all to upper

List data type in Python

list1 = [ 'Apple' , 'Banana' , "Stawberry" ] ## Declare 3 List Element
list1[0] = "Change from apple to Chili"   ## Remember to access List 0 is the first element
list2 = ['Name' , 'Fruit' , '123']
## looping list
for x in list1:
    print (x)
print (list1)          # Prints complete list
print (list1[0])       # Prints first element of the list
print (list1[1:3])     # Prints elements starting from 2nd till 3rd
print (list1[2:])      # Prints elements starting from 3rd element
print (list1 * 2)  # Prints list two times
print (list1 + list2) # Prints concatenated lists
print (len(list1))               ### print how many element in list which is 3
list1.append ("New Element")     ### append to list1
list1.insert (1, 'New Item')     ### insert in list[1] New Item
del list1[0]                     ### remove item from list[0]

Tuple Data Type in Python

While list we begin to declare it with [] , tuple we declare it with () . Unlike List , List can be change while Tuple can’t be change . It is like read only data . Let’s take a look from example below.

tuple1 = ('12345' , 'Some Text Here' , 'Final text here 12345') ## declare tuple Notice we use ()
tuple2 = ('54321', "another text here")
print (len(tuple1))           ## print tuple1 length
print (len(tuple2))           ## print tuple2 length
print (tuple1)           # Prints complete tuple
print (tuple1[0])        # Prints first element of the tuple
print (tuple1[1:3])      # Prints elements starting from 2nd till 3rd
print (tuple1[2:])       # Prints elements starting from 3rd element
print (tuple2 + tuple1)  # prints tuple 2 and follow by tuple 1
#### We try to edit tuple1 with result of error
tuple1[0] = 'Error'     # TypeError: 'tuple' object does not support item assignment

Dictionary Data Type in Python

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.

A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.

dict1 = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
    ### Nested Dictionary
    'key4' : { 'A' : 'Welcome' , 'B' : 'To' , 'C' : 'Python'}
}
##### Let's see what we can do with Dictionary
print (dict1)                  ## print key and value of dict1
print (dict1.get('key1'))      ## print key1 value which is value1
dict1 ['key1'] = 'somevalue'   ## change key1 value to somevalue
dict1 ["key5"] = 'somevalue5'  ## Adding an item to the dictionary is done by using a new index key and assigning a value to it:
del dict1["key2"]                   ## remove key2 from dictionary
dict2 = dict1.copy()                  ## Copy Dictionary
#### We can loop over the key .
for x in dict1:                ## Print all key names in the dictionary, one by one:
  print(x)
#### Print all values in the dictionary, one by one:
for x in dict1:
  print(dict1[x])
#### You can also use the values() function to return values of a dictionary:
for x in dict1.values():
  print(x)
#### Loop through both keys and values, by using the items() function:
for x, y in dict1.items():
  print(x, y)
Source :

https://docs.python.org/3/library/stdtypes.html

https://python-reference.readthedocs.io/en/latest/docs/complex/

https://www.geeksforgeeks.org/python-dictionary/

https://www.w3schools.com/python/python_dictionaries.asp

https://www.tutorialspoint.com/python3/python_variable_types.htm

Leave a Reply