

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The importance of indentation in python programming and demonstrates its role in determining the grouping of statements in control structures. It also covers the use of the print() function for outputting data to the standard output device or a file. Indentation is crucial for python's syntax, and the document provides examples to illustrate the concepts.
Typology: Assignments
1 / 3
This page cannot be seen from the preview
Don't miss anything!


Whitespaces as Indentation Python’s syntax is quite easy, but still you have to take some care in writing the code. Indentation is used in writing python codes. Whitespaces before a statement have significant role and are used in indentation. Whitespace before a statement can have a different meaning. Let’s try an example.
print('foo') # Correct print('foo') # This will generate an error
Leading whitespaces are used to determine the grouping of the statements like in loops or control structures etc. Example:
x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x - = 2 # Line 5 """ Lines 1, 3, 5 are on same level Line 2 will only be executed if if condition becomes true. Line 4 will only be executed if if condition becomes false. """ Output: x > 5 x > 5 x > 5 x < 5 x < 5
The above program should be written as follows using the indentation x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x - = 2 # Line 5 OUTPUT: x > 5 x > 5 x > 5 x < 5 x < 5 OUTPUT Function: Python provides numerous built-in functions that are readily available to us at the Python prompt. Some of the functions like input() and print() are widely used for standard input and output operations respectively. Python Output Using print() function We use the print() function to output data to the standard output device (screen). We can also output data to a file. The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen. Syntax print (object(s) , sep= separator , end= end , file= file , flush= flush ) 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).