Print line return python

Python print() Function

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

Parameter Values

Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before printed
sep=’separator Optional. Specify how to separate the objects, if there is more than one. Default is ‘ ‘
end=’end Optional. Specify what to print at the end. Default is ‘\n’ (line feed)
file Optional. An object with a write method. Default is sys.stdout
flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False

More Examples

Example

Print more than one object:

Example

Example

Print two messages, and specify the separator:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Читайте также:  Php тип переменной число

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python Print

The function which prints the specified message on the screen and any other output device is the Python Print() function. By the end of this article, we expect you to be comfortable with what print() is and how it works, and we also show some amazing things one can do using python print().

If you want enrich your career and become a professional in python, then visit Mindmajix — a global online training platform : «Python Certification Course » This course will help you to achieve excellence in this domain

Following are the topics we will be covering in this article

  • print() function: Definition, description and Usage
  • print() Parameters
  • Return Value from print()
  • How print() works in Python?
  • print() with separator and end parameters
  • More Variables and Printing
  • How to print without newline in python?

The Python print() function helps in printing the specified message onto the screen, or any other standard output device.

The message can be a string, or any other object, the object will be converted into a string before being written to the screen. Whatever be the message format i.e string or any other object, it finally gets converted into a string only.

The print function in Python is a function which is used to output to the console window whatever you say you want to print out. At the first instance, it might seem that the print function is rather pointless for programming, but it is actually one of the most widely used functions in all of python.

The reason for this being that print() function is great as a debugging tool. «Debugging» can be defined as the act of finding and removing or fixing errors and mistakes present in the code which allows the program to operate according to a set of specifications.

Whenever something isn’t acting as expected, one can use the print function to print out what is happening in the program. A lot of times, you would be expecting a variable to be a certain way, but the problem is that you cannot see what the program sees. When you print out the variable, you might be able to see what the variable actually is.

Before we proceed let us look at the python print() format.

The syntax of the print function is of the following format

print(object(s), separator=separator, end=end, file=file, flush=flush)
object(s) As many objects as you like will be converted to string before being printed
sep='separator' Optional. This specifies how to separate the objects, whenever there is more than one. Default is ''
end='end' Optional. This specifies what needs to be printed at the end. The Default value is 'n'
file Optional. This is an object with a write method whose default is sys.stdout
flush Optional. A Boolean value which specifies if the output is flushed (True) or buffered (False). The default value is False 

A point to remember is that sep, end, file, and flush are all keyword or named arguments. In case you would want to use sep argument, you have to write:

print(*objects, sep = 'separator') not print(*objects, 'separator') 

Return Value from print()

One important thing to remember is that Python print() returns no value. It returns None. This is because in Python 2.x, it is considered as a reserved keyword and not a function.

Let us now move forward by going through a couple of examples using the Python print(). We shall also cover examples using

But before that let us see the basic functioning using python print() examples.

How print() works in Python?

Let us carefully understand how print in python actually works.

print("Python is fun.") a = 5 # Two objects are passed print("a language-javascript">Python is fun. a = 5 a = 5 = b

In the previous program, only the objects parameter has been passed to print() function (in all three print statements).

' ' separator is used. Observe the space between two objects in output.
end parameter 'n' (newline character) is used. Observe that each print statement displays the output in the new line.
The output has been printed on the screen.
flush is False . This means that the stream is not forcibly flushed.

Now let us look at another example of Python print() with separator and end parameters which we will further elaborate later in this article.

a = 5 print("a =", a, sep='00000', end='nnn') print("a language-javascript">sourceFile = open('python.txt', 'w') print('Pretty cool, huh!', file = sourceFile) sourceFile.close()

What this program does is that it tries to open the python.txt in writing mode. If this file doesn't exist, python.txt file is created at that moment and then opened in writing mode. Here, we have passed file object ' sourceFile ' as the file parameter. Here, 'Pretty cool, huh!' is the string object which is printed to python.txt file.

Finally, the close() method helps in closing the file.

Usually, the separator between the arguments in the print() function in Python is space by default (softspace feature) , which can be changed and be made to any character, integer or string as per our requirements. To achieve the same, we use the ‘ sep ’ parameter, which is found only in python 3.x or later. It also finds its use in formatting the output strings.

Let us take a look at the below examples:

#code for disabling the softspace feature print('G','F','G', sep='') #for formatting a date print('09','12','2016', sep='-') #another example print('pratik','geeksforgeeks', sep='@') 

The output generated will be of the following format:

GFG 09-12-2016 pratik@geeksforgeeks

When the sep parameter is coupled with end parameter it produces amazing results. Some examples showing the combination of the two are:

print('G','F', sep='', end='') print('G') #n provides new line after printing the year print('09','12', sep='-', end='-2016n') print('prtk','agarwal', sep='', end='@') print('geeksforgeeks') 

The output generated is a below:

GFG 09-12-2016 prtkagarwal@geeksforgeeks

More Variables and Printing

Now let's continue with doing more typing of variables and printing them out. This time we'll use the concept of “format string." Whenever you put " (double-quotes) around a piece of text, it results in the formation of a string. We can do a lot with strings. We can print strings, we can save strings to files, we can also send strings to web servers, and many other things.

Strings are very handy, and in this exercise, we will teach you how to make strings that have variables embedded in them. With the help of specialized format sequences we can embed variables inside a string. And by putting these variables at the end of this sequence with a special syntax that communicates to Python that it is a format string and the variables need to be put here.

Though it's difficult to completely understand at this point of time, just type this in. You'll get clarity once you see the output.

my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height print "He's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) 
A point to remember is to put # -*- coding: utf-8 -*- at the top in case you notice non-ASCII characters and face an encoding.

This is the expected output:

Let's talk about Zed A. Shaw.

he's 74 inches tall. He's 180 pounds heavy. Actually that's not too heavy. He's got Blue eyes and Brown hair. His teeth are usually White depending on the coffee. If I add 35, 74, and 180 I get 289.

We would like to challenge you with a couple of exercises. Try them out yourself.

  • Try to rename all the variables so that there is no my_ in the beginning of each one. You should be sure that you changed the name everywhere, not just at the point where you used = to set them.
  • Try to name and use some variables that convert the inches and pounds to centimeters and kilograms or convert Celsius to Fahrenheit. We suggest you to not just type in the measurements but also work out the math present in Python.
  • Make a note of all the Python format characters.
  • Try using more format characters. One of the useful ones is %r which says "print this no matter what."

 MindMajix YouTube Channel

We expect you to face some roadblocks and hurdles too. So we have compiled a set of frequently asked questions.

  • Can I name a variable in this format: 1 = 'Zed Shaw'?
    • No, you cannot. 1 is not considered a valid variable name. Variables need to start with a character, so a1 would be working well, but 1 will not.
    • These are called formatters and you'll be learning more about this as you progress.
    • The approach we take is to make you do something, and then we explain the concept behind it later. Whenever you run into any kinds of questions, write them down.
    • The round() function can be used to round off a floating point number like this: round(1.7333).
    • This might arise because you might have forgot the % between the string and the list of variables.

    Python print without Newline

    Whenever people switch from C/C++ to Python, they wonder how to print two or more variables or statements without progressing onto a new line in python, since, by default, the python print() function ends with newline. Python provides you with a predefined format wherein if you use print(a_variable) then it will go to the next line automatically.

    Let us look at the following example:

    print("geeks") print("geeksforgeeks") 

    will generate this

    But in case you would like to print on the same line, what can we do?
    Input : print("geeks") print("geeksforgeeks") Output : geeks geeksforgeeks Input : a = [1, 2, 3, 4] Output : 1 2 3 4 

    One thing to be noted is that the solution which has been discussed is totally dependent on the python version being used.

    Print without newline in Python 2.x

    # Python 2 code for printing # on the same line printing # geeks and geeksforgeeks # in the same line print("geeks"), print("geeksforgeeks") # array a = [1, 2, 3, 4] # printing a element in same # line for i in range(4): print(a[i]), 
    geeks geeksforgeeks 1 2 3 4 

    Print without newline in Python 3.x

    # Python 3 code for printing # on the same line printing # geeks and geeksforgeeks # in the same line print("geeks", end =" ") print("geeksforgeeks") # array a = [1, 2, 3, 4] # printing a element in same # line for i in range(4): print(a[i], end =" ") Copy CodeRun on IDE 
    geeks geeksforgeeks 1 2 3 4 

    With the Python 3.0 version, the python print() statement has changed from being a statement to a function. With more flexibility at its disposal python print() can help you do amazing things. We hope this article has given you the base on which you can master!!

    If you are interested learn python and build a career in it ? Then checkout our python training near your cities

    These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Microsoft Azure and help you to achieve your dream job.

    Источник

Оцените статью