In [ ]:
var=10 #(Ture)
var #(FALSE)
In [ ]:
val=int(input("enter the no 1"))
#val=int(val)
val2=int(input("enter the no 2"))
print(val)
print(val2)
c=val+val2
print(c)
print(type(val))
In [ ]:
"""
#synatx
if(cond):
print("hello")
print("hello")
"""
#condtion statements
#simple if
numb=int(input("enter the value"))
var=int(input("enter the value two"))
if(numb>var):
print("yeah ! number is numb and var are not same")
print("cod2")
print("cod3")
print("Done")
In [ ]:
#if else condition:
"""
if(condtion):
statments 1...n
else:
statements 1 ... n
"""
numb=input("enter the session")
#var=int(input("enter the value two"))
if(numb=="morning"):
print("yeah good morning ! have a good start")
else:
print("plz complete the work first")
print("Done")
In [ ]:
#if elseif else
numb=int(input("enter the value"))
var=int(input("enter the value two"))
if(numb>var):
print("yeah ! number is numb and var are not same")
elif(numb<var):
print("num is less than var")
else:
print("we need to do something")
print("Done with the code")
In [ ]:
name="datascience"
#0 1 2....12
#val='1''2'
"""
syntax :
=======
for temp in seq:
print("statements")
"""
for char in name:
print(char)
print("Done")
In [ ]:
numberlist=[10,20,30]
numsum=0
for num in numberlist:
#numberr=0
print("Number ", num)
numsum+=num
#number+=num
print("After summing", numsum)
#print("the value of number",number)
#print(numberr)
print("outside summing", numsum)
print("Done")
In [ ]:
#while
num=10
i=1
sum=0
while i<=num: #i=10 num=10
print("value of i",i)
sum=sum+i
i=i+1
print("print the value of sum",sum)
print("after i+1 value of i",i)
print("sum value",sum)
#string ="hello" or list=["names","hello"],tuple=("names","hello")
In [ ]:
#break
name="bring"
for val in name:
if val == "i":
break
print("hello")
print(val)
print("The end")
In [ ]:
#continue
for val in "bring":
if val == "i":
continue
print(val)
print("The end")
In [ ]:
#someone one to develop the code
sequence = 'pass'
for val in sequence:
#developer need to develop the logit
pass
In [ ]:
print("hello")
type(1.5)
In [ ]:
"""
syntax :
def function_name():
statements
return val (optional)
"""
In [ ]:
#simple function
def myname(name):
"""prints out my name """
print("my name "+name+" good morning to all")
#myname("dilip")
myname("python","hello")
#print(myname.__doc__)
In [ ]:
def addi(a,b):
c=a+b
print("add of two numbers in function ",c)
return c
result=addi(2,3)
print("result",result)
In [ ]:
#return function example
num=-10
def abus_no(num):
if (num>0):
print("abus_no")
return num
else:
return -num
number=abus_no(num)
print(number)
In [ ]:
#scope
x=10
y=20
total=0
def sum(a,b):
total=a+b
print("total inside the method ",total)
return total
tot=sum(x,y)
print(total)
print(tot)
In [ ]:
# Types of functions : Build in functions and user defined functions
# Assignment : Simple Calculator by Making Functions.
In [ ]:
#function arugment types
#Required Args
def sayhello(name,msg):
print("Hello",name +", " +msg)
In [ ]:
sayhello("good morning","dilip")
In [ ]:
#Keyword arguments
def sayhello(name="datascience",msg="good morning"):
print("Hello",name +"," +msg)
sayhello(msg="gm",name="dilip")
In [ ]:
#Default arguments
def sayhello(name,msg="good morning"):
print("Hello",name +"," +msg)
sayhello("dilip")
In [ ]:
def manyarg(*names):
print(names)
return names
names=manyarg("dilip","python","sonal")
type(names)
In [ ]:
#nested if
marks=58
if(marks>=90):
print("you got A grade")
elif(marks>=80):
print("you got B grade")
elif(marks>=60):
print("you got c grade")
else:
print("you failed in the exam")
print("you have to take the exam once again")
print("Thank-you")
In [ ]:
#lamda functions
doubele=lambda x:x*5
print(doubele(5))
In [ ]:
from fractions import Fraction as F
# Output: 2/3
print(F(1,3) + F(1,3))
# Output: 6/5
print(1 / F(5,6))
# Output: False
print(F(-3,10) > 0)
# Output: True
print(F(-3,10) < 0)
In [ ]:
import math
# Output: 3.141592653589793
print(math.pi)
# Output: -1.0
print(math.cos(math.pi))
# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))
In [ ]:
import random
# Output: 16
print(random.randrange(10,20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
In [ ]:
(1.1 + 2.2) == 3.3
1.1+2.2
In [ ]:
from decimal import Decimal as D
# Output: Decimal('3.3')
print(D('1.1') + D('2.2'))
# Output: Decimal('3.000')
print(D('1.2') * D('2.50'))
In [ ]:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
# nested list
In [ ]:
my_list = ['D','i','l','i','p']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Error! Only integer can be used for indexing
#my_list[5]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
#print(n_list[0][4])
# Output: 5
print(n_list[1][3])
In [ ]:
### Negative Indexing :
my_list = ['D','a','t','a','e']
# Output: e
print(my_list[-2])
# Output: p
print(my_list[-5])
In [ ]:
my_list = ['p','r','o','g','r','a','m','i','e']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
In [ ]:
#update elements
# mistake values
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
In [ ]:
my_list = [3, 8, 1, 6, 0, 8, 4]
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
In [ ]:
#deleting
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
# delete multiple items
del my_list[1:5]
# Output: ['p', 'm']
print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)
In [ ]:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'o'
print(my_list.pop(1))
my_list.clear()
my_list
In [ ]:
fruits=["apple","mango"]
for fru in fruits:
print("fruits in my list",fru)
In [ ]:
import math
dir(math)
In [ ]:
a=2+3j
type(a)
In [ ]:
a=2
complex(a)
In [ ]:
firstlist=["names","cars",]
type(firstlist)
firsttuple=("names","cars","sonal","python")
type(firsttuple)
for t in firsttuple:
print("names inside the tuple:",t)
firstlist[0]="dilip"
firstlist
#firsttuple[0]="names"
firsttuple[1:3]
In [ ]:
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
In [ ]:
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
In [ ]:
str = 'cold'
#character count
print('len(str) = ', len(str))
In [ ]:
#Iterating Through String:
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
In [ ]:
#Iterating Through String:
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
In [ ]:
#Iterating Through String:
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
In [ ]:
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed data types
my_set = {1.0, "Hello", (1, 2, 3),25}
print(my_set)
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
#my_set = {1, 2, [3, 4]} #mutable list doesn't contain
#my_set = set([1,2,3,2])#making set form list
type(my_set)
In [ ]:
# initialize my_set
my_set = {1,3}
print(my_set)
# if you uncomment line ,
# you will get an error
# TypeError: 'set' object does not support indexing
#my_set[1:]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)
# add list and set
In [ ]:
for t in my_set:
print ("hello",t)
In [ ]:
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(10)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(10)
print(my_set)
In [ ]:
my_dict = {'name':'pyboy', 'hi':'pyboy','age': 30}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
In [ ]:
my_dict = {'name':'Jack', 'age': 26}
print(my_dict)
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
In [ ]:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
#print(i)
print(i,squares[i])
In [ ]:
#file_object = open(“filename”, “mode”)
file=open("C:/Users/SHAIK NAWAAZ/Desktop/python/text.txt","w")
#print(file)
#print(type(file.read()))
#print(file.read())
#print(file.seek(0))
file.write("we added data to the file")
print("read again")
#print(file.read())
#print(file.tell())
#print(file.readline())
#print(file.readlines())
file.close()
In [ ]:
import math as m
In [ ]:
m.pi
In [ ]:
import os as o
In [ ]:
o.pi
In [ ]:
class Egclass:
#def __init__(self):
#print ("in init")
a=50
def myprint(self):
print("hello to oops")
print(Egclass.a)
#Egclass.myprint()
ob=Egclass()
ob.myprint()
In [ ]:
import matplotlib.pyplot as plt
In [ ]:
#simple line example
#co-ordinates as (1,5),(2,7),(3,4)
plt.plot([1,2,3],[5,7,4])
In [ ]:
plt.show()
In [ ]:
#using pyplot and numpy as single package or module
from pylab import *
plot([1,2,3,4])
show()
In [ ]:
from pylab import *
lines = plot([1,2,3],'b-',[0,1,2],'r--')
#legend(lines, ('First','Second'))
#savefig('legend')
show()
In [ ]:
#line 1
x = [1,2,3]
y = [5,8,9]
#line 2
x2 = [1,2,3]
y2 = [15,12,13]
#label is the attribute used to name a line
plt.plot(x, y, label='First Line')
plt.plot(x2, y2, label='Second Line')
#plt.legend()
#xlabel and ylabel are used to name the axis
plt.xlabel("Plot no's")
plt.ylabel("variance")
#title is used to name the graph
plt.title('Two line Graph')
#legend is used to show the line_names
#plt.legend()
plt.show()
In [ ]:
import matplotlib.pyplot as plt
In [9]:
#bars
#reading the list of values as x1,y1
plt.bar([1,3,5,7,13],[5,2,7,8,6], label="BarEg one")
#reading the list of values as x2,y2
plt.bar([2,4,12,8,10],[8,6,3,5,7], label="BarEg two", color='g')
plt.legend()
#naming the x,y axis
plt.xlabel('number')
plt.ylabel('height of bar')
#naming the graph
plt.title("Bar")
#showing the plot
plt.show()
In [10]:
#histogram
#ages as list of elements
ages = [15,22,55,62,45,21,22,34,43,42,4,99,102,110,120,121,122,125,111,115,112,80,75,65,54,44,43,42,48]
#in between
bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]
plt.hist(ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('ages in btw')
plt.ylabel('age bar')
plt.title('histogram of bar')
#plt.legend()
plt.show()
In [12]:
#scatter plot
x = [1,2,3,4,5,6,7,8]
y = [5,2,4,2,1,4,5,2]
plt.scatter(x,y, label='scatter', color='b', s=55, marker="o")
plt.xlabel('x')
plt.ylabel('y')
plt.title('scatter Graph')
plt.legend()
plt.show()
In [13]:
#stack-plot
days = [1,2,3,4,5]
sleep = [7,8,6,11,7]
eat = [2,3,4,3,2]
work = [7,8,7,2,2]
play = [8,5,7,8,13]
plt.plot([],[],color='c', label='sleep', linewidth=5)
plt.plot([],[],color='m', label='eat', linewidth=5)
plt.plot([],[],color='k', label='work', linewidth=5)
plt.plot([],[],color='r', label='play', linewidth=5)
plt.stackplot(days, sleep,eat,work,play, colors=['c','m','k','r'])
plt.xlabel('x')
plt.ylabel('y')
plt.title('stackplot Graph')
plt.legend()
plt.show()
In [16]:
#pie-plot
slices = [8,12,2,9]
activities = ['skyblue','violet','red','blue']
cols = ['c','m','r','b']
plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow= False,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('pie graph')
plt.show()
In [ ]: