Posts

Showing posts with the label Python

Functions in Python.

Python Functions: In python, function is a group of related statements that perform a specific task. A function is a block of organized, reusable cod that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Types of Functions: i)Built in Functions ii) User defined Functions Built in Functions: You already know, Python gives you many built in functions like print(). User defined Function You can also create your own functions. These functions are called user defined function. Example: def swap(x,y): '''creating user temp=x define swap x=y function''' y=temp return x,y x=2 y=3 print(swap(x,y)) #calling function Outupt: (3,2) Defining a Function: Function Definition provides the information about function name, parameters and the definition what operation is to be performed. 'def...

Comments in Python.

Python Comments: A comment in python starts with the hash character(#). Comments are in the source code for humans to read, not for computers to execute. Example: #This is a comment Types of Python comments: 1)Single lined comment 2)Multi lined comment 3)Inline comments Single lined comment: In case user want to specify a single line comment,then comment must start with #. Example: int a=10 #here a is a variable. print("Hello,world") print(a) Output: Hello,world 10 Multi lined comments: Multi lined comment can be given inside triple quotes. Example: ''' This is multiline comment in python''' Inline comments: If a comment is placed on the same line as a statements,it is called an inline comments. Similar to the block comments, an inline comments beigns with a single hash(#) sign and followed by a space and comment. Example: N=10 n+=1 # increase n by 1

Operators in Python.

Operator: Operators are special symbol in python that carry out arithmatic or logical computation, Used to perform specific operation. For Example: >>>2+3 5 Types of Operator: 1. Arithmatic operator 2. Assignment operator 3. Comparison operator 4. Logical operator 5. Bitwise operator 6. Identity operator 7. Membership operator Arithmatic operator: Arithmatic operators are used to perform mathematical operation like addition,subtraction ,multiplication etc. Addition(+): Adds value on either of the operators. Example: a=10 b=20 print(a+b) Output: 30 Subtraction(-): Subtracts right hand operands form left hand oprand. Example: a=20 b=10 print(a-b) Output: 10 Multiplication(*): Multiply values on either side of the operators. Example: a=20 b=10 print(a*b) Output: 200 Division(/): divides left hand operand by right hand operand. Example: a=20 b=10 print(a/b) Output: 2 Module(%): Divides left hand operan...

Literals in Python.

Literls:- Literal is a raw data given in a variable or consatant. In python, there are various type of literls. Type of Literls:- 1. String 2. Numeric 3. Boolean 4. Special String: String is an immutable data type. String formed by enclosing a text in the qutoes. Both single and double quotes can be used. Example: string='This is python' char="C" print(string) print(char) Output: This is python C Numeric Literls: Numeric literals are immutable data type. Numeric literals can belong to four different Numeric type. Types of Numeric Literls: .Integer .Long .Float .Complex integer(signed integer): Number( can be +ve and -ve) with nuber fractional part. Example: 230 Long(long integer): Integer of unlimited size followed by lower case or uppercase. Example 8703285L Float(folating point): Real numer with both integer and fractional part. Example 35.2 Complex(complex): In the form ...

Built in functions in Python.

Built in functions: sum() sum () function is used to add the all elements of list. marks=[70,60,55,80,75] temp=sum(marks) print(temp) avg=float(temp/len(marks)) print(avg) output: 340 68.0 len() This method is used to find the length of given list. l1=[10,20,30,40,50] print(len(l1)) output: 5 max() This method is used to find the maximum value present in list. l1=[10,20,30,40,50] print(max(l1)) output: 50 min() This method is used to find the minimum value presentin the list. l1=[10,20,30,40,50] print(min(l1)) output: 10 shuffle() This method is used to shuffle the value present in the list. To used the memthod shuffle, we have to import module. import random l1=[10,20,30,40,50] random.shuffle(l1) print(l1) output: [50, 10, 30, 40, 20] join() To join the individual characters of the list if it is a string. We can combined the character into long string. str=['P',...

Built in Methods in Python.

BUILT IN METHOD: append() append() method add a list item in the end of list. books=['java','python','DBMS','Ds'] print(books[2:4]) books.append('os') print(books) output: ['DBMS', 'Ds'] ['java', 'python', 'DBMS', 'Ds', 'os'] Count() Count() return the numbers of time x apper in list. m1=[1,2,3,1,5,6,1] print(m1) print(m1.count(1)) output: [1, 2, 3, 1, 5, 6, 1] 3 Clear() It will remove all the item from list. m1=[1,2,3,4] print(m1) m1.clear() print(m1) output: [1,2,3,4] [] Copy() This method is used to return a same copy of the list. l1=['a','b','c'] print(l1) l2=l1.copy() print(l2) output: ['a','b','c'] ['a','b','c'] extend(object x) append all element of the list l2 to the list l1 or vice-versa. ...

List Slicing & List Operations in python..

List Slicing: The slicing operator return a subset of list called slice, by specifying start and end indexes. Syntax: list_variable_name [start:end] Creating List without using Constructor: list1=['ram','shyam',23,45,67,20.05] print(list1[1:4]) print(list1[2:5]) print(list1[:3]) print(list1[:]) print(list1[::-1]) print(list1[2::]) Output: ['shyam', 23, 45] [23, 45, 67] ['ram', 'shyam', 23] ['ram', 'shyam', 23, 45, 67, 20.05] [20.05, 67, 45, 23, 'shyam', 'ram'] [23, 45, 67, 20.05] List slicing with step-size: The third parameter step-size is to select list with step-size. Syntax: name_of_list_variable [staert:end:step] Example: list1=['ram','shyam',23,45,67,20.05] print(list1[0:4:2]) Output: ['ram', 23] List Operations: Traversing a List: To traverse a list we use "for in" statement which make it easy to loo...

List in Python...|empty list | retrieve list.

List: In python a list is a sequence of values called items or elements. The elements can be any datatype like integer,string or float values. The items or elements are placed between the '[]',separated with ','. Creating List: The list class define List. A programmer can use list constructor to create a list. l1=list() l2=list(['b',1,2,3,4,'A']) l3=list([1,2,3,4,5,6.06]) print(l1) print(l2) print(l3) Output: [] ['b', 1, 2, 3, 4, 'A'] [1, 2, 3, 4, 5, 6.06] Creating List without using Constructor: l1=[] l2=['b',1,2,3,4,'A'] l3=[1,2,3,4,5,6.06] print(l1) print(l2) print(l3) Output: [] ['b', 1, 2, 3, 4, 'A'] [1, 2, 3, 4, 5, 6.06] Retrieve the elemements of List : The elements of list are access by index operator. Syntax: name_of_list_variable [index] Example: l1=["Python","Code",2020] print(l1[0]) print(l1[1]) print(l...

A simple Python Game..

Image
Source Code: attemp=int(input("Enter Attempts:")) no_attept=attemp guessContainer="Harshwardhan" while attemp > 0: guessword=input("Guess Character:") failed=0 if guessword in guessContainer: print("Correct Guess") else: print("Incorrect Guess") failed=failed + 1 attemp=attemp-1 if failed > no_attept/2: print("You failed..") else: print("you won") Output:  

Positional and Keyword Argument in python.

Positional Argument If there are more then one parameters are present in a function, how does python idenify which argument in the statement has to assign which parameter. The parameter are assign accordings to their position i.e. first argument in the first column. Example 1: def display(name,mobile_no): print("Name:",name) print("Mobile_number:",mobile_no) display("Harsh",123456) Output: Name: Harsh Mobile_number: 123456 Example 2: def display(name): print("Name:",name) display("Harsh",123456) Error: Traceback (most recent call last): File " ", line 7,in TypeError:display()takes 1 positional argument but 2were given Keyword Argument An alternative to positional argument is keyword argument. If the program knows the parameter name use within the function then they can use the parameter name by calling the function. This is done by: Parameter_name=value ...

Python Function.. Parameter, Arguments,Factorial of number.

Function: It is difficult to maintain large scale program and the identification of the programming gets harder. The best way to create programming application is to divide a big program in small module and repeatedly call this module within program with the help of function and entire program can be devide into small independent modules. A function is the self contained block of one or more statement that perform a special task when called. This improve the code readability as well as flow of execution and small modules can be managed easily. Syntax: def function_name (list_parameter): statement(s) the syntax for the python contains header and the body. The function header begins with the header 'def' followed by the function name and arguments are optional. the body contents the statement to be executed and function will be executed only when it is being called. Example: Write a python program to display a simple message Source ...

Testing of a String.|String methods|

A string may contain digit, alphabet or combination of both of this. This various methods are available to test if the entered string is digit or alphabets or alphanumeric. bool isalnum: str=input("enter string") print(str) print(str.isalnum()) output: enter string:harsh harsh True bool isalpha: str="123python" str1="python" print(str.isalpha()) print(str1.isalpha()) output: False True bool isdigit: str="123" str1="python" print(str.isdigit()) print(str1.isdigit()) output: True False bool islower: str="PYTHON" str1="python" print(str.islower()) print(str1.islower()) output: False True bool isupper: str="PYTHON" str1="python" print(str.isupper()) print(str1.isupper()) output: True False bool isspace: str=" " str1="python" print(str.isspace()) print(str1...

Searching of String in Python.|methods|sub-strings.

Searching of String. This is the process of checking occurance of substring in whole string or in a substring finding the characyers if starting index BEG and End ending index are given. Syntax: str_var.find("string",beg=0,end=len(string)) where string specify,string to be search beg specify starting index by default it is 0. end specify is ending index by default it is length of string. Here, return value of this function will be an index if found or -1 otherwise. Example: str="python" print(str) print(str.find("y")) output: python 1 Various methods of string class is used to search the substring in a given string. bool endswith(str1,str2) str="python basic" print(str) print(str.endswith("basic")) output: python basic True bool startswith(str1,str2) str="python basic" print(str) print(str.startswith("python")) output: python basic...

String Operations in Python. |print all letters appear in two words|

String contains the slicing operator and the slicing with the stepsize parameter is used to obtain the subset of string. It also has basic concatination " + " in and repeatation " * ". String Slicing Operators The slicing operator return a subset of string called slice by specifying two indexes start and end. Syntax: Var_name[start:end] Example: st="python string" print(st[4:10]) output: on str String Slicing with step size If the programmer select every second character from string. This can be done by using step-size. We need to add third parameter as step-size. Syntax: Var_name[start:end:stepsize] Example: st="python basic string" print(st[1:10:2]) output: yhnbs Some more Complex examples: st="python basic string" print(st[::]) print(st[::-1]) print(st[-1::-1]) print(st[:-1]) output: python basic string gnirts cisab nohtyp gnirts cisab nohtyp p...

Control statements(Break, Continue, Pass) in Python.

Control Statement Control statement allow a programmer to control the flow of program according to their need. Control statements are break, continue and pass. Break Statement The break statement allow a programmer to terminate a loop, when the break statement is encountered inside the loop,the loop is immidiately terminated and program control automatically goes to first statement. Break statement in while loop Syntax: while test_condition: statement(s) if test_condition: break statement(s) Break statement in for loop Syntax: for variable_name in Sequence: //Loop_Body if test_condition: break //Loop_Body //Statement after Loop Write a program to demonstrate the use of break statement. Syntax: print("The number from 1 to 5") for num in range(1,100): if num==4: break else: print(num) output The number from 1 to 5 1 2 3 Continue Statement The continue Statement is exactly opp...

How to identify the consonants in string? |String | Python Code.

Source Code st=input("Enter your string ") vowel="aeiouAEIOU" l1=[] for i in st: if(i not in vowel): l1.append(i) print("Consonants in given String") print (l1) output Enter your string hello Consonants in given String ['h', 'l', 'l']

Loops in Python.

Looping Looping is a continuous execution of a statement till the condition becomes false or till it set the end point. In python two types of looping supported , they are: 1. While Loop 2. For Loop While loop While loop is a conditional control statement. It will be executed based on the condition, if the condition is true it will execute the body of the loop till the condition become false Syntax: while condition: Block Statement increment/decrement Example: Write a python program to add 10 consecutive number starting from 1 using while loop. Syntax: count=0 sum=0 while count output: sum of 10 consecutive numbers is : 55 For loop The for loop in python a slightly different from other programming language. The python for loop iterate through each value in a sequence,where squence of object hold multiple items of data store one after another. Syntax: for variable_name in sequence: statement(...

Decision Making Statement.

Image
Conditional Statement Decision making of an anticipation of condition occuring by execution of program and dpecific action is taken according to condtion. Following is a general form of typical decision making structure found in most programming language. Python programming language uses any non-zero or non-null value as true and if it is either zero or null then it is assume false value. if Condition: In python the block of statement is executed if the condition is true. Syntax if (condition): Block(s) Example var1=100 if var1: print('i got an true value') print(var1) output i got an true value 100 Question: Write a program that prompt user to enter two integer values, print the message "equal" if both entered value are equal a=int(input("Enter first number")) b=int(input("Enter second number")) if a==b: print("equal") output Enter fir...

Introduction to Python.

What is python? Python is an object-oriented programming language created by Guido Rossum in 1998. If you just beginning your programming career, python suits you best. With python you can do everything from GUI developement, web application, Machine learning, IOT, Game Developement etc. so it is general purpose high level programming language. It is very easy language,it is good for beginners. It is case sensitive language. Python is Dynamically Typed, Write less code do more. Introduction Easy to Learn and Use Python is easy to use and learn, it is user friendly and high level programming language. Expressive language Pyton language is more expressive means that is more understand and readable. Unique style Python is an interpreted language i.e interpreter execute the code line by line at a time . This makes debugging easy and thus suitable for beginners. Cross Platform Language Python can run equally on different platform such as windows, Linu...

Tower of Henoi Algorithm.

Image
Tower of Hanoi: Tower of Henoi It is a mathematical puzzle in which three towers and more than one different sizes rings are stacked in ascending order. In this puzzle number of disc can be increases. Disc are kept in this way that smaller disc sits over bigger disc. Rules to Play: The task of this puzzle is to move the discs to another tower without breaking the sequence of arrangement. 1. Only one disc can be move at a time. 2. Only upper disc can be move. 3. Bigger disc can not be sit over small disc. Source code: def towerOfHenoi(n, source, to,intermediate): if(n==1): print("Transfer disc", source ,"to", to) else: towerOfHenoi(n-1,source,intermediate,to) print("Transfer disc", source ,"to", to) towerOfHenoi(n-1,intermediate,to,source,) numOfdisc=int(input("Enter number of disc")) towerOfHenoi(numOfdisc,'A...