Skip to main content

Python for Machine Learning

 **Numbers in Python**


## Adding two numbers

2+3


## Subtracting two numbers

3-2


## Multiplication of two numbers

2*3


## Dividing two numbers it gives the floating point number

3/2


## Floor division gives the quotient

3//2


## Modulo division % gives the reminder

4%4


5%3


## Power, That means exponential we use **

2**3


3**2


## We can use floating point number in power.

4**0.2


## Squareroot of 2

2**0.5


## Multiplication of two numbers

4*0.2


**Variables**


**1. Rules for varibale names**

- Names can not start with a number

- Names can not contain spaces, use _ instead

- Names can not contain any of these symbols: ' " < > / ! @ # % ^ & * 

- Avoid using Python built-in keywords like list and str 


## Assigning values to variable 'a'

a=10

print(a)


number=10.5


New_number = 9

print(New_number)


## Boolean variable

a=True

print(a)


false=89

h=false


print(h)


## Calculate the simple interest

## Simple Interest = p*t*r/100

principal_amount = 10000

time = 5

rate = 0.1


simple_interest = (principal_amount*time*rate)/100

print(simple_interest)



**Dynamic Typing:** Python uses dynamic typing, that means you can reassign variables to diiferent data types. This makes python very flexible in assigning data types. It differs from other languages that are statically typed.


a = 1.5

type(a)


a=[1,2,3,4,5,6]

type(a)


You can check what type of object is assigned to a variable using Python's built-in type() funtion.

Common data types include:

- int    (for integer)

- float  (floating point)

- str    (for string)

- list   (for group of items)

- tuple  (for group of items)

- set    (for set or group of values)

- dict   (for dictionary)

- bool   (for Boolean True/False)


a=7

type(a)


a=5.6

type(a)


a='raju'

type(a)


a=[1,2,3,4,5,6]

type(a)


a=(1,2,3,4,5,6)

type(a)


**Strings:** String is nothing but sequence of characters.


Note: To create a string in python you need to use either single quotes or double quotes.


## Using single quote

'Hai'


## Using double quote

"Hai"


## We can use single quote with in double quote

"I'm human"


print("Welcome to python \n")

print("This is python")


Length Function: len()


## Length of a string by len() funtion in python

a=("Welcome to python")

len(a)


**String Indexing in Python:**

- In python, we use square brackets [] after an object to call it's index. We should also note that indexing starts at 0 for python.


a='Hai Bro'

type(a)


## Access the elements in string by using index

a[1]


## a[staring_index:stop_index]

a[0:2]


## Grab all values

a[:]


a[:4]


a[3:]


## -1 represents last index 'Hai Bro'

a[-1]


## Lower case a string

a.lower()


## Upper case a string

a.upper()


a.split()


a.split('i')


**String Formatting**

- String formatting provides a more powerful way to embed non-strings with in string.

- There are three ways to perform string formatting.

    - Using modulo % character

    - Using .format() method

    - Using f-string literals


## Formatting with Placeholders that means modulo operator

a=input('Enter the name')

print("My name is %s" %a)


a,b='Raj','Ram'

print("Welcome to %s %s" %(a,b))


Formatting with .format()


'String  here {} then also {}' .format('Something1','Something2')


print('The {} {}'.format('Raja','Rama'))


Formatting with f-strings


## We can use python 3.6 version or above

n='Raju'

print(f'Hai {n}')


**Lists:**

- Lists are used to store items. Simply it's an array.

- A list is created using square brackets with commas separating items.

- A certain item in the list can be accessed by using it's index in square brackets.

- It's mutable that means after creating it we can modify it.


a=[1,2,3,4,5,6]

print(a)


type(a)


## Creating an empty list

a=[]

type(a)


b=[1,3.9,'NAme',[1,2,3,4]]

print(b)


len(b)


## Indexing in list

b[-1]


b[0]


b[1]


**List Slicing:** 

- List slices provides a more advance way of retrieving values from a list. 

- Basic list slicing involves indexing a list with two colon-seperated integers.

- This returns a new list containing all the values in the old list between the indices.


## Grabs the all values in the list

b[:]


##Grabs the all values in the list from index 1

b[1:]


b[-1:]


b[:3]


List operations in Python:


b


b+['Ram']


b=b+['Raju']

print(b)


type(b)


b*2


 b[2]='Raju'

 b


**List Functions:**

- The **append** methdod adds an item to the end of the existing list.

- The **extend** method adds an elements in the list end of the list.

- To get number of items in a list, you can use the **len** function.

- The **insert** method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.

- The **index** method finds the first occurrrence of a list item and returns its index.

- **max(list)**: Returns the list item with the maximum value.

- **min(list)**: Returns the list item with the minimum value.

- **list.remove(item)**: Removes an object from a list.

- **list.reverse()**: Reverses items in a list.


a=[1,2,3,4,5,6]

print(a)


a.append(7)

a


print(len(a))


## a.insert(index,value)

a.insert(7,8)

a


## Get the maximum value in list

max(a)


## Get the minimum value in list

min(a)


a.index(5)


a.pop()

a


**Dictionaries:**

- Dictionaries are data structures used to map arbitrary key to values.

- Dictionaries can be indexed in the same way as lists, using square brackets containing keys. 


a={}

type(a)


a={"key1":1,"key2":2,"key3":'Raju'}

print(a)


## Dictionary is key based search not a index.

## Indexing

a['key1']


a['key2']


a={1:'One',2:'Two',3:'Three',4:'Four'}

a


a[1]


## Reassigning or modifing

a[1]='Raju'

a


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

a


 a[2]


a[2][1]


a[2][2]


## Covert two list into dictionary

a=[1,2,3,4,5,6]

b=['Ram','Raj','Rani','Ramu','Roja','Ramya']


dict(zip(a,b))


## Convert list to dictionary

a=[1,2,3,4,5,6,7]

b={ n:n*n for n in a}

print(b)


b[1]


b[7]


**Dictionary Functions:**

- To determine whether a key is in a dictionary , you can use in and not in, ust as you can for a list.

- A useful dictionary method is get. It does the same thing as indexing,but if the key is not found in the dictionary it returns another specified value instead('None',by default).


d={1:'One',2:'Two',3:'Three',4:'Four'}

d


## Get the all keys

d.keys()


## Get the all values

d.values()


## Get the all items in the dictionary

d.items()


## in and not in

if 5 in d.keys():

  print(True)

else:

  print(False)


## in and not in

if 5 not in d.keys():

  print(False)

else:

  print(True)


d[4]


print(d.get(5))


print(d.get(1))


**Tuples:**

- Tuples are vary similar to lists, except that they are immutable that means cannot be changed.

- An empty tuple is created using an parenthesis pair.

  Ex: tp=()

- Also, they are created using parentheses, rather than square brackets.


## Creating an empty tuple

a=()

type(a)


a=(1,2,3,4,5)

a


a[:]


a[-1]


## Immutable that means once created the tuple we cannot change it. 

## If we try to change it will give the TypeError

a[1]=8


a*2


**Sets:**

- Sets are an unorderd collection of unique elements. we can construct by using the set() funtion.

- They are created by using curly braces, or the set funtion.

- They share same funtionalty with lists, such as the use of in to check whether they contain a particular item.


## Creating a set

s=set()

type(s)


s.add(5)

s


s.add(3)

s


k={1,2,3,4,5,6,3,4,6,7,3,5,2,4,5,3}

k


## Converting list to set

a=[1,2,3,4,5,6,3,5,6,2,5,2,5,3,6]

set(a)


if 18 not in a:

  print(True)


Comparison Operators:

- Comparison Operator will allow us to compare variables and output a Boolean value(True or False).

- == > < != >= <= 


## Equal operator

print(2==2)

print(4==3)


## Not Equal

print(2!=2)

print(1!= 2)


## Greater than

print(2>1)

print(1>2)


## Less than

print(2<1)

print(1<2)


## Greater than or equal

print(2>=2)

print(1>=2)


## Less than or equal

print(2<=1)

print(1<=3)


**IF Statements:**

- If the condition is True, then the statements inside the if block will execute.

- Syntax:

  

  if expression:

      statements


if True:

  print('It was true')


## Any intger is True except '0' it will give false.

n=-1

if n:

  print('It was true')


loc='Bank'

if loc == 'Bank':

  print('Welcome to our bank')

else:

  print("Wecome to Hotel")


loc='Hotel'

if loc == 'Bank':

  print('Welcome to our bank')

if loc =='Hotel':

  print("Wecome to Hotel")


**If ELif Else**


if case1:

      

      perform action1

elif case2:

  

      perform action2

else:


      perform action3


 ## If else

 n='Raju'


 if n=='Raju':

   print('Hai',n)

 else:

   print('Hello',n)


 ## If else

 n='Ramu'


 if n=='Raju':

   print('Hai',n)

 else:

   print('Hello',n)


a=6

if a==5:

  print('Hai Bro')

elif a==6:

  print('Ha Bro')

else:

  print('Hmma')


**For Loop:**

- The for loop is used to iterate over a given sequence, such as lists or strings.

- The for loop can be used to iterate over strings.


a=[1,2,3,4,5,6,7,8,9]


for i in a:

  print(i,end=" ")


for i in a[::-1]:

  print(i,end= " ")


## Range

list(range(0,10))


for i in range(0,10):

  print(i,end=" ")


## Write a program to print even numbers

for i in range(0,51):

  if i % 2 == 0:

    print(i,end=" ")


## Write a program to print even numbers

for i in range(0,51):

  if i % 2 == 1:

    print(i,end=" ")


## Sum of n natural numbers

n=int(input("Enter the number: "))

s=0

for i in range(n+1):

  s=s+i

print(s)


## Write a program to print 3rd table

for i in range(0,51):

  if i % 5 == 0:

    print(i,end=" ")


## Write a program to print even numbers

for i in range(0,21):

  if i != 3:

    print(i,end=" ")


## Print the first 10 number using for loop

for i in range(1,11):

  print(i,end= " ")


## Python program to print all the even numbers with the given range

for i in range(1,51):

  if i % 2 == 0:

    print(i,end=" ")


## Python program to print all the odd numbers with the given range

for i in range(0,51):

  if i % 2 == 1:

    print(i,end=" ")


## Python program to calculate the sum of all number 1 to a given number.

n=10

s=0

for i in range(1,n+1):

  s=s+i

print(s)


## Python program to calculate the sum of all the odd numbers with in the given range.

n=10

s=0

for i in range(n):

  if i % 2 == 1:

    s=s+i

print(s) 


# ## Python program to print a multiplication table of a given number

n=5

for i in range(11):

  print(n, "X",i,"=",5*i)


n=51

s=0

for i in range(n):

  if i % 5 == 0:

    print(i,end=" ")


## Python program to display numbers from a list using a for loop.

l=[1,2,3,4,5,6,7,8,9,10]

for i in l:

  print(i,end=" ")


## Python program to count the total number of digits in a number.

n='123456789'

c=0

for i in n:

  c=c+1

print(c)


n=123456789

n=str(n)

c=0

for i in n:

  c=c+1

print(c)


## Python program to check if the given string is pallindrome or not.

n=input()

r=""

for i in n:

  r = i + r

if n == r:

  print("This is Pallindrome")

else:

  print("This is not Pallimdrome")


n='eye'

r=""

for i in n:

  r = i + r

if n == r:

  print("This is Pallindrome")

else:

  print("This is not Pallimdrome")


# Python program that accepts a word from the user and reverses it.

n=input()

r=""

for i in n:

  r = i + r

print(r)


# ## Python program to check if a given number is an Armstrong number or not

# Follow the below steps and write python program to find armstrong number using For loop:


# Take input the number from the user.

# Initialize “order” with the length of the num variable.(order= Number of digits)

# Store the value of the num variable in the temp variable.

# Initialize the sum of digits with zero.

# While temp>0 repeat steps 6-7

# digit =temp%10 and sum += digit **order

# temp = temp//10

# If the sum equals to num, then we will print the number entered by the user is an Armstrong number


num = int(input("Enter a Number:"))

order = len(str(num))

temp = num;

sum = 0

stnum=str(num)

for i in stnum:

    digit =temp%10

    sum += digit **order

    temp = temp//10

if(sum==num):

    print("",num,"is an Armstrong number")

else:

    print("",num,"is not an Armstrong number")


## Python program to count the number of even or odd numbers from series of numbers.

n=[1,2,3,5,6,4,7,99,243,234,55]

for i in n:

  if i % 2 == 0:

    print(i,"Even Number")

  else:

    print(i,"Odd Number")


## Python program to display all number with in the range except the prime numbers.

# First, we will take the input:  

lower_value = int(input ("Please, Enter the Lowest Range Value: "))  

upper_value = int(input ("Please, Enter the Upper Range Value: "))  

  

print ("The Prime Numbers in the range are: ")  

for number in range (lower_value, upper_value + 1):  

    if number > 1:  

        for i in range (2, number):  

            if (number % i) == 0:  

                break  

        else:  

            print (number,end=" ")  


import math

def prime(n):

  f=True

  for i in range(2,int(math.sqrt(n))+1):

    if n%i==0:

      f=True

  return f


prime(16)


## Python program to find a factorail of the given number

def factorial(x):

    """This is a recursive function

    to find the factorial of an integer"""


    if x == 1:

        return 1

    else:

        # recursive call to the function

        return (x * factorial(x-1))



# change the value for a different result

num = 7


# to take input from the user

# num = int(input("Enter a number: "))


# call the factorial function

result = factorial(num)

print("The factorial of", num, "is", result)


# Python program to find the factorial of a number provided by the user.


# change the value for a different result

num = 7


# To take input from the user

#num = int(input("Enter a number: "))


factorial = 1


# check if the number is negative, positive or zero

if num < 0:

   print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

   print("The factorial of 0 is 1")

else:

   for i in range(1,num + 1):

       factorial = factorial*i

   print("The factorial of",num,"is",factorial)


**Break and Continue:**

- To end a while loop permanently, the break statement can be used.

- Unlike break, continue jumps back to the top of the loop, rather than stopping it. 

- Basically, the continue statement stops the current iteration and continue with the next one.


for i in range(10):

  if i == 2:

    print("Skipping 2")

    continue

  if i==5:

    print("Breaking")

    break

  print(i)

print('Finished')


**While Loop:**

- A while statement will repeatedly execute a single statement or group of statements as long as the condition is true.


## WHile Loop

x=0

while x<5:

  print(x)

  x+=1


## Using else with while loop

n=0

while n<5:

  print(n)

  n=n+1

else:

  print("Else is executed")


## We can use break and continue in while loop:

n=0

while 1==1:

  print(n)

  n += 1

  if n>=5:

    print("Breaking")

    break

print("FInished")


i=0

while True:

  i=i+1

  if i == 2:

    print("Skipping 2")

    continue

  if i==5:

    print("Breaking")

    break

  print(i)

print('Finished')


## Largest among three numbers

n1=int(input("Enter the n1: "))

n2=int(input("Enter the n2: "))

n3=int(input("Enter the n3: "))


if n1>n2 and n1>n3:

  print("n1 is largest")

elif n2>n1 and n2>n3:

  print("n2 is largest")

else:

  print("n3 is largest")


## Swap two numbers using python

## Using temporary varialbe

x=int(input('Enter a number: '))

y=int(input('Enter a number: '))


print("Before Swapping",x ,y)


t=x

x=y

y=t


print("After Swaping: ",x,y)


## Using without temporary variable.

x=int(input('Enter a number: '))

y=int(input('Enter a number: '))


print("Before Swapping",x ,y)


x,y=y,x


print("After Swaping: ",x,y)


## Program to check Vowel or Consonant

n=input("Enter the character: ")

if(n=='A' or n=='E' or n=="I" or n=='O' or n=='U' or n=='a' or n=='e' or n=='i' or n=='o' or n=='u'):

  print(n,"is a vowel")

else:

  print(n,"is a consonent")


**Functions:**

- A function is a block of coded instructions that perform a certain action.

- Once properly defined, a function can be reused throughout your program i.e re-use the same code.

- First, use def keyword followed by the function name(): 

- The parentheses can contain any parameters that your function should take (or stay empty)

    

    

    def name():


def name_of_the_function():

  pass

name_of_the_function()


def name_of_the_function():

  print(2)

name_of_the_function()


def sh():

  print("Hello")


sh()


def s(n):

  print(f'Hello {n}')

s('Raju')


## How to write a return in function

def ad(n1,n2):

  return n1+n2


print(ad(1,2)) ## No need to be integer it can be any data type in funtion.


## To find the number is prime or not


import math


def is_prime(n):

  if n%2==0 and n>2:

    return False

  

  for i in range(3,int(math.sqrt(n))+1):

    if n % i == 0:

      return False

    return True


is_prime(17)



is_prime(18)


is_prime(20)


## Find LCM of two numbers

def lcm(a,b):

  if a>b:

    g=a

  else:

    g=b

  while True:

    if (g % a == 0) and (g % b == 0):

      lcm=g

      break

    g+=1

  return lcm


n1=int(input("Enter the first number:"))

n2=int(input("Enter the second number: "))


LCM=lcm(n1,n2)


print(f"The LCM of {n1} and {n2} = {LCM}")




## Program to check Armstrong Number

n=int(input("Enter the number"))

s=0

t=n

while t:

  d = t % 10

  s += d**3

  t = t // 10


if n==s:

  print('Armstrong Number')

else:

  print("Not an Armstrong Number")


## Program to calculate the power using recursion

def p(b,e):

  if e == 1:

    return b

  return b*p(b,e-1)


b=int(input("Enter the number:"))

e=int(input("Enter the exponent value:"))


r=p(b,e)


print(r)










Comments

Popular posts from this blog

Important Topics in Statistics for Data Sce

  Some important topics in Statistics: - Central Limit Theorem - Mean CLT Statement: For large sample sizes, the sampling distribution of means will approximate to normal distribution even if the population distribution is not normal. If we have a population with mean μ and standard deviation σ and take large random samples (n ≥ 30) from the population with replacement, then the distribution of the sample means will be approximately normally distributed. Why CLT is important? The field of statistics is based on fact that it is highly impossible to collect the data of entire population. Instead of doing that we can gather a subset of data from a population and use the statistics of that sample to draw conclusions about the population. In practice, the unexpected appearance of normal distribution from a population distribution is skewed (even heavily skewed). Many practices in statistics such as hypothesis testing make this assumption that the population on which they work is normall...