Posts

17.Sample Programs using-loops and nested loops

Sum of the digits of a number sum=0 n=int(input("Enter a number..")) while n!=0:      sum=sum+n%10;      n=n//10 print("Sum of the digits=",sum) Output: Enter a number..123 Sum of the digits=6 Program to check whether the given number is prime or not  n=int(input("Enter a number..")) i=2 prime=True while i<=n//2:      if n%i==0:           prime=False           break      i=i+1 if prime==True:      print('Prime number') else:      print('Not a prime number') Output: Enter a number..7 Prime number Enter a number..4 Not a Prime number Python program to find the sum of even numbers from N given numbers sum=0 N=int(input("enter the number of numbers (N)..")) print("Enter the ", N ," Numbers") for i in range(N):      num=int(input())      if num%2==0:           sum=sum+num print("Sum of even numbers..",sum) Output Enter the number of numbers (N)..5 Enter the 5 Numbers

16.Nested Loops

A nested loop is a loop inside another loop.The "inner loop" will be executed completely for each iteration of the "outer loop": we can nest while loops, for loops or the combination. Syntax The syntax for a nested while loop statement in Python programming language is as follows    while expression:        while expression:             statement(s)         statement(s)   The syntax for a nested for loop statement in Python programming language is as follows  for iterating_var in sequence:      for iterating_var in sequence:           statements(s)       statements(s)  Note: indentation is very important to identify the code blocks Example: i=1 while i<=3:    j=1    while j<=i:       print(j,end=' ')            # inner while loop       j=j+1    print()    i=i+1 here the inner while loop will execute 'i '  times and  'i'  will very from 1 to 3 in the outer loop.So it will print 1 1 2 1 2 3 In the same way for loop can also be nested.The

15. break, continue and pass statements

Image
break statement The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop. break can be used in while loop and for loop . The statement break is mostly required when because of some external condition, we need to exit from a loop. Example for letter in 'Python':         if letter == 'h':                          break print(letter) output: P y t In this program, we iterate through the string "Python" . We check if the letter is 'h', upon which we break from the loop. Hence, we see in our output that all the letters up till 'h' gets printed. After that, the loop terminates. Continue Statement This statement is used to tell Python to skip the rest of the statements of the current loop block and to move to next iteration, of the loop. Con

14.Looping(Iteration )Statement- while, for

Image
We know that computers are often used to automate the repetitive tasks. One of the advantages of using computer to repeatedly perform an identical task is that it is done without making any mistake. Loops are used to repeatedly execute the same code in a program. Python provides two types of looping constructs: 1) while statement 2) for statement while loop The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand. Syntax of while Loop in Python  while test_expression:       Body of while In the while loop, test expression is checked first.The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False. In Python, the body of the while loop is determined through indentation.The body starts with ind

13.Programming Assignment 3 ( Programs using if-else)

Try the following program using if else or if elif statement 1)Compare two numbers 2)Check whether the given number is even or odd. 3)Find the biggest of 3 numbers 4)Read internal marks( out of 50) and external mark( out of 100) and print passed /failed in internal or external ( use KTU criteria..45%) 5)Check whether the given number is zero, positive or negative. 6)Find the roots of a quadratic equation ( ax^2+bx+c) 7)Read length of 3 sides and check whether it forms a triangle. (All you have to do is use the Triangle Inequality Theorem, which states that the sum of two side lengths of a triangle is always greater than the third side. If this is true for all three combinations of added side lengths, then you will have a triangle.) 8)Check the type of a triangle after reading the three sides ( scalene, isosceles, equilateral) 9) Check the type of a triangle after reading the three vertices ( scalene, isosceles, equilateral) Note: From the vertices length of the sides can be computed us

12.Selection statement if-else , if elif,match case example programs

Image
Python code Indentation Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation. A code block (body of a  function,  loop, etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. Generally, four whitespaces are used for indentation and are preferred over tabs. Conditional Statement- if-else In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest way to do is to use a if statement. In programming and scripting languages, conditional statements or conditional constructs are used to perform different computations or actions depending on whether a condition evaluates to true or false. (Please note that true and false are always written as True and False in Python.) The con

11.Programming Assignment 2( Programs using built-in functions and modules)

Read the blog post  https://pythonformlktuminor.blogspot.com/2020/08/built-in-functions-modules-and-packages.html  before attempting the following programs Programs to try using built in functions ,modules and  packages 1.Read a number in decimal and convert it into different bases. 2.Read a binary number (Eg: 0b101010) and convert it into different bases.( use eval,oct,hex functions) 3.Read a hexa decimal number (Eg: 0xa3) and convert it into different bases. 4.Read an octal number (Eg:012) and convert it into different base. 5.Read a string and find the length.( use len) 6.Find the biggest and smallest of three numbers.( use min and max function) 7.Read a number and find its factorial. ( use factorial function from math) 8.Find the number of digits in the factorial of a given number.( convert into string and find length) 9. Read a Year and print the calendar of that year (Hint: import calendar ;print(calendar.calendar(2017)) will display 2017 calendar. 10.Read a Year and month and p

10.Programming Assignment 1 ( Basic Programs)

Now you can try the following simple programs. 1) Area of the circle given the diameter. 2)Area of the circle given the circumference.(circumference=2*pi*r) 3)Area of the circle given center point (x1,y1) and one point on the perimeter (x2,y2). (Hint: input the two points and compute the distance between them as radius) 4)area of a triangle given three sides a,b,c.(use Heron's formula) 5)Area and perimeter of a right angled triangle given width(w) and height(h). (area=1/2.0*w*h .use Pythagoras theorem to find the hypotenuse then add the three sides to find the perimeter) 6).Surface area of a cube given the length of an edge. 7)Circumference,volume and surface area of a sphere given the radius. (Circumference=2*pi*r volume=4/3.0*pi*r*r*r surface area=4*pi*r*r) 8)Area of an equilateral triangle given one side (s).( sqrt(3)/4.0*s*s) 9)Volume and surface area of the cylinder given radius(r) and height(h). (volume=pi*r*r*h surfacearea=2*pi*r*r+2*pi*r*h) 10) Volume and surface area of a

9.Simple Programs to Begin with, Comments and statements, IDEs

Program Format and Structure It is always better to structure your Python program as follows Start with an introductory comment stating the author's name, the purpose of the program and other relevant information.This information should be in the form of comment or document string Then include statements that do the following Import any modules needed by the program Initialize important variables, suitably commented Prompt the user for input data and save the input data in variables Process the input to produce the results Display the results Comments Comments are very important while writing a program. They describe what is going on inside a  program, so that a person looking at the source code does not have a hard time figuring it out. You might forget the key details of the program you just wrote in a month's time. So taking the time to explain these concepts in the form of comments is always fruitful. Advantages of Using Comments Using comments in programs makes our code mo

8.Built-in Functions, Modules and Packages

  Built-in Functions A function is a named sequence of statement(s) that performs a computation. It contains line of code(s) that are executed sequentially from top to bottom by Python interpreter.They are the most important building blocks for any software development in Python. Built in functions are the function(s) that are built into Python Standard Library  and can be accessed directly.Functions usually have arguments and return a value. Some built in functions are given below with examples. Refer python documentation for more details. https://docs.python.org/3.8/library/functions.html abs(x) returns the absolute value of x . abs(-45) will return 45 max(x,y,z) returns the maximum of x,y,z . max(10,20,30) will return 30 min(x,y,z) returns the minimum of x,y,z . min(10,20,30) will return 10 divmod(x,y) returns both the quotient and remainder . divmod(14,5) will return (2,4) cmp(x,y) returns 0 if x==y , 1 if x>y and -1 if x<y round(x,n) round x to n digits. round(3.14567,2) wil

7.Output and Input functions- print() and input()

Python Output Using print() function We use the print() function to output data to the standard output device (screen) An example of its use is given below. >>>print('This is a sample output') This is a sample output Another example is given below: >>>x = 5  >>>print('The value of x is', x) The value of a is 5 The actual syntax of the print() function is: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) Here, objects is the value(s) to be printed. The sep separator is used between the values. It defaults into a space character. After all values are printed, end is printed. It defaults into a new line. The file is the object where the values are printed and its default value is sys.stdout (screen). flush: Whether to forcibly flush the stream. >>>print(1, 2, 3, 4, sep='*')  1*2*3*4 >>>print(1, 2, 3, 4, sep='#', end='&') 1#2#3#4& Output formatting Sometimes we would

6.Operator Precedence and Expression Evaluation

Operators Precedence Operator precedence in Python determines the order in which operations are performed when an expression contains multiple operators. Operators with higher precedence are evaluated before operators with lower precedence. When operators have the same precedence, their associativity determines the order of evaluation. The precedence rule learned in algebra is applied during the evaluation of arithmetic expression in Python. Exponentiation has the highest precedence and is evaluated first. Unary negation is evaluated next before multiplication and division Multiplication, division and mod operators are evaluated before addition and subtraction Addition and subtraction are evaluated before assignment Operations of equal precedence are left associative, so they are evaluated from left to right.Exponentiation and assignment operations are right associative, so consecutive instances of these are evaluated from right to left We can use parentheses to change the order of eva