0% found this document useful (0 votes)
3 views20 pages

Python Imp Coding

Uploaded by

psamiksha865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Python Imp Coding

Uploaded by

psamiksha865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
program 1(a): Create a program that asks the user to enter their name and their age. Print out a m g 7 essage addressed to them that tells them the year that they will turn 100 years old. ae a ane =inpat (Enter your name: ") age = ning’ Enter your age-*)) year= st(Q017 - age}#100)" L— prnk(name +" willbe 100 years old in the year "+ year) output “nb ten Shed en ee ee >> Enter your name: ‘swam! wo Enter your age: 30 suvama wil be 100 years ofd in the year 2087 So ing (BSC-T- MU) Ps Practica’s > Program 1(f): Write a recursive function to print the factorial for a given number. ferecta): p ea fnat: return A else: return ni*rec(n-1) pum=7 nud: print(“factorial does not exist for negative numbers”) elif num=—=0: print(“the factorial of 0 is 1”) else: print(“the factorial of’,.num,“is”,rec(num)) Output [rhe factorial of 7455040 SY write a functio: also write the function for Palindrome. G0 n= input(‘Enter Number to check for Armstrong!) d= input(Your Entered number fs of how many digits’) fen s-0 while(fl=0): “aef%10 fef/10 s=s+(a**d) if(s——n): print(' else: ed is a armstrong number’ Yen) _ print(‘%d fs not a armstrong number! %n) n to check the Input value Is Armstrong and Output >>> As() s Enter Number to check for Armstrong153 Your Entered number fs of how many digits3 153 {s a armstrong number >>> As() Enter Number to check for Armstrong121. Your Entered number fs of how many digits3 121 {s not a armstrong number a): Write a function that takes a character 1) and returns True if it is a vowel, False er is Vov 2. Python Comparison Operators The comparison operators are also known as relational ae wa in éPerators compare the values on either sides of them and decide the relatio, among them, z Table 1.6.2 | Operator | ey If the values of two oper: true, Is If values of two operands are not equal, then condition becomés true, <> If values of two operands are not equal, then condition becomes true, > If the value of left operand is greater than the value of right operand, then condition becomes true. < If the value of left operand is less than the value of right operarid, then condition becomes true. >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. = If the value of left operand is less than or equal to the value of right operand, then condition becomes true. on Programming (BSC-IT- MU) Introd a and b are equal") - '@ and b are not equal") greater than b") not greater than b") less than b") print("3. not less than b"} if (a!=b): not equal b") equal b") a ptions >> Listi3]= -viclet= >>> print (listi3i) Syllabus Topi l 322 initializing Values of List = How to Initialize the values of lists 2 You can initialize a list variable by assigning the empty list to it. The following example initializes the empty string. 3.23 Accessing the Elements of List ES _ Howto access elements of list To access the elements of the list use the square brackets for slicing along with the index to get the value available at that index. The following example shows how the elements are accessed from the list. You can access a single element by specifying its index or you can access the range of elements by giving range as shown in example. Syllabu 3.6 Tuples 5 Explain wpies indetail cs 3.6.1 Immutable Concept Tuples are the immutable sequence data typ e. Immutable means once Y create the immutable data types the contents of these changed. data types cannot | Tuples are used to store the heterogeneous data, for example two tuple: generated by enumerate(Q built in function. You can also use tuple when the immutable sequence of homogeneous data is needed like storing data in a set. List Tupl, Ditonaron ang, Python Programming (BSC: Tuples are declared in following ways : 1. You can declare the empty tuple by using the pair of parentheses: () 2. You can use the trailing comma for the single value tuple: a, or(a,) 8. Separate the tuple item by using the comma: a, b, c or (a, b, ©) 4. You may also use the built in tuple function : tuple() or tuple (iterable) Tuple creation — Creating tuple is a very easy as you have to put different comma separate, values. You can create a tuple by using parenthesis or without parenthesis, ‘yellow', up. "green', 'blue', >>> tuple2 = (7538, 3437, 2736) >>> tuple3=('d','t!,!m',!n') >>> print (tuple) ('red', 'green', "blue', 'yellow', '1234') >>> print (tuple2) (7538, 3437, 2736) ~ >>> print (tuple3) erat, tt', om, tne) >>> 1 ; a : wane 5 2 msc. vy 219 Liste, Tuptes, Oxcionarins art Fes Tuple Initialization You can create an empt; . . 'y just i i e follow! example shows empty tuple, by putting the parenthesis. The following _ Example : Empty tuple >>> print (emptytupie) oO 4 - You can initialize a tuple a single value, it means your tuple may contain a single value as shown in the following example. - Example : Tuple with a single value : ~ ae [Frac eae Shes > ~ >>> onevaluetuple=(45) >>> print (onevaluetuple) 45 Syllabus Topic : Accessing the Elements in Tu | 3.6.2 Accessing the Elements in A Tuple - To access the elements in the tuple, you have to use the square brackets for slicing along with the index, to get the value present at that index. - The following example shows how you can access a single value as well as a range of values by using the colon [:] s - Example : Accessing the tuple elements Reset: tuplei=('red', ‘green’, 'blue', 11234") |tuple2 = (7538, 3437, 2736) print ("tuple[o] : ", tuple1[0]) print ("tuple[2] : ", tuple2[2]) print(" first 3 values of tuple tuple[0} : red one n', ‘blue') Fai values of tuple : ('zed!, ‘green’, >>I Delete Tuple Elements ove the individual tuple element. So delete the ony - It is not possible to rem tuple. 12, tat, 'edya >>> tupa |e 2, tat, retyary ]>>> dear tupa J>s> } | T¥aceback (most recent call last): | Fite "", line 1, in : | tupa NameError: name J>>>1 ‘tup4' 4s not defined Syllabus Topic : Tuple Assign | 3.6.3 Tuple Assignment us _Howtoassignatuple? Tuple assignment is used to assign the values to the variable. The following example illustrates the tuple assignment by swapping the two numbers. Faieon se ny i ile _ Fan Shall _Orbug "Options Windows Hep 33> 3 33> temp—a 335 aco 333. Botemp S35 Sos 3, 3s the dit utable data types- Each key available in nary e colon (:). d by using a comma G - Dictionaries are the m is separated from its value by using th - The items of the dictionary are separates ing is enclosed in curly braces. . - nn can create an empty dictionary by simply writing two curly braces, like this : {}. | 3.9.1 Concept of Key-Value Pair — Dictionaries are indexed by the keys and the keys are of any immutable data as keys provided all the keys ) and the enti, type like number and strings. You can use tuple are only numbers, strings or tuples. — Lists cannot be used as keys because lists can be modified in place using index assignments. Dictionary is an unordered list of key : Value pairs with the unique key values. ‘The { } braces are used to create an empty dictionary. 2.02, Lists, Tuptes, Otto Fite In the dictionary are not unique. the koy, SYS Are Unique but the valuea asalgned to thoae keys The values are of any 4 type like tuple, number and sui in the dictionary are immutable data # value pair within ( } braces adds Beit Set 4 pe weep >> mydict=t tape >>> my@icti= (onan poe mratet2= dict((1 : sappier, 2:tbalie, g:ccaty BF ree SMEG, appieny) 2, epaiggy Fant, a: texte (2: (3, 4, 51, tnamet: teres) >>> mydict2 (2: tapple', 2: “balls, 3: teats) >>> mydict3 (2: ‘apple’, 2: "paras >>> 3.9.3. Initializing a Dictionary To create an empty dictionary use the { } braces. The following example shows now to create an empty dictionary. | [Fete eae Shell = Debug | Options | Windows. >>> myaict=0) yon Programming (BSC.1T- muy 329 tise Tuples, Dore Lists, Tuples_ Octo SEC en ey eee 3.9.6 Delete Dictionary Elements __- The del statement is used to delete the entire directory. - It is also possible to delete individual dictionary elements as well as the entire contents of a dictionary. You can also delete entire dictionary in a single operation. _- Following example illustrate the delete operation : | 1 'rdya', ‘fav food': ‘pavbhajit >>> del mydict['nane'] ae ee >o> mydict {'age': 21, 'fav_food': "pavbhaji") J>>> mydict.clear() [>>> mydict - 0 2 >>> del mydict 7 >>> mydict Praceback (most recent call last): File "", line 1, in nydict ee name ‘mydict' is not defined >>> mming (BC: pon DIDS 21 Syl Ragular Exprassions an unre inheritance | explain Inheritance with example ] { on uses inheritance, which hel t i 7 ~ fem class. The syntax for a derived clace stu” the information from the Z pervedclassName(BaseClassNamey: > tatement-1> Setatement-N> Z ‘As shown in the example’ DerivedClassName is the derived class and the BaseClassNarme is the parent class. The keyword class is used before the name of the derived class. The base class scope is in the derived class definition. You can also use the other arbitrary expression in the place of base dass name. For example, when the base class can be defined in another module as shown in example. Der assName (modilename:Bas ane eee ‘The derived class executed in the same manner the base class executed. Whenever we.create an object of class then the base class is remembered. This is utilized for settling attribute references : If a asked attribute is not found in the class, the inquiry continues to look in the base class. This rule is applied recursively if the base class itself is derived from some other class. In the derived class instantiation is not all that exceptional.. For example DerivedClassName() creates a new instance of a class. The method references are searched downward to the chain of base classes if needed, and the method reference is valid if gives in a function object. - There is a possibility that a derived class may override the methods of the base class. As methods have no special privileges when calling other methods of the same object. A-method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. - An overriding method in a derived class would extend instead of replacing the base class method. To call a base class method just type or write BaseClassName.methodname (self, arguments). 1. 1 isinstance() 2 issubclass() Isinstance() function is used to check the type of instance. For example : isinstance(obj,int) This function will return the true value if obj.class is of int type oy . derived from the int. mn issubclass() This function is used to check the class inheritance. For example : issubclass(bool,int) This function will return the true value if bool is a subclass of However, issubclass(float, int) will return the false value ag fos? subclass of int. The following example will help you to understand the ..°' in of inheritance. def init (self): Print ("Calling parent constructor") def parentMethod (self) : print (‘Calling parent method’) def setattr(self, attr): Parent.parentattr = attr def getattr(self): print ("Parent attribute :", Parent.parentattr) class Child(parent): # define child class def init (self) : ‘PFint ("Calling child constructor") def childethod (self) : print (‘Calling child method') © = child() # Anstance of child ¢.childMethod() # child calis its method ©.parentMethod () # calls parent's method ce. setattr (200) # again call parent's method c.getattr () | 2.22 String Slices String is a collection of character : >>>name="hello pyi is similar to selecting a selecting a slice is similar characters , In this exam, ns the part of the string from the "n-eth” character to the “m-eth” character, it include the first but it exclude the last. It helps to imagine the indices Pointing between the characters, The slice Starts a the be, t Binning of the str the colon) and the slice index, if we omit the first index(before of the String if we omit the Second Mu} “New Window” in the ~F, in IDLE ( the directo ler” Open a new file teypy In FY Where om, ond save It a5 960 this course. Then copy the YOu ie reate fer,g volumes and areas in the Unctic? the files you ©! ta te for calcul? ise into this file ana ro! exerci Save i¢oMtra, Python Programming (BSC. >» Program 8(a) : you wi ions’ Flow and Functions ave it in the same directory, ew file an rr own module fil Ou show open Be able to import you ike this: ict rt now seeaiie ir(geometry) to the file ang int dir(g run eral aoe ton pointyShapevolume(x, Y, squarcee, Jume 0! e calculates ts right ‘circular cone if squareBase js are the length of an ec the radius of a circ height of the obj cases. Use the cir module to calculate t! ie when squareBase is False, "Ue an is t! h th, ject. First use squareBase to dist; obje ‘cleArea and squareArea from Gtinauis he base areas. Seo, [import geometry +h, square def pointyShapeVolume| if square: base = geometry.squareArea else: ee : base = geometry.circleAre teturn h * base / 3.0 print dir(geometry) Print pointyShapeVolume(4, ; print pointyShapeVolume(4, 2.6, False Output PyramidVolume = pointyShapeVolume(@y 2G) True) SeneVolume = pointyShapeVolume(4, 2.6, False) Ng f a square pyramid if Squares) the age on 2 square if squareBase jg 28°. x |* ™Metry

You might also like