Saturday, August 8, 2020

Writing Functions and Importing Custom/System Functions

 

                    Writing Functions and Importing Custom/System Functions


# writing custom function to find index 

print('Imported testp...')


def find_index(to_search, target):
'''Find the index of a value in a sequence'''
for i, value in enumerate(to_search):
if value == target:
return i

return -1



# Import sys module and printing all System Path.

import sys
print(sys.path)

# Import OS module and print location of file where the function is defined.

import os
print(os.__file__)

Comparisons and Loops with break/Continue


# Comparisons:


# Equal: ==
# Not Equal: !=
# Greater Than: >
# Less Than: <
# Greater or Equal: >=
# Less or Equal: <=
# Object Identity: is



Break statement :


nums = [1,2,3,4,5]

for num in nums:

if num == 2:

### Here we are breaking out of while loop when num is equal to 2, output will only be 1
break
print(num)
num += 1



Continue statement :

nums = [1,2,3,4,5]

for num in nums:

if num == 2:

### Here we are passing off when num is equal to 2, so output is 1,3,4,5
continue
print(num)
num += 1



Tuesday, August 4, 2020

List, Tuples, Set and Dictionary

                                          List, Tuples, Set and Dictionary


# Empty Lists - Mutable
empty_list = []
empty_list = list()

# Empty Tuples -
Immutable
empty_tuple = ()
empty_tuple = tuple()

# Empty Sets - throw away duplicates or membership test
empty_set = set()

# Empty Dict - Key Value pairs
empty_dict = {} # This isn't right! It's a dict



Examples
list_1 = ['History', 'Math', 'Physics', 'CompSci']
print(list_1)
Update list
list_1[0] = 'Art'


#tuple tuple_1 = ('History', 'Math', 'Physics', 'CompSci')

print(tuple_1)
# Sets
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
print(cs_courses)
# Dictionary
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}

for key, value in student.items():
print(key, value)

Sunday, August 2, 2020

Python String formatting


                                       Python String formatting

                                             

  Formatting string in python can be achieved via different ways as below.


Declaring variables :


greeting = 'Hello'

name = 'Abizer'

morninggreeting = 'Morning !'



Concatenating string (Default and easy when not many strings need to be Concatenated)


message =  greeting + ", " + name + "." + morninggreeting

Formatting strings via below method to make it more readable.



message =  '{}, {}.{}'.format(greeting, name, morninggreeting)


If your using 3.6+ version of Python we can use f strings to achieve same thing


message = f'{greeting}, {name}.{morninggreeting}'





Finally print the output.


print(message)

Output :

Hello, Abizer.Morning !