In Python, you print using the print () function. In our first program, we will create a program that prints the text line “Hello World!”.
Now it’s time to code your first program! It is an old tradition that a programmer’s first program prints “Hello World!” If you want, you can encode yourself, directly in the Jupyter Notebook.
Printing in Python is easy. You simply use the print () function
For example, like this:
print("Hello World!")
When you run the program, you will then receive the printout:
Hello World!
Note that you put the text you want to print quotation marks ( ” ” ). To run your program, click Run in Jupyter Notebook.
There are several ways to format your printing in Python, in other words, how you can format your prints to make them look the way you want them to. Below we will se some examples how to easily adjust our prints.
For example,
a = "Programming in Python" b = " is fun" print (a, b)
Gives the print:
Programming in Python is fun
You simply add \ n to make a line break
print ("Programming in Python", "\nis fun")
Gives the print:
Programming in Python is fun
Note, there is no space after \n, if we would have put it then the print becomes:
Programming in Python is fun
In other words, an extra space after the line break.
You simply add \ t to make a tab
a = "Programming in Python" b = "is" c = "Fun!" print("\na:\t", a, "\nb:\t", b, "\nc:\t", c)
Gives the print:
a: Programming in Python b: is c: Fun!
You use the brackets to create so called Placeholders. For example,
a = "Programming in Python is {}" print(a)
With print:
Programming in Python is {}
Furthermore, by using the command format ( ) we can use the placeholder to add values
b = a.format('FUN!') print(b)
With the new print:
Programming in Python is FUN!
The text you want to print should be inside the quotation marks (” “). Be careful not to forget these, in that case, there is the risk that you will perform a mathematical operation instead.
Let’s take a example to show what we mean,
print(1+1)
Gives print:
2
And the code:
print("1 + 1")
Gives the print
1 + 1
If you would make a mistake and forget the , for example, quotation marks, you will get a so-called compilation error. This means that the compiler does not understand your code and the program will then crash. If we try to print “Hello World!” Without the quotation marks, we will receive an error message.
print(Hello World!)
Resulting in:
SyntaxError: invalid syntax