Variables in python


In [ ]:
# How to defining variables ?
a = 10 # integer variable
b = 20.1 # float variable
c = "Hello World" # string variable
d = "A" # character variable = string variable of length 1

In [ ]:
print("Int:", a)
print("Float:", b)
print("String:", c)
print("Character:", d) # it is one of the special case of string variable

In [ ]:
# How to find the data type of a variable ?
print(type(a))
print(type(b))
print(type(c))
print(type(d))

Data structure - List()


In [ ]:
# Define an empty list
empty_list = list()
new_empty_list = []

# View created lists
print(empty_list)
print(new_empty_list)

In [ ]:
# Assign values in a list
# empty_list[0] = "Mango" # wrong
empty_list.append("Mango")
print(empty_list)

In [ ]:
# List can have multiple data types
empty_list.append(100)
empty_list.append("A")
empty_list.append(0.001)
print(empty_list)

In [ ]:
# change values in a non empty list
empty_list[0] = "Apple" # which is Mango currently
print(empty_list)

In [ ]:
# Get size of a list
size_of_list = len(empty_list)
print(size_of_list)
print(empty_list)

In [ ]:
# List is zero indexed
print(empty_list[0])

# List has inverse indexes as well -> revese index start from -1
print(empty_list[-4])

Looping in python

for-loop


In [ ]:
# Simple for-loop
array = [0, 1, 2, 3, 4, 5]
for value in array:
    print(value)

In [ ]:
# Looping on a list of string
fruits = ["mango", "guava", "banana"]

for fruit in fruits:
    print("Fruit name is", fruit)

In [ ]:
# Looping on a list of string with condition
fruits = ["mango", "guava", "banana", "apple"]

for fruit in fruits:
    # acces each fruit in fruits list
    if fruit == "apple":
        # if fruit is apple then make it upper case
        print(fruit.upper()) # convrts all lower case character to upper case
    else:
        # if the fruit is other than apple print as it is
        print(fruit)

In [ ]:
# Looping on a list of string with condition
fruits = ["mango", "guava", "banana", "apple"]

for fruit in fruits:
    # acces each fruit in fruits list
    if fruit == "apple":
        # if fruit is apple then make it upper case
        print(fruit.upper()) # convrts all lower case character to upper case
    elif fruit == "mango":
        print("Fruit is Mango!")
    else:
        # if the fruit is other than apple print as it is
        print(fruit)

In [ ]:
# Loop over generated list
# Easy way to create a list of number
list_of_number = range(0, 10) # 0, 1, ..., 9 -> [0, 10)
print(list_of_number)

for number in list_of_number:
    print(number)

    
list_of_number = range(0, 10, 2) # 0, 2, 4, ..., 8 -> [0, 10)
print(list_of_number)

for number in list_of_number:
    print(number)

In [ ]:
print(empty_list)

In [ ]:
# Loop over a list using its index
for index in range(len(empty_list)):
    # here range generates a list = [0, 1, ..., 4]
    print(empty_list[index])

while-loop


In [ ]:
i = 0
stop = 10
while i < stop:
    print(True) # Boolean data type -> True and False
    i = i + 1

In [ ]:
print(type(True)), print(type(False))

In [ ]:
start = 0
stop = 10
while start < stop:
    print(start) # Boolean data type -> True and False
    start += 1 # start = start + 1

In [ ]:
# lopping on a list
names = ["Youplus", "Nokia", "Microsoft", "Apple"]

i = 0
while i < len(names):
    print(names[i])
    i += 1 # unlike for-loop, while doesn't do increament automatically

In [ ]:
print(names)

In [ ]:
# Sort list
print(sorted(names))

In [ ]:
print(sorted(names, reverse=True))

Data types - Int, Float, String


In [ ]:
# Define an integer variable
a = 1
print(type(a))

In [ ]:
# List properties and methods on a integer variable
print(dir(a))

In [ ]:
print(a.bit_length())

In [ ]:
a = 10
print(a.bit_length())

In [ ]:
# More interseting data type
name = "Kumar Nityan Suman"


# Methods on string variables
print(dir(name))

In [ ]:
print(name)

In [ ]:
print(name.capitalize()) # Only capitalize first character of the string

In [ ]:
print(name.casefold()) # all lower -> good for other languages than english

In [ ]:
print(name.lower()) # works with english language

In [ ]:
print(name.upper())

In [ ]:
name = "   Apple.       "
print(name)

In [ ]:
print(name.lstrip()) # strips white spaces from left

In [ ]:
print(name.rstrip())

In [ ]:
print(name.strip()) # strip from both sides

In [ ]:
# Strip other than white space
print(name.strip().strip("."))

In [ ]:
name = "Youplus Inc."

In [ ]:
print(name)
print(name.strip())

In [ ]:
print(name.strip("."))

In [ ]:
name

In [ ]:
# Split string into words
print(name.split()) # split on any number of white space

In [ ]:
name = "Youplus          Inc." # 10 spaces
print(name.split())

In [ ]:
print(name.split(" ")) # split on 1 white space

In [ ]:
" "

In [ ]:
""

In [ ]:
email = "nityan.suman@gmail.com"
print(email.split("@"))
print(email.split("."))

In [ ]:
print(email.split("suman"))

In [ ]:
# Concatenate string
fname = "you"
lname = "plus"
print(fname + lname)
print(fname + " " + lname)
print(fname + "%" + lname)

In [ ]:
name = "Youplus"

print(name.isalnum())
print(name.isalpha())
print(name.isdecimal())
print(name.isdigit())

In [ ]:
print(name.isprintable())

In [ ]:
print(name.islower())
print(name.lower().islower())

In [ ]:
float_variable = 10.1
print(type(float_variable))

float_variable = 0.01
print(type(float_variable))

In [ ]:
# Methods and properties onf float objects
print(dir(float_variable))

Data structure - Dict()


In [ ]:
# Define an empty dictionary
my_dict = dict()
my_dict_new = {}

print(type(my_dict))
print(type(my_dict_new))

In [ ]:
# Assign key-value pair
my_dict["nityan"] = 1

In [ ]:
print(my_dict)

In [ ]:
my_dict["suman"] = 2
my_dict["kumar"] = 0

In [ ]:
print(my_dict)

In [ ]:
my_dict["nityan"] = 3
print(my_dict)

In [ ]:
# Dictionary can also handle multiple data types like lists
my_dict["suman"] = 100
print(my_dict)

In [ ]:
for item in my_dict.values():
    print(item)

In [ ]:
my_dict["kumar"]

In [ ]:
# Acces keys
print(my_dict.keys())

# Access values
print(my_dict.values())

In [ ]:
for x in my_dict.keys():
    print(x)

In [ ]:
print(sorted(my_dict.keys()))

In [ ]:
print(sorted(my_dict, reverse=True))

In [ ]:
print(sorted(my_dict.values())) # sort values

In [ ]:
print(my_dict)

In [ ]:
my_dict["nityan"] = 10
my_dict["suman"] = 5
my_dict["kumar"] = 1000

In [ ]:
print(my_dict)

In [ ]:
# Sort a dictionary based on values
sorted_x = sorted(my_dict.items(), key=lambda item: item[1])

# Sort dictionary based on keys
sorted_y = sorted(my_dict.items(), key=lambda item: item[0])

print("Sorted on values = ", sorted_x)
print("Sorted on keys = ", sorted_y)

Methods in python


In [ ]:
# How to write a method / function in python ?
# Why use methods ? - So that you can use same piece of code again and again without writing it multiple times.
def is_equal(paramater1, parameter2):
    if paramater1 == parameter2:
        return True
    else:
        return False

In [ ]:
# Apply method
print(is_equal(10, 10))
print(is_equal("nityan", "Nityan"))
print(is_equal(10, 10.0))
print(is_equal("1", 1))

In [ ]:
def is_equal(paramater1, parameter2):
    if paramater1 == parameter2 and type(paramater1) == type(parameter2):
        return True
    else:
        return False

In [ ]:
# Apply method
print(is_equal(10, 10))
print(is_equal("nityan", "Nityan"))
print(is_equal(10, 10.0))
print(is_equal("1", 1))

In [ ]:
def count_in_list(sample_list):
    count = 0 # count variable set to 0
    for element in sample_list:
        count += 1
    return count

In [ ]:
# Apply method
print(count_in_list(["1", "2", "3"]))

a = [1, 2, 3, 4, 5]
print(count_in_list(a))

b = ["screen", "speaker", "battery", "power"]
print(count_in_list(b))

In [ ]:
def get_list_of_words(sample_string):
    words = sample_string.split() # split string into words using any-number of spaces
    return words

In [ ]:
# Apply
words_returned = get_list_of_words("This is a    sample test string!")
print(words_returned)

print(get_list_of_words("This is a sentence."))

In [ ]:
"This is a    sample test string!".split()

In [4]:
!pwd


/Users/nityansuman/__home__/python-programing

In [3]:
from basics.util import is_equal

In [ ]:
is_equal(10, 10.0)

In [ ]: