Python Input, Output and Import


Python Output Using print() function





print() sends its output to a default stream called sys.stdout, which is usually equivalent to the console





print() inbuilt function of python to output data on the standard output device (screen).





We can also output data to a file.





Syntax:-





print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)





Here,





 objects is the value(s) which want to be printed.





 sep is separator used between the values. It defaults into a space character.





 end is used at last and print all values into a new line.





 file is the object where the values are printed. Its default value is sys.stdout (screen). 





Ex.





print(1, 2, 3, 4)





print(1, 2, 3, 4, sep='*')





print(1, 2, 3, 4, sep='#', end='&')





Output





1 2 3 4





1*2*3*4





1#2#3#4&





Ex.





>>> x = 5; y = 10





>>> print('The value of x is {} and y is {}'.format(x,y))





Output:- The value of x is 5 and y is 10





We can specify the order in which we want, the curly braces {} are used as placeholders.





We can use keyword arguments to format the string.





Ex.





>>> print('Hello {name}, {greeting}'.format(greeting = 'Good morning', name = RAM))





Output:-





Hello RAM, Good morning





Unformatted Console Output





To display objects to the console with comma-separated list of argument.





Syntax:-    print(<obj>, ..., <obj>)





Unformatted Console Output





To display objects to the console with comma-separated list of argument.





Syntax:-    print(<obj>, ..., <obj>)





ex.  





>>> fname = SITA





>>> lname = RAM





>>> print('Name:', fname, lname)





Output: - Name: SITA RAM





object can be specified as an argument





If an object isn’t a string, then print() converts it to an appropriate string representation displaying it:





Ex.





>>> a = [1, 2, 3]





>>> type(a)





<class 'list'>





>>> b = -12





>>> type(b)





<class 'int'>





>>> d = {'abc': 1, 'xyz': 2}





>>> type(d)





<class 'dict'>





>>> type(len)





<class 'builtin_function_or_method'>





>>> print(a, b, d, len)





Output:-





[1, 2, 3] -12 {'abc': 1, 'xyz': 2} <built-in function len>





Keyword Arguments to print()





Syntax:-  <keyword>=<value>.





Any keyword arguments passed to print() must come at the end, after the list of objects to display.





The sep= Keyword Argument





Adding the keyword argument sep=<str> causes objects to be separated by the string  <str> instead of the default single space:





Ex.





>>> print('ABC', 42, 'XYZ', sep='/')





ABC/42/XYZ





we can also use the + operator to perform concatenation and star/ multiply(*) operator to repeat the string. In + operator, both the arguments must be string only and while using the star(*) operator, one argument must be of int type, and another must be of a string data type.





Ex.





print('chercher'+'tech')





print(5*'chercher.tech')





 output:-





cherchertech





chercher.techchercher.techchercher.techchercher.techchercher.tech





print() function use for print the various outputs in a single line output as newline character by the end attribute.





Ex.





print('cher',end='')





print('cher',end='')





print('.tech',end='')





output:-





chercher.tech





we can use any arguments with the print() statement as object passing.
ex.





L=[10,20,30]




print(L)




# the output for above code is




[10,20,30]




 




T=(1.0,20,23)




print(T)




#The output for above code is




(1.0,20,23)




Output:-





[10, 20, 30]





(1.0, 20, 23, 'abc')





We can use replace () inbuilt function with print() in python,





replace() returns the copy of a string with the substring where we had specified. The replacement operator is specified with the {} symbol.

The syntax for replace operator is:





string.replce(old, new, count)





The parameters are:





  • old: old substring which you want to replace
  • new: new substring which is going to replace the old substring
  • count(optional): The number of times you wish to return the old substring with unique substring.
    The following example demonstrates the use of replacing (), operator
    example:-
    s="Hello chercher technology"




#print the string by replacing technology with tech





print(s.replace("technology","tech"))





output:-





Hello chercher tech





Example :-





File Opening





For opening a file we use open() functions. This is a built-in function in Python.





f = open("output.txt ")    # open " output.txt " file in current directory





f = open("C:/Python34/README.txt"# specifying full path of a file





You can also specify the mode or purpose for opening that file.





f = open("output.txt ",'r')    # open " output.txt " file to read purpose





f = open("output.txt ",'w')  # open " output.txt " file to write purpose





f = open("output.txt ",'a')  # open " output.txt " file to append purpose





File Closing





f = open("output.txt ")    # open " output.txt " file





#do file operation.





f.close()





Reading From a file





You can read a certain number of byte from the file with read() function.





f = open("output.txt ")    # open " output.txt " file





str=f.read(10) #read first 10 bytes from the file.





print(str)     #print first 10 bytes from the file.





f.close()





You can read file line by line with readline() function.





f = open("output.txt ")    # open " output.txt " file





str=f.readline() #read first line from the file.





print(str)     #print the first line.





str=f.readline() #read second line from the file.





print(str)     #print the second line.





f.close()





You can also read all the lines at once and store the lines in a list of strings.





f = open("output.txt ")    # open " output.txt " file





str=f.readlines() #read all the lines from the file at once. and store as a list of string





print(str)     #print list of all the lines.





f.close()





Writing to a file





f = open("output.txt",'w')    # open "output.txt" file





#write something in the file.





f.write("this is my first line\n")





f.write("this is my second line\n")





f.close()





====================================================





Python Input





 input() function access value from user via console.





the python will automatically identify whether the user entered a string, number, or list;





syntax:





input(prompt_message)





 prompt is the string which display on the screen. It is optional.





Ex.





>>> n = input('Enter a digit : ')





Enter a digit: 100





>>> n





'100'





To convert this into a number we can use int() or float() functions.





>>> int('100')





100





>>> float('100')





100.0





Display message with input function:-





>>> name = input('Hello, who r you? ')





Hello, who r you ? ram





>>> name





'ram'





By default input() returns a string. If you change data type, then you use built-in functions conversion functions, which are string to int() /  float() / or complex() :





Ex.





  >>> n = input('Enter a digit: ')





  >>> print(n + 1000)





Output:-  





Enter a digit: 500





TypeError: must be str, not int





For removing this error you use int() input function.





For removing this error you use int() input function.





Ex.





 >>> n = int(input('Enter a digit: '))





 >>> print(n + 1000)





Output:-





Enter a digit: 300





1300





Writing Output to the Console





Take data from the user and  send data to the console in Python with print(). For this you Convertstrings to int before addition.





x1 = input("Enter a first number: ")





x2= int(x1)





x2





y1 = input("Enter a second number: ")





y2= int(y1)





y2





print('The sum of ', x1, ' and ', y1, ' is ', x2+y2, '.', sep='')





output:-





Enter a first number: 2





Enter a second number: 3





The sum of 2 and 3 is 5.





Example:-





eno=int(input("Enter the Emplyoyee number:"))





ename=input("Enter the Employee name:")





esal=float(input("Enter the employee salary:"))





eaddr=input("Enter the employee address:")





married=bool(input("Is employee married?[True|False]:"))





print("Please confimr your provided information")





print("Emplyoyee number:", eno)





print("Employee name:", ename)





print("Employee salary:", esal)





print(" Employee address:", eaddr)





print("Employee married?:", married)





output:-





Enter the employee address:ase1,3445





Is employee married?[True|False]:true





Please confimr your provided information





Emplyoyee number: 101





Employee name: aaa





Employee salary: 100000.0





 Employee address: ase1,3445





Employee married?: True





immediate conversion





a = int(input("Enter a first number: "))





b = int(input("Enter a second number: "))





print('The sum of ', a, ' and ', b, ' is ', a+b, '.', sep='')





 output:-





Enter a first number: 5





Enter a second number: 6





The sum of 5 and 6 is 11.





Ex.





x = int(input("Enter first number: "))





y = int(input("Enter second number: "))





sum = x+y





print('The sum of ', x, ' and ', y, ' is ', sum, '.', sep='')





output:-





Enter first number: 2





Enter second number: 7





The sum of 2 and 7 is 9.





format with {} in print:-





syntax:-





object. methodname(parameters)





Ex.





rno  = input('Enter your rno: ')





msg = 'Hello, {}!'.format(rno  )





#object= hello, methodname= format , parameter = variable name.





print(msg)





output:-





Enter your rno: 1001





Hello, 1001





Compare print with concatenation and with format string.





Ex.





applicant = input("Enter the guest’s name: ")





interviewer = input("Enter the interviewer's name: ")





time = input("Enter the interview time: ")





print(interviewer + ' will interview ' + applicant + ' at ' + time +'.')





print(interviewer, ' will interview ', applicant, ' at ', time, '.', sep='')





print('{} will interview {} at {}.'.format(interviewer, applicant, time))





Output:-





Enter the applicant's name: ram





Enter the interviewer's name: sita





Enter the appointment time: 04:10 PM





sita will interview ram at 04:10 PM.





sita will interview ram at 04:10 PM.





sita will interview ram at 04:10 PM.





Example:-





'''Two numeric inputs, explicit sum'''





x = int(input("Enter an integer: "))





y = int(input("Enter another integer: "))





sum = x+y





total = 'The sum of {} and {} is {}.'.format(x, y, sum)





print(total)





output: -





Enter an integer: 5





Enter another integer: 8





The sum of 5 and 8 is 13.





Example:





'''Illustrate braces in a formatted string.'''





a = 5





b = 9





setStr = 'The set is {{{}, {}}}.'.format(a, b)





print(setStr)





output:-





The set is {5, 9}.





Example:-





'''Fancier format string example with





parameter identification numbers’’’





x = int(input('Enter an integer: '))





y = int(input('Enter another integer: '))





formatStr = '{0} + {1} = {2}; {0} * {1} = {3}.'





equations = formatStr.format(x, y, x+y, x*y)





print(equations)





output:-





Enter an integer: 4





Enter another integer: 4





4 + 4 = 8; 4 * 4 = 16.





Example:-





name = input("What's your name? ")





age = input("Your age? ")





print(age, type(age))





colours = input("Your favourite colours? ")





print(colours)





print(colours, type(colours))





output:-





What's your name? ram





Your age? 50





50 <class 'str'>





Your favourite colours? blue, white, black





blue, white, black





blue, white, black <class 'str'>





example:-





name, age, phone = input("Enter your name, Age, Percentage separated by space ")





print("\n")





print("User Details: ","\n name :- " ,name,"\n age:- ", age,"\n phon:- ", phone)





outputs:-





File "C:\Users\panka\OneDrive\Documents\a1\a1.py", line 1, in <module>





    name, age, phone = input("Enter your name, Age, Percentage separated by space ")





ValueError: too many values to unpack (expected 3)





Example:-





name, age, phone = input("Enter your name, Age, Percentage separated by space ").split()





print("\n")





print("User Details: ","\n name :- " ,name,"\n age:- ", age,"\n phon:- ", phone)





output:-





Enter your name, Age, Percentage separated by space zzz 20 90





User Details: 





 name :-  zzz





 age:-  20





 phon:-  90





Example:-





text = input("Enter String ")





print("\n")





print("Left justification", text.ljust(60, "*"))





print("Right justification", text.rjust(60, "*"))





print("Center justification", text.center(60, "*"))





Output:





Enter String Jessa





Left justification Jessa*******************************************************





Right justification *******************************************************Jessa





Center justification ***************************Jessa****************************





===============================================================





eval () function





eval () function automatically returns what argument is passed to eval () function.
If the argument represents a string, then eval () function also returns a string. If you pass an argument as int, float, string, Boolean, it will return the corresponding datatype only. The eval () function is used as an alternate for typecasting.
example:-





x=eval(input("Enter something:"))




print(type(x))




===============================================================





Python Import





Bigger program break into various sub parts called modules.





A module is a file in this Python definitions, functions and statements are store. It end with the extension .py.





We use the import keyword to do this.





example:-





import math





print(math.pi)





Output





3.141592653589793





We can use all specific attributes and functions of math module.





example:





>>> from math import pi





>>> pi





Output:-





3.141592653589793





While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.





import sys





import sys





print (sys.path)





# sys.path show list of directory locations.





=================================================================






Post a Comment

0 Comments