Skip to main content

Python

Python is popular for its reliability and easy to write and easy to learn, python will hide the complexity of programming syntaxes and allow you to concentrate more on actual work.

Data types in Python

Python is a dynamic typed language, in python it is possible to create a variable with one type and assign value of another type, bellow are the list of data types available in Python.

1. int (Integers): -- Used for handling Whole numbers, ex: 3, 10, 50000, 47293393

int sampleInt = 77

2. float (Floats): -- Used for handling Numbers with decimal points, ex: 3.43, 10.3, 72.83783, 77.0

float sampleFloat = 7.7

3. str (Strings): -- Used for handling Group of characters (AKA array fo characters), ex:"Hello", "know basics", "id242", "P@ssw0rd"

str sampleString = "Hello World"

4. list (Lists): -- Used for handling Ordered sequence of object, could be combination of any datatypes, ex : [1, "Know basics", 7.7, "hello"]

list sampleList = [1, "Know basics", 7.7, "hello"]

5. dict (Dictionaries): -- Used for handling Key value pair in unordered sequence, ex: {"key1": "value1", "key2": "value2"}

dict sampleDict = {"id": 10007, "name": "Know basics"}

6. tup (Tuples): -- Used for handling Ordered immutable sequence of objects, ex: ("Know basics", 7.7, "hello")

tup sampleTup = ("Know basics", 7.7, "hello")

7. set (Sets): -- Used for handling Unordered collection of unique objects {"a", "b"}

set sampleSet = {"a", "b"}

8. bool (Booleans): -- Used for handling Boolean value that store True or False

bool sampleBool = True

It is possible to declare a variable without providing any type, python will identify the type based on provided value. And when type is not provided it is possible to use same variable name for different types. The type() method will help to identify what is the value type in given variable.

test_variable = 2 # valid case and type(test_variable) will returns int
test_variable = "Use different type" # This is also valid, and the type(test_variable) will return string

But if a type is provided while creating a variable then it is not possible to assign different type.

int test_variable = 2 # valid case and type(test_variable) will returns int
test_variable = "Use different type" # This is invalid and throws error

Numbers

The declaration of numbers looks Below

int a = 10
float b = 7.6
c = 52

Different kind of operations are possible on numbers, they are

  • Addition(+) : -- Regular addition, ex: a+b
  • Subtraction(-) : -- Regular subtraction, ex: a-b
  • Multiplication(*) : -- Regular multiplication, ex: a*b
  • Division(/) : -- Regular division, ex: a/b
  • Module(%) : -- Calculates the reminder of the division, ex: 5%2 = 1, 15%10=5
  • Power(**) : -- Calculates the power of, ex: 2**2 = 4, 2**3=8, 3**4=81

Strings

Strings are sequence of characters, each character in a string will start with a whole number, the number start with 0 and increase by 1 for each character. And The python will also provide reverse index in negative numbers, as zero is already used the last character of the string will start with -1, and will decrease by 1 for each character in reverse order

str foo = "Know basics"
bar = "Hello world"

In above example the variable bar have 11 characters, the space will also count as a character, so indexes are assigned as shown below

bar         K   n   o   w       b   a   s   i   c   s
Index 0 1 2 3 4 5 6 7 8 9 10
Reverse -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

It is possible to fetch any particular character from the string by passing its index. Also python will allow to slice part of the string by providing range in a given syntax, the syntax looks like this string[start:stop:step]

  • start : -- The index from where the sub part of text required
  • stop : -- The index upto where the sub part of text required, it will always include before one index of this value
  • step : -- Number of indexes to skip after each character selection, the default and minimum value is 1, where no character is skipped
print(bar[5]) # Prints character b, consider step as 1 if not provided

print(bar[-3]) # Prints character i

print(bar[2:8]) # Prints ow bas, from index 2 character to index 7th index character (Won't include 8 index char)

print(bar[2:]) # Prints ow basics, start from second character to remaining string

print(bar[:7]) # Prints Know ba, From beginning to 6th index character (won't include 7th index char)

print(bar[-11:-1]) # Prints Know basic

print(bar[::]) # Prints Know basic, Return same string as response, considers step as 1 if not provided

print(bar[::1]) # Prints Know basic, Return same string as response

print(bar[::2]) # Prints Ko ais, Skips one char after every single char, and returns all odd index chars

print(bar[::-1]) # Prints scisab wonK, Reverse of a given string

String values are immutable, immutable means you can't change the value of string once created. That doesn't mean you can't replace a string variable value with completely new value, but you can't change any character in string once it is created. Lets understand it better from bellow examples

str a = "hello"
print(a[0]) # returns first char from string

a[0] = "H" # throws error, you can't change any char value with in the string

a = "world" # this is valid and the value will change from hello to world

str a ="hello"
str b = "world"
c = a + " " + b # string concatenation would done and c value would be hello world

# * operator on string
a = "v"
b = a*3 # The b will have value vvv

1.capitalize() : -- Converts the first character of string to upper case

my_str = "know basics"

print(my_str.capitalize()) # This will print "Know basics

2.casefold() : -- Advanced version to lower, The lower will works on ASCII characters only (256 chars), but casefold will work on Unicode characters (Around 143,859 chars)

my_str = "Ķnow BasiĆs"

print(my_str) # prints "Ķnow BasiĆs"
print(my_str.casefold()) # prints "ķnow basićs"

3.center(count, character) : -- This will add given characters before and after the string and make over all string length to given count. the character input is optional, if not provided will take space

my_str = "hello"

print("|"+my_str.center(20)+"|")
# added pipes while print so that you could observe appended spaces, the print result is "| hello |"
# Here the length of " hello " would be 20, and the length of "hello" is 5
# The method prepend 7 spaces, and append 8 spaces, total length is 7 + 5 + 8 = 20 which is equal to given input

print(my_str.center(20,"*")) # this will prepend 7 * to string and append 8 * to string, the result is "*******hello********"

4.count(input_string) : -- This method will count number of times the input string occurs in given string

my_str = "Ķnow BasiĆs"

print(my_str) # prints "Ķnow BasiĆs"
print(my_str.casefold()) # prints "ķnow basićs"

5.count() : -- Returns the number of times a specified value occurs in a string

5.encode() : -- Returns an encoded version of the string

5.endswith() : -- Returns true if the string ends with the specified value

5.expandtabs() : -- Sets the tab size of the string

5.find() : -- Searches the string for a specified value and returns the position of where it was found

5.format() : -- Formats specified values in a string

5.format_map() : -- Formats specified values in a string

5.index() : -- Searches the string for a specified value and returns the position of where it was found

5.isalnum() : -- Returns True if all characters in the string are alphanumeric

5.isalpha() : -- Returns True if all characters in the string are in the alphabet

5.isascii() : -- Returns True if all characters in the string are ascii characters

5.isdecimal() : -- Returns True if all characters in the string are decimals

5.isdigit() : -- Returns True if all characters in the string are digits

5.isidentifier() : -- Returns True if the string is an identifier

5.islower() : -- Returns True if all characters in the string are lower case

5.isnumeric() : -- Returns True if all characters in the string are numeric

5.isprintable() : -- Returns True if all characters in the string are printable

5.isspace() : -- Returns True if all characters in the string are whitespaces

5.istitle() : -- Returns True if the string follows the rules of a title

5.isupper() : -- Returns True if all characters in the string are upper case

5.join() : -- Converts the elements of an iterable into a string

5.ljust() : -- Returns a left justified version of the string

5.lower() : -- Converts a string into lower case

5.lstrip() : -- Returns a left trim version of the string

5.maketrans() : -- Returns a translation table to be used in translations

5.partition() : -- Returns a tuple where the string is parted into three parts

5.replace() : -- Returns a string where a specified value is replaced with a specified value

5.rfind() : -- Searches the string for a specified value and returns the last position of where it was found

5.rindex() : -- Searches the string for a specified value and returns the last position of where it was found

5.rjust() : -- Returns a right justified version of the string

5.rpartition() : -- Returns a tuple where the string is parted into three parts

5.rsplit() : -- Splits the string at the specified separator, and returns a list

5.rstrip() : -- Returns a right trim version of the string

5.split() : -- Splits the string at the specified separator, and returns a list

5.splitlines() : -- Splits the string at line breaks and returns a list

5.startswith() : -- Returns true if the string starts with the specified value

5.strip() : -- Returns a trimmed version of the string

5.swapcase() : -- Swaps cases, lower case becomes upper case and vice versa

5.title() : -- Converts the first character of each word to upper case

5.translate() : -- Returns a translated string

5.upper() : -- Converts a string into upper case

5.zfill() : -- Fills the string with a specified number of 0 values at the beginning

format() method usage

The format method can be used in multiple ways, it is also allowed to use with floats along with strings, below are few example that demonstrate how the format() will work

# Using format() with strings 
"You {} reading blog in {} basics ".format("are", "Know") # The result would be "You are reading blog in know basics"
"You {1} reading blog in {0} basics ".format("Know", "are") # The result would be "You are reading blog in know basics"
"You {1} reading blog in {1} basics ".format("Know", "are") # The result would be "You are reading blog in are basics"
"You {a} reading blog in {k} basics".format(a="are", k="Know") # The result would be "You are reading blog in know basics"

# the string literal feature of python that is alternate to format()
a = "are"
k = "know"
print(f"You {a} reading blog in {k} basics")# The result would be "You are reading blog in know basics", observe character f at beginning of string

# Using % for merging strings
print("You are reading blog in %s basics" %'Know')# The result would be "You are reading blog in know basics"
print("You %s reading blog in %s basics" %('are','Know'))# The result would be "You are reading blog in know basics"

a, k ="are", "Know"
print("You %s reading blog in %s basics" %(a, k))# The result would be "You are reading blog in know basics"

# Using format() with floats using {value:width:precision f} pattern
f = 1.276438972
"The float number is {res}".format(res=f) # Will returns The float number is 1.276438972
"The float number is {res:1.2f}".format(res=f) # Will returns The float number as 1.28
"The float number is {res:10.2f}".format(res=f) # Will returns The float number as 1.28, there would a lot of space
"The float number is {res:10.6f}".format(res=f) # Will returns The float number as 1.276439, as decimal points increase prepended space would be decreased

f = 701.3928394
"The float number is {res:1.2f}".format(res=f) # Will returns The float number as 701.39, as decimal points increase prepended space would be decreased

List functions

1. len() : -- Calculates number of items in list

len(my_list)

2. [start:stop:step] : -- Splits array and return elements

my_list[1:5:1] # Splits array and return elements from index 1 to index 4

3. concat : -- Concatenates the two lists with operator +

result = my_list1 + my_list2

4. append : -- Adds the new value to list

my_list.append("test") # Adds the new value `test` at end of list

5. clear: -- Delete all elements in list

my_list.clear()

6. copy : -- Clones the list

cloned_list = my_list.copy()

7. count : -- Returns the count of inputted element in list

my_list.count(<value>)

8. extend : -- Concat inputted list to current list but returns nothing.

my_list.extend([val1, val2, ...])

9. index : -- Returns index of the given value. If not found throws error.

my_list.index(value)

10. insert : -- Inserts given value at given index

my_list.insert(index, value)

11. pop : -- Deletes last element of the list

my_list.pop()

12. remove : -- Deletes given element from list

my_list.remove(value)

13. reverse : -- Reverse the order of elements in list

my_list.reverse()

14. sort : -- Sorts the elements in list

my_list.sort()

Dictionary functions

1. clear : -- Delete all key value pairs in dictionary

my_dict.clear()

2. copy : -- Clones the dictionary

cloned_dict = my_dict.copy()

3. fromkeys : -- Construct new dictionary by list of Keys mapping to given value

result_dict = my_dict.fromkeys(listOfKeys, value)

4. get : -- Returns value of the given key

my_dict.get(key)

5. items : -- Convert each key value to tuple and returns

my_tuple= my_dict.items()

6. keys : -- Returns list of all keys

my_keys= my_dict.keys()

7. pop : -- Delete the key value by given key

my_dict.pop(key)

8. popitem : -- Deletes the last inserted key value pair

my_dict.popitem()

9. setdefault : -- If given key exists returns that value, if not exist set the given value in dictionary and returns it

my_val = my_dict.setdefault(key, value)

10. update : -- Concatenates two dictionaries

my_val = my_dict.update(oter_dict)

11. values : -- Return list of all values in dictionary

my_vals = my_dict.values()