Posts

Showing posts from July, 2020

Using With Block To Open Python Files

if we use with block to read a file line and than open file simply to read file lines So whether the file lines will open simply or not...?? # SOLUTION # f = open("raaz.txt", "rt") # # f.close() # Above open close syntax can be replaced by single statement # open file using with block # Everything else(means functions like readlines,seek,etc.) on f are same # first create a text file "raaz" then run this program. # with open("raaz.txt") as f: # a = f.read(7) # print(a) # Output : Stud # with open("raaz.txt") as f: # a = f.readlines() # Give List of lines # print(a) # Output : # ['Students should use LinkedIn to get connected with Corporate and Research world.\n', # 'It will be very helpful for students.'] # Question of the day - # Question 1: # Can we do readlines outside with block? # Yes or No and why? # Answer : # No, because with block closes the files once we get out of with block. # Question 2: # f...

Seek(), tell() & More On Python Files

## Set Up Steps for this tutorial :=> # Make a File "28. Tutorial.txt" # Add few lines of text in it. f = open ( "28. Tutorial.txt" ) # f.tell() tells us where is file pointer currently in file # first charcter is at 0 index in file print ( f . tell ()) # Output : 0 print ( f . readline ()) # Print First Line in the File # Output : Can We build Aatmnirbhar Districts in India ? # f.seek() is used to reset file pointer f . seek ( 7 ) # move file pointer to 5th index print ( f . readline ()) # Print First Line in the File from index 7 # Output : build Aatmnirbhar Districts in India ? print (...

Exercise

# Question : ## Pattern Printing ## # Input : # Integer n # Boolean = True or False # Expected Output : # Given: True n=4 # Output: # * # ** # *** # **** # Given: False n=4 # Output: # **** # *** # ** # * # Solve Here : r = int ( input ( "Enter Row: \n " )) n = int ( input ( "Enter Boolean 1/0: \n " )) b = bool (n) if b: for i in range (r): print ( "*" * i) else : for a in range (r): print ((r-a) * "*" )

Writing Appending to a File

# f is better to say file handle which open() return # instead saying it pointer but commonly f also known as file pointer # Opening file in write,text mode # Only 'w' mentioned below because t-text mode is by default # So 'w' is same as 'wt' # IF file "26. Tutorial.txt" not exist then it will create that. # If alrady exist then it will replace all the content with what we will write in the file # f = open("26. Tutorial1.txt", "w") # f.write("Rural Development Party - A party that contests only gram panchayat elections and has the vision to make World Class Villages with limited resources.\n") # f.close() # If we again do f.write on same file it just replace content # but in most cases we want to append the content in the file at end # for that open file in append mode -'a' # f = open("26. Tutorial1.txt", "a") # due to newline character "\n" at the last of previous write # this content...

Readline function to read one line a time, Readlines Function to get list of lines.

# Readline function to read one line a time # f = open("24. Tutorial.txt", "rt") # print(f.readline()) # f.close() # Output : # We are on a mission to transform and Optimize World with Indian Technologies. # f = open("24. Tutorial.txt", "rt") # print(f.readline()) # print(f.readline()) # print(f.readline()) # f.close() # Output : (new line in file already + one line gap due to print's by default backslash) # We are on a mission to transform and Optimize World with Indian Technologies. # We will work hard. # We will win. ########## Readlines Function to get list of lines. # f = open("24. Tutorial.txt", "rt") # print(f.readlines()) # f.close() # Output : # ['We are on a mission to transform and Optimize World with Indian Technologies.\n', # 'We will work hard.\n', 'We will win.'] ###################################################### # d = open("raaz", "rt") # print(d.readlines()) ...

Python File IO Basics

# Two types of memory # 1. Volatile Memory : Data cleared as System Shut Down # Example : RAM # 2. Non-Volatile Memory : Data remains saved always. # Example : Hard Disk # File : In Non-Volatile Memory we store Data as File # File may be text file,binary file(Ex - Image,mp3),etc. # Different Modes of Opening files in Python """ "r" - Open file for reading - Default mode "w" - Open a file for writing "x" - Create file if not exists "a" - Add more content to a file/ append at end in file "t" - open file in text mode - Default mode "b" - open file in binary mode "+" - for update (read and write both) """ # Question of the tutorial: # How to print docstring of func1() # Answer : print(func1.__doc__) ######### INOpen(), Read() & Readline() For Reading File ########## ############ Open(), Read() & Readline() For Reading File ######### # file pointer(here f) returned by open function is...

Try Except Exception Handling Tutorial

# Lets assume we running something in our python program # which may or may not throw error # For, Example : """ print("Enter num 1 :") num1 = int(input()) # Expect a number as input print("Enter num 2 :") num2 = int(input()) # Expect a number as input print("Sum of these two numbers is",num1+num2) """ # Above program will give error if input is not a number # Input : # $ python 22.\ Try\ Except\ Exception\ Handling\ In\ Python.py # Enter num 1 : # re # Output : error in line 2 # ValueError: invalid literal for int() with base 10: 're' """ print("Enter num 1 :") num1 = input() # Expect a number as input print("Enter num 2 :") num2 = input() # Expect a number as input print("Sum of these two numbers is",int(num1)+int(num2)) # It will not get printed due to error in line 5 print("This line is very important") """ # Above program will give same error at...

Functions and Doc Strings Tutorial

# Function helps in code reuseability ########################################## ## Example of built in function # a = 9 # b = 8 # Sum is a inbuilt function in Python # takes tuple or list (more, general Iterables) as input # c = sum((a, b)) # print(c) # Output : 17 ########################################## ## Example of user defined function ## The keyword def introduces a function definition. # It must be followed by the function name and # the parenthesized list of formal parameters. # The statements that form the body of the function # start at the next line, and must be indented. # def function1(): # print("Hello you are in function 1") # function1() # Output : Hello you are in function 1 ##### Functions with Parameter & Return Statement #### # The 'return' statement returns with a value from a function. # 'return' without an expression argument returns None # if no 'return' statement used in function , # then function returns None # pr...

Short Hand If Else Notation Tutorial

# a = int(input("enter a :\n")) # b = int(input("enter b :\n")) # Concise but not Obivious Readability in Code # if a>b: print("A is greater than B") # Less Concise but Better Readability in Code # if a>b: # print("A is greater than B") # This is a Trade-off, use which suit best for you team. # Short if else # print("A is greater than B") if a>b else print

Operators in python

#### Operators : # Arithmetic Operator # Assignment Operator # Comparison Operator # Logical Operator # Identity Operator # Membership Operator # Bitwise Operator # Arithmetic Operator : helps in numerical claculations # print("Arithmetic Operators :") # print("5 + 6 is",5+6) # Output : 5 + 6 is 11 # print("5 - 6 is",5-6) # Output : 5 - 6 is -1 # print("5 * 6 is",5*6) # Output : 5 * 6 is 30 # print("5 / 6 is",5/6) # Output : 5 / 6 is 0.8333333333333334 # // Gives floor division # print("5 // 6 is",5//6) # It divide and give only Integer part # Output : 5 // 6 is 0 # print("15 // 6 is",15//6) # Output : 15 // 6 is 2 # Power operator # print("5 ** 3 is",5**3) # Output : 5 ** 3 is 125 # Modulous/Remainder Operator # print("5 % 3 is",5%3) # Output : 5 % 3 is 2 #### Assignment Operator : to assign values # print("Assignment Operators :") # x = 5 # print(x) # Output : 5 # x += 7 # x = x + 7 # ...

break & continue statements

# i = 0 # while(True): # if i+1<9: # i = i + 1 # continue # # print(i+1, end=" ") # if(i==45): # break # i = i+1 # while(True): # inpu = int(input("enter your number \n")) # if inpu>100: # print("congratulation you have entered greater than hundread number\n") # break # else: # print("try again!\n") # continue # n=18 # number_of_guesses=1 # # print("Number of guesses is limited to only 9 times: ") # # while (number_of_guesses<=9): # # guess_number = int(input("Guess the number :\n")) # # if guess_number<18: # # print("you enter less number please input greater number.\n") # # elif guess_number>18: # # print("you enter greater number please input smaller number.\n ") # # else: # # print("you won\n") # # print(number_of_guesses,"no.of guesses he took...

Exercise : Faulty Calculator

""" Design a calculator which will correctly solve all the problem except the following ones: 45 * 3 = 555, 56 + 9 = 77, 56 / 2 = 4 Your program should take operator and two numbers as inputs and the return the result """ # # Taking inputs from user for calculate two number: # operator = input("select your operator like ( + or - or * or / ) ") # first = int(input("enter your number here\n" )) # second = int(input("enter your number here\n" )) # add = "+" # sub = "-" # mul = "*" # div = "/" # # if operator == add: # if first==56 and second==9: # print("your number first + second = 77") # else: # print("your result is {first} + {second} =",first+second) # for loops # list1 = [ ["Harry", 1], ["Larry", 2], # ["Carry", 6], ["Marie", 250]] # dict1 = dict(list1) # # for item in dict1: # print(item) # for i...

if else & elif

# import age as age # print("what is your age?") # age = int(input()) # if age<18: # print("no you cannot drive") # # elif age==18: # print("we cannot decided that you should drive or not come here and do a physically test") # # else: # print("yes you can drive") # age = int(input("UMAR BATAO\n")) # # if age<18: # print(" padhai likhai main dhyan do iyas yss bano desh ko smbhlao magar nahi tumhari g**d me to chanune kaat rahe hai") # elif age==18: # print("tera to sochna padega kya kare ") # elif age>60: # print("ab to retire ho ja ") # else: # print("sahi hai tm chala skte ho gadi") # Neat and clean code with comments. Hope you will like it.