Posts

Showing posts with the label python tutorial

Files and exceptions in python

  File Concepts in python : The main function in file execution is the  open()  function which is used for opening the required files. The files can be opened in four modes namely, "r" - read mode, here the file can only be read and no other permission is granted. It is the default mode. "w" - write mode, here the file is opened for writing alone "a" - append mode, here the file grants access for appending "x" - create mode, for creating a new file example, open("file1.txt","r") The above line of code opens the file named file1 in read mode. If we try to write on this file, it throws an error. We have  read()  method for reading the file. For example, f= open("file1.txt","r") print(f.read()) When the above set of lines is implemented, it prints all the contents available in the file as f.read() reads the entire file. If we pass argument inside the read function i.e.  read(5),  we'll be getting the first

Looping in python (for & while)

  Loops 1. While loop In general a loop helps us to repeat things a number of times. Some times though we know we wanted to repeat things but don't know how many times exactly the particular thing has to be repeated. So the number of turns varies for each problem. This is a situation that calls while loop. The syntax for while loop is as follows, While (condition):         #Statements         #your code For example, To print the sum of n numbers The code goes here N=int(input())  Sum =0 i=0 While (i<=N ):       Sum =Sum +i print(Sum) The above code is executed using while loop. The first line gets the number of terms N from user. A variable Sum and i are initialized as zero. The loop runs until  the condition (i<=N) fails . And hence we get the sum of N terms as the output. Conditional statements in loops : To print n odd terms The code goes on here, N=int(input ()) Sum=0 i=0 While (i<=2N):     if(i%2!=0):         Sum+=i     else:         Continue print (Sum) In this case

Python if else

  Python  Condition al statements (If else) 1) if Syntax : if(condition) :         s1           This  is used to execute the mentioned statement s1  if the given condition is true and skip the execution of statement when the condition is false. Example: x=int(input()) if(x>0):      print ("positive")  Here if the input is greater than zero it will be printed as positive otherwise no output will be shown. 2) else Syntax :          else :          S1 Here S1 is the statement that is needed to be executed when if condition fails. Example: x=int(input ()) if(x>0):      print ("positive") else:      print ("negative") In this case all the other numbers which doesn't fall under if condition will be printed as negative. 3)elif(condition):           This is used in case of multiple  conditions. Example: x=int(input ()) if(x>0):     print ("positive") elif(x<0):      print ("negative") else:      print ("zero") Here eli