py2
#switch case
def fa(story):
match story:
case 1:
return "first one"
case 2:
return "secod one"
case 3:
return "third one"
case _:
return 'unknown one'
print(fa(1))
print(fa(2))
print(fa(3))
print(fa(4))
#o/p is:
first one
secod one
third one
unknown one
#try and catch method:
try:
first =int(input('Enter a number:'))
except Exception as e:
print(f'you should enter numbers only {e}')
print('thanks for your input')
#unique way
try:
a= int(input("Enter first number:"))
b=int(input("Enter second number:"))
except Exception as e:
print(f'you should enter numberss only')
if (b==0):
raise ZeroDivisionError ('program is not created for divison by zero')
print(f'your divison is: {a/b}')
#adding a list
ad = ['faizan', 'ayyan', 'azfaar']
new = []
for x in ad:
if 'i' in x:
new.append(x)
print(new)
#o/p is:
['faizan']
#list comprehension Tuesday
newlist = [expression for item in iterable if condition == Truehg = ['faizan','adil','sameer','umar']
new_list=[a for a in hg if a!='adil']
new_list1 =[b for b in range(10) if b<6]
new_list2 = [a.upper() for a in hg]
new_list3 = [a.lower() for a in hg]
print(new_list)
print(new_list1)
print(new_list2)
print(new_list3)
#o/p is:
['faizan', 'sameer', 'umar']
[0, 1, 2, 3, 4, 5]
['FAIZAN', 'ADIL', 'SAMEER', 'UMAR']
['faizan', 'adil', 'sameer', 'umar']
#we use list comprehension to reduce the code
hg = ['faizan','adil','sameer','umar']
new_list=[a for a in hg if a!='adil']
new_list1 =[b for b in range(10) if b<6]
new_list2 = [a.upper() for a in hg]
new_list3 = [a.lower() for a in hg]
new_list4 =[f if f!='adil'else 'khaja'for f in hg]
new_list5 =['faizan' for a in hg]
print(new_list)
print(new_list1)
print(new_list2)
print(new_list3)
print(new_list4)
print(new_list5)
#o/p is:
['faizan', 'sameer', 'umar']
[0, 1, 2, 3, 4, 5]
['FAIZAN', 'ADIL', 'SAMEER', 'UMAR']
['faizan', 'adil', 'sameer', 'umar']
['faizan', 'khaja', 'sameer', 'umar']
['faizan', 'faizan', 'faizan', 'faizan']
#sorting of a list
a= ['faizan','adil','sameer','umar']
b=[975,812,856,845]
a.sort(reverse=True)
a.sort()
b.sort()
print(a)
print(b)
c= ['faizan','adil','sameer','umar']
c.reverse()
print(c)
def lol(n):
return abs(n - 30)
list = [100, 50, 65, 82, 23]
list.sort(key = lol)
print(list)
#o/p is:
['adil', 'faizan', 'sameer', 'umar']
[812, 845, 856, 975]
['umar', 'sameer', 'adil', 'faizan']
[23, 50, 65, 82, 100]
#copy of a list
a= ['faizan','adil','sameer','umar']
b=a.copy()
c= list(a)
d=a[:3] #slicing
print(b)
print(d)
print(c)
#o/p is:
['faizan', 'adil', 'sameer', 'umar']
['faizan', 'adil', 'sameer']
['faizan', 'adil', 'sameer', 'umar']
class itera:
def __iter__(self):
self.b=1
return self
def __next__(self):
if self.b<=5:
x=self.b
self.b+=1
return x
else:
raise StopIteration
obj = itera()
iter =iter(obj)
for x in iter:
print(x)
#o/p is :
Running] python -u "c:\Users\faiza\OneDrive\Desktop\second.py\tempCodeRunnerFile.python"
1
2
3
4
5
[Done] exited with code=0 in 0.112 seconds
#In list
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
'''
note: In python there are 4 built in data types to store collection of data they are:
list, tuples, set, Dictionary
in tuple if there is a only one element we have to put comma otherwise it is not a tuple
constructor in list and tuple is = ((''))
'''
#if we to change this we can use list
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)
#o/p is:('banana', 'cherry')
#In tuples
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was found
#adding in a set
first_a= {'faizan','adil','sameer','umar'}
second_b={'abrar','khaja'}
third_c=['taher']
first_a.update(second_b,third_c)
print(first_a)
print(second_b)
print(third_c)
#o/p is:
'faizan', 'adil', 'khaja', 'sameer', 'abrar', 'umar', 'taher'}
{'abrar', 'khaja'}
['taher']
first_a= {'faizan','adil','sameer','umar'}
second_b={'abrar','khaja'}
first_a.remove('adil')
second_b.remove('abrar')
print(first_a)
print(second_b)
#o/p is:
{'faizan', 'sameer', 'umar'}
{'khaja'}
first_a= {'faizan','adil','sameer','umar'}
second_b={'abrar','khaja'}
third_c={'jack'}
f =first_a.pop()
second_b.clear() #shows that set()
del third_c #shows that no data
print(first_a)
print(second_b)
print(third_c)
#o/p is:
{'adil', 'umar', 'sameer'}
set()
Traceback (most recent call last):
File "c:\Users\faiza\OneDrive\Desktop\second.py\tempCodeRunnerFile.python", line 9, in <module>
print(third_c)
^^^^^^^
NameError: name 'third_c' is not defined
#wednesday
#The union() method returns a new set with all items from both sets.
first_a= {'faizan','adil','sameer','umar'}
second_b={'abrar','khaja'}
third_c={'jack'}
ans=first_a.union(second_b)
c=second_b|third_c
b=first_a.union(second_b,third_c)
e=first_a|second_b|third_c
third_c.update(second_b)#here the set added by the another set by update
print(ans)
print(c)
print(b)
print(e)
print(third_c)
#o/p is:
{'adil', 'sameer', 'abrar', 'faizan', 'umar', 'khaja'}
{'abrar', 'khaja', 'jack'}
{'adil', 'sameer', 'abrar', 'jack', 'faizan', 'umar', 'khaja'}
{'adil', 'sameer', 'abrar', 'jack', 'faizan', 'umar', 'khaja'}
{'abrar', 'khaja', 'jack'}
#itersection the values:first_a= {'faizan','adil','sameer','umar'}
second_b={'abrar','khaja','faizan'}
c= first_a.intersection(second_b)
#The intersection_update() method will also keep ONLY the duplicates, but it will change the original set instead of returning a new set.
first_a.intersection_update(second_b)
d=first_a &second_b
print(c)
print(d)
print(first_a)
one = {1,0,'umar','khaja','faizan'}
two={True,False,'faizan'}
three=one&two
print(three)
#o/p is:
{'faizan'}
{'faizan'}
{'faizan'}
{False, True, 'faizan'}
#difference of a set:
first_a= {'faizan','adil','sameer','umar'}
second_b={'abrar','khaja','faizan'}
c= first_a.difference(second_b)
d=first_a-second_b
#The difference_update() method will also keep the items from the first set that are not in the other set, but it will change the original set instead of returning a new set.
first_a.difference_update(second_b)
e=first_a.symmetric_difference(second_b)
f=first_a^second_b
first_a.symmetric_difference_update(second_b)
print(c)
print(d)
print(first_a)
print(e)
print(f)
print(first_a)
first_a.symmetric_difference_update(second_b)
#o/p is :
{'adil', 'umar', 'sameer'}
{'adil', 'umar', 'sameer'}
{'abrar', 'khaja', 'sameer', 'faizan', 'adil', 'umar'}
{'abrar', 'khaja', 'sameer', 'faizan', 'adil', 'umar'}
{'abrar', 'khaja', 'sameer', 'faizan', 'adil', 'umar'}
{'abrar', 'khaja', 'sameer', 'faizan', 'adil', 'umar'}
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Shortcut Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() - Returns a set containing the difference between two or more sets
difference_update() -= Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() & Returns a set, that is the intersection of two other sets
intersection_update() &= Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() <= Returns whether another set contains this set or not
< Returns whether all items in this set is present in other, specified set(s)
issuperset() >= Returns whether this set contains another set or not
> Returns whether all items in other, specified set(s) is present in this set
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() ^ Returns a set with the symmetric differences of two sets
symmetric_difference_update() ^= Inserts the symmetric differences from this set and another
union() | Return a set containing the union of sets
update() |= Update the set with the union of this set and others
a=fa['name']
b=fa.get('age')
print(fa)
print(a)
print(b)
#adding a new key to the dictionary
c=fa.keys()#only prints key value
print(c)
fa['marrks'] = 975
print(c)
print(fa)
#o/p is:
{'name': 'faizan', 'age': 18, 'clg': 'MBU'}
faizan
18
dict_keys(['name', 'age', 'clg'])
dict_keys(['name', 'age', 'clg', 'marrks'])
{'name': 'faizan', 'age': 18, 'clg': 'MBU', 'marrks': 975}
#deleting a dictionary
fa.update({'rollno': 779})
print(fa)
fa.pop('rollno')
fa.popitem()#popitem keyword is used for deleting item
print(fa)
ab={
'name':'adil',
'age':18,
'clg':'MBU'
}
del ab['age']
print(ab)
ab.clear()
print(ab)
#o/p is:
{'name': 'faizan', 'age': 18, 'clg': 'MBU', 'rollno': 779}
{'name': 'faizan', 'age': 18}
{'name': 'adil', 'clg': 'MBU'}
{}
#loop in dictionary
fa={
'name':'faizan',
'age':18,
'clg':'MBU'
}
for a in fa.keys():
print(a)
for b in fa.values():
print(b)
for c,d in fa.items():
print(c,d)
#o/p is:
name
age
clg
faizan
18
MBU
name faizan
age 18
clg MBU
#thursday
# copy of a dictionary
fa={
'name':'faizan',
'age':18,
'clg':'MBU'
}
op=fa.copy()
pp=dict(fa)
print(op)
print(fa)
print(pp)
#o/p is :
{'name': 'faizan', 'age': 18, 'clg': 'MBU'}
{'name': 'faizan', 'age': 18, 'clg': 'MBU'}
{'name': 'faizan', 'age': 18, 'clg': 'MBU'}
#nested dictionary:myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
#o/p is:
'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
last = {
'fa':child1,
'af':child2,
'fl':child3
}
print(last['fl']['name'])
print(last)
for a,object in last.items():
print(a)
for b in object:
print(b+':',object[b])
#o/p is:
inus
{'fa': {'name': 'Emil', 'year': 2004}, 'af': {'name': 'Tobias', 'year': 2007}, 'fl': {'name': 'Linus', 'year': 2011}}
fa
name: Emil
year: 2004
af
name: Tobias
year: 2007
fl
name: Linus
year: 2011
#while loop:
a=int(input('Enter a number:'))
while a<=a:
a+=1
if a==9:
break
print(a)
#o/p is:
Enter a number:5
6
7
8
#loop in break
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
#If the loop breaks, the else block is not executed.
#o/p is:
0
1
2
1
2
# Nested loops:
ab=['Raees','mohammed']
fa=['faizan','ayyan','azfaar']
for a in ab:
for b in fa:
print(a,b)
#o/p is:
Raees faizan
Raees ayyan
Raees azfaar
mohammed faizan
mohammed ayyan
mohammed azfaar
#friday
#arguement:
def my_function(self):
for x in self:
print(x)
fa=['faizan','is','great']
my_function(fa) #we are calling a function tr runs through loop
print(fa)#in this we get the entire list
#o/p is:
faizan
is
great
['faizan', 'is', 'great']
#recursion is:def re(a):
if a>0:
fa= a + re(a-1)
print(fa)
else:
fa=0
return fa
print('Recursion is:')
print(re(int(input('Enter the number:'))))
#o/p is:
Recursion is:
Enter the number:5
1
3
6
10
15
15
#only return the value
def re(a):
if (a>0):
return a+re(a-1)
else:
return 0
print('Recursion is:')
print(re(5))
#o/p is:
ecursion is:
15
#factorial of numbers by using recursion and user interaction:
def re(a):
if a==0:
return 1
else:
return a*re(a-1)
num=int(input("Enter the number:"))
print(f'The number is {num} and factorial of this is {re(num)} ')
#o/p is:
Enter the number:5
The number is 5 and factorial of this is 120
#By using for loop:
def re(a):
if a==0:
return 1
else:
return a*re(a-1)
for n in range (1,7):
ans = re(n)
print(f'The number is {n} and factorial of this is {ans} ')
#o/p is:
The number is 1 and factorial of this is 1
The number is 2 and factorial of this is 2
The number is 3 and factorial of this is 6
The number is 4 and factorial of this is 24
The number is 5 and factorial of this is 120
The number is 6 and factorial of this is 720
#another method:
def af(num):
if num==1 or 0:
return 1
else:
return num*af(num-1)
b=int(input('Enter where to print factorial of a number:'))
for i in range(1,b+1):
ans=af(i)
print(f'The factorial of {i} is {ans}')
#o/p is:
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6
The factorial of 4 is 24
The factorial of 5 is 120
#we use lambda which takes any arguement:
def fa(n):
return lambda a:a*n
first = fa(10)
print(first(2))
#o/p is:
20
#inheritance in py
class inh: #parent class
def __init__(self,name,age):
self.name=name
self.age=age
def fa(self):
print(f' Name is {self.name},and the age is {self.age}')
class child(inh): #child class
pass
a=inh('faizan',18)
a.fa()
#o/p is:
Name is faizan,and the age is 18
#overiding inheritanceclass inh: #parent class
def __init__(self,name,age):
self.name=name
self.age=age
def fa(self):
print(f'Name is {self.name},and the age is {self.age}')
class child(inh): #child class
def __init__(self,name,clg):#child class overides the parent class attributes
self.name=name
self.clg=clg
def af(self):
print(f'Name is {self.name},and clg is {self.clg}')
a=inh('faizan',18)
b=child('adil','MBU')
a.fa()
b.af()
#o/p is:
Name is faizan,and the age is 18
Name is adil,and clg is MBU
# child class will not overide
class inh: #parent class
def __init__(self,name,age):
self.name=name
self.age=age
def fa(self):
print(f'Name is {self.name},and the age is {self.age}')
class child(inh): #child class
def __init__(self,name,age):#child class will not override by this method
inh.__init__ (self,name,age)
a=child('faizan',18)
a.fa()
#o/p is:
Name is faizan,and the age is 18
class inh: #parent class
def __init__(self,name,age):
self.name=name
self.age=age
def fa(self):
print(f'Name is {self.name},and the age is {self.age}')
class child(inh): #child class
def __init__(self,name,age):#child class will not override by this method
super().__init__ (name,age) # super method is used for inherit all the methods
a=child('faizan',18)
a.fa()
#o/p is:
Name is faizan,and the age is 18
#adding methods and property:
class inh: #parent class
def __init__(self,name,age):
self.name=name
self.age=age
def fa(self):
print(f'Name is {self.name},and the age is {self.age} and year is {self.year}')
class child(inh): #child class
def __init__(self,name,age,year):#child class will not override by this method
super().__init__ (name,age)# super method is used for inherit all the methods
self.year=year # adding property
def clg(self):#adding new method
print(f'Name is {self.name},and the age is {self.age} and year is {self.year}')
a=child('faizan',18,2024)
print(f'second year of clg is {a.year}')#printing the property
a.clg() #calling new method
#o/p is:
second year of clg is2024
Name is faizan,and the age is 18 and year is 2024
def fa():
a ='adil'
def af():
nonlocal a #non local is used in nested and takes outer function
a='faizan'
af()
return a
print(fa())
#o/p is:
faizan
#importing time
import datetime
a=datetime.datetime.now()
print(a)
x = datetime.datetime.now()#present time
y= datetime.datetime(2022,2,14)#creating object of time
print(y)
print(x.year)
print(x.strftime("%A"))#for declaring month and year
#o/p is:
2024-08-10 11:09:19.705522
2022-02-14 00:00:00
2024
Saturday
#maths in py
a=min(5,25,625)#minimum
b=max(5,25,625)#maximum
c=pow(5,2)#power of a number
print(a)
print(b)
print(c)
import math
d=math.sqrt(625)
e=math.ceil(2.8)#takes uo value
f=math.floor(2.4)#takes down value
g=math.pi
print(d)
print(e)
print(f)
print(g)
#o/p is:5
625
25
25.0
3
2
3.141592653589793
#monday
#Regular expressionimport re
af = "faizan is great"
a = re.search("^faizan.*great$", af)
if a:
print('yes')
else:
print('no')
line='The Himalayas are great and famous '
new_line='There are heavy rains in adoni'
y=re.search(r'\bT\w+',new_line)
'''
\b: This is a word boundary anchor. It matches the position between a word character (like a letter, digit, or underscore) and a non-word character (like a space or punctuation).
T: This matches the letter “T” literally.
\w+: This matches one or more word characters (letters, digits, or underscores).
'''
b=re.findall('are',line)
c=re.search('The',line)
d=re.search('\s',line)
e=re.split('\s',line)
f=re.split('\s',line,2)
print(b)
print(c)
print(f'loction of first whitespace {d.start()}')
print(e)
print(f)
print(y.span())#It prints start and end position
print(y.string)#It prints all the string
print(y.group())#It prints upper case only mentioned in the code
#o/p is:
yes
['are']
<re.Match object; span=(0, 3), match='The'>
loction of first whitespace 3
['The', 'Himalayas', 'are', 'great', 'and', 'famous', '']
['The', 'Himalayas', 'are great and famous ']
(0, 5)
There are heavy rains in adoni
There
#tuesday
#logic building#swap of two numbers by user input
def fa():
a= int (input("Enter first number:"))
b=int(input("Enter second number:"))
temp=a
a=b
b=temp
print(a)
print(b)
fa()
#o/p is:
def fa():
a= int (input("Enter first number:"))
b=int(input("Enter second number:"))
temp=a
a=b
b=temp
print(a)
print(b)
fa()
# changing first and last element in list
def swap(list):
size =len(list)
third = list[0]
list[0]=list[size-1]
list[size-1]=third
return list
list=[25,32,45,98,625]
print(swap(list))
#o/p is:
[625, 32, 45, 98, 25]
#another apporach
def swapList(list):
list[0],list[-1]= list[-1],list[0]
return list
list=[1,2,3,4,5]
print(swapList(list)) def swapList(list): list[0],list[-1]= list[-1],list[0] return list list=[1,2,3,4,5] print(swapList(list))
#friday
# NOTE:For infinite times we use this
a='faizan'
while True:
print(a)
third()
#functions:
def list_benefits():
return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
return "%s is a benefit of functions!" % benefit
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
name_the_benefits_of_functions()
#o/p is :
More organized code is a benefit of functions!
More readable code is a benefit of functions!
Easier code reuse is a benefit of functions!
Allowing programmers to share and connect code together is a benefit of functions!
#unique code by functions:
def first():
return" faizan is great "
def second(self):
return' %s faizan codes in python '%self
def third():
ed=first()
for a in ed:
print( second(a))
third()
#o/p is:
faizan codes in python
f faizan codes in python
a faizan codes in python
i faizan codes in python
z faizan codes in python
a faizan codes in python
n faizan codes in python
faizan codes in python
i faizan codes in python
s faizan codes in python
faizan codes in python
g faizan codes in python
r faizan codes in python
e faizan codes in python
a faizan codes in python
t faizan codes in python
faizan codes in python
#printing only positive numbers:
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = []
for num in numbers:
if num >= 0:
newlist.append(num)
print(newlist)
#o/p is:[34.6, 44.9, 68.3, 44.6, 12.7]
#another method of printing positive numbers
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(a) for a in numbers if a>=0]
print(newlist)
#o/p is:
[34.6, 44.9, 68.3, 44.6, 12.7]# using lambda function:
'''
in py we define a function but lambda has Now instead of defining the function somewhere and calling it, we can use python's lambda functions, which are inline functions defined at the same place we use it. So we don't need to declare a function somewhere and revisit the code just for a single time use.
#printing true for even numbers:
l = [2,4,7,3,14,19]
for i in l:
use_lambda = lambda a :a%2==0
print(use_lambda(i))
#o/p[ is:
True
True
False
False
True
False
#printing false for odd numbers :
l = [2,4,7,3,14,19]
for i in l:
use_lambda = lambda a :a%2==1
print(use_lambda(i))
#o/p is:
False
False
True
True
False
True
#monday
#We have a class defined for vehicles. Create two new vehicles called car1 and car2. Set car1 to be a red convertible worth
#$60,000.00 with a name of Fer, and car2 to be a blue van named Jump worth $10,000.00.
# define the Vehicle class
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
# your code goes here
car1=Vehicle()
car1.name='Fer'
car1.color='red'
car1.kind='convertiable'
car1.value=60000
car2=Vehicle()
car2.name='Jump'
car2.color='blue'
car2.kind='van'
car2.value=10000
# test code
print(car1.description())
print(car2.description())
#o/p is:
Fer is a red convertiable worth $60000.
Jump is a blue van worth $10000.
'''
class fa:
name='faizan'
def hg(self):
print('This is inside the class')
class af(fa):
des='It prints fa and af by inheritance'
obj =af()
print(obj.name)
obj.hg()
print(obj.des)
#o/p is:
faizan
This is inside the class
It prints fa and af by inheritance
#multiline functions:
def fa(first,second,third, **last):
if last.get('faizan')=='first':
print(f'faizan got marks:{first+second+third}')
if last.get('umar')=='second':
last=800
return last
result=fa(900,70,5, faizan='first',umar='second')
print(f'umar Result is:{result} ')
#o/p is:
aizan got marks:975
umar Result is:800
#another method:def bar(first, second, third, **options):
if options.get("action") == "sum":
print("The sum is: %d" %(first + second + third))
if options.get("number") == "first":
return first
result = bar(1, 2, 3, action = "sum", number = "first")
print("Result: %d" %(result))
#o/p is:The sum is: 6
Result: 1
# edit the functions prototype and implementation
def first(a, b, c, *args):
return len(args)
def second(a, b, c, **kwargs):
return kwargs["magicnumber"] == 7
# test code
if first(1, 2, 3, 4) ==1:
print("Good.")
if first(1, 2, 3, 4, 5) ==2:
print("Better.")
if second(1, 2, 3, magicnumber=6) == False:
print("Great.")
if second(1, 2, 3, magicnumber=7) == True:
print("Awesome!")
#o/p is:
Good.
Better.
Great.
Awesome!
# edit the functions prototype and implementation
def first(a, b, c, *args):
return (args) #by not using it will not work
def second(a, b, c, **kwargs):
return kwargs["magicnumber"] == 7
# test code
if first(1, 2, 3, 4) ==1:
print("Good.")
if first(1, 2, 3, 4, 5) ==2:
print("Better.")
if second(1, 2, 3, magicnumber=6) == False:
print("Great.")
if second(1, 2, 3, magicnumber=7) == True:
print("Awesome!")
#o/p is:
Great.
Awesome!
def first(a, b, c, *args):
return (args) #by not using it will not work
def second(a, b, c, **kwargs):
return kwargs["magicnumber"] == 7
# test code
if first(1, 2, 3, 4):#it will print because of the absence of length
print("Good.")
if first(1, 2, 3, 4, 5):
print("Better.")
if second(1, 2, 3, magicnumber=6) == False:
print("Great.")
if second(1, 2, 3, magicnumber=7) == True:
print("Awesome!")
#o/p is:
Good.
Better.
Great.
Awesome!
#Tuesday hacker rank
if __name__ == '__main__':
n = int(input())
i=1
while i<=n:
if (i<=n and n<=150):
print(str(i),end='')
i += 1
#o/p is:
3
123
# second larget value:
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
a=list(set(arr))
a.sort(reverse=True)
print(a[1])
#o/p is:
5
1 2 3 4 5
4
#another method
lst = []
n = int(input("Enter the number of elements: "))
for i in range(n):
ele = int(input("Enter an element: "))
lst.append(ele)
lst.sort(reverse=True)
print(lst)
print(lst[1]) #list comphernsion in one line:
name = input()
vowel="aeiouAEIOU"
lis_comp=[b for b in name if b in vowel]
print(lis_comp)
#o/p is:
[a,i,a]
#prime number:
#By taking user input
def fa(no):
if no<=1:
return False
for i in range(2,no):
if no%i==0:
return False
else:
return True
no=int(input("Enter number:"))
print(fa(no))
#o/p is:
Enter a number:5
True
#Built in input:
def fa (no):
if no<=1:
return False
for i in range(2,no):
if no%i==0:
return False
else:
return f" {True} it is a prime number"
print(fa(3))
#o/p is:
True it is a prime number
#By using oops
class fa:
atr='faizan'
print(f'By using class the output is {fa.atr}')
obj=fa()
print(f'By using objectthe output is {obj.atr}')
#o/p is:
By using class the output is faizan
By using objectthe output is faizan
#another method for prime by user input:num_a=int(input("Enter a number:"))
if num_a<=1 :
print ('Give another number which is greater than 1')
else:
for i in range(2,num_a):
if num_a%i==0:
print('Not a prime number')
break
else:
print('Prime number')
#o/p is:
Enter a number:3
Prime number
#list comprehension:
a=[1,2,'faizan','ayyan',3,'azfaar',4]
string =[b for b in a if type(b)==str]
num=[c for c in a if type(c)==int]
print(f'strings are: {string}')
print(f'integers are: {num}')
#o/p is:
strings are: ['faizan', 'ayyan', 'azfaar']
integers are: [1, 2, 3, 4]
#for add and even in a list:
#a=[1,2,3,4,5,6,7,8,9,]
a=[i for i in range(10)]
b= [num for num in a if num%2==0]
c=[nu for nu in a if nu%2!=0]
print(a)
print(f'Even numbers are:{b}')
print(f'Odd numbers are:{c}')
#o/p is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
even numbers are:[0, 2, 4, 6, 8]
odd numbers are:[1, 3, 5, 7, 9]
Comments
Post a Comment