Skip to content

Your first program

Amin Zamani edited this page Dec 15, 2023 · 11 revisions

The print() function

print("Hello, World!")

The word print that you can see here is a function name.

You've probably encountered the term function many times before, during math classes. You can probably also list several names of mathematical functions, like sine or log.

Python functions, however, are more flexible, and can contain more content than their mathematical siblings.

A function (in this context) is a separate part of the computer code able to:

  • cause some effect (e.g., send text to the terminal, create a file, draw an image, play a sound, etc.); this is something completely unheard of in the world of mathematics;
  • evaluate a value (e.g., the square root of a value or the length of a given text) and return it as the function's result; this is what makes Python functions the relatives of mathematical concepts.

Moreover, many of Python functions can do the above two things together.

Where do the functions come from?

  • They may come from Python itself; the print function is one of this kind; such a function is an added value received together with Python and its environment (it is built-in); you don't have to do anything special (e.g., ask anyone for anything) if you want to make use of it;
  • they may come from one or more of Python's add-ons named modules; some of the modules come with Python, others may require separate installation - whatever the case, they all need to be explicitly connected with your code (we'll show you how to do that soon);
  • you can write them yourself, placing as many functions as you want and need inside your program to make it simpler, clearer and more elegant.

The name of the function should be significant (the name of the print function is self-evident).

As we said before, a function may have:

  • an effect;
  • a result.

There's also a third, very important, function component - the argument(s).

Mathematical functions usually take one argument, e.g., sin(x) takes an x, which is the measure of an angle.

Python functions, on the other hand, are more versatile. Depending on the individual needs, they may accept any number of arguments - as many as necessary to perform their tasks. Note: any number includes zero - some Python functions don't need any argument.

print("Hello, World!")

In spite of the number of needed/provided arguments, Python functions strongly demand the presence of a pair of parentheses - opening and closing ones, respectively.

If you want to deliver one or more arguments to a function, you place them inside the parentheses. If you're going to use a function which doesn't take any argument, you still have to have the parentheses.

The only argument delivered to the print() function in this example is a string:

print("Hello, World!")

As you can see, the string is delimited with quotes - in fact, the quotes make the string - they cut out a part of the code and assign a different meaning to it.

You can imagine that the quotes say something like: the text between us is not code. It isn't intended to be executed, and you should take it as is.

Almost anything you put inside the quotes will be taken literally, not as code, but as data.

So far, you have learned about two important parts of the code: the function and the string. We've talked about them in terms of syntax, but now it's time to discuss them in terms of semantics.

The function name (print in this case) along with the parentheses and argument(s), forms the function invocation.

We'll discuss this in more depth soon, but we should just shed a little light on it right now.

What happens when Python encounters an invocation like this one below?

function_name(argument)

Let's see:

  • First, Python checks if the name specified is legal (it browses its internal data in order to find an existing function of the name; if this search fails, Python aborts the code);
  • second, Python checks if the function's requirements for the number of arguments allows you to invoke the function in this way (e.g., if a specific function demands exactly two arguments, any invocation delivering only one argument will be considered erroneous, and will abort the code's execution);
  • third, Python leaves your code for a moment and jumps into the function you want to invoke; of course, it takes your argument(s) too and passes it/them to the function;
  • fourth, the function executes its code, causes the desired effect (if any), evaluates the desired result(s) (if any) and finishes its task;
  • finally, Python returns to your code (to the place just after the invocation) and resumes its execution.

The print() function - The escape and newline characters

print("The itsy bitsy spider\nclimbed up the waterspout.")
print()
print("Down came the rain\nand washed the spider out.")

There are two very subtle changes - we've inserted a strange pair of characters inside the rhyme. They look like this: \n.

Interestingly, while you can see two characters, Python sees one.

The backslash \ has a very special meaning when used inside strings - this is called the escape character.

The word escape should be understood specifically - it means that the series of characters in the string escapes for the moment (a very short moment) to introduce a special inclusion.

In other words, the backslash doesn't mean anything in itself, but is only a kind of announcement, that the next character after the backslash has a different meaning too.

The letter n placed after the backslash comes from the word newline.

Both the backslash and the n form a special symbol named a newline character, which urges the console to start a new output line.

The itsy bitsy spider
climbed up the waterspout.

Down came the rain
and washed the spider out.

As you can see, two newlines appear in the nursery rhyme, in the places where the \n have been used.

This convention has two important consequences:

  1. If you want to put just one backslash inside a string, don't forget its escaping nature - you have to double it, e.g., such an invocation will cause an error:
print("\")

while this one won't:

print("\\")

Test print() with more than one argument

print("The itsy bitsy spider" , "climbed up" , "the waterspout.")

There is one print() function invocation, but it contains three arguments. All of them are strings.

The arguments are separated by commas. We've surrounded them with spaces to make them more visible, but it's not really necessary, and we won't be doing it anymore.

The console should now be showing the following text:

The itsy bitsy spider climbed up the waterspout.

Two conclusions emerge from this example:

  • a print() function invoked with more than one argument outputs them all on one line;
  • the print() function puts a space between the outputted arguments on its own initiative.

The print() function - the positional way of passing the arguments

The way in which we are passing the arguments into the print() function is the most common in Python, and is called the positional way (this name comes from the fact that the meaning of the argument is dictated by its position, e.g., the second argument will be outputted after the first, not the other way round).

The print() function - the keyword arguments

The mechanism is called keyword arguments. The name stems from the fact that the meaning of these arguments is taken not from its location (position) but from the special word (keyword) used to identify them.

The print() function has two keyword arguments that you can use for your purposes. The first of them is named end.

print("My name is", "Python.", end=" ")

any keyword arguments have to be put after the last positional argument (this is very important)

The console should now be showing the following text:

My name is Python. Monty Python.

As you can see, the end keyword argument determines the characters the print() function sends to the output once it reaches the end of its positional arguments.

The default behavior reflects the situation where the end keyword argument is implicitly used in the following way: end="\n".

The keyword argument that can separates its outputted arguments, this is named sep (like separator).

print("My", "name", "is", "Monty", "Python.", sep="-")

The print() function now uses a dash, instead of a space, to separate the outputted arguments:

My-name-is-Monty-Python.

Key takeaways

  1. The print() function is a built-in function. It prints/outputs a specified message to the screen/console window.
  2. Built-in functions, contrary to user-defined functions, are always available and don't have to be imported. Python 3.8 comes with 69 built-in functions. You can find their full list provided in alphabetical order in the Python Standard Library.
  3. To call a function (this process is known as function invocation or function call), you need to use the function name followed by parentheses. You can pass arguments into a function by placing them inside the parentheses. You must separate arguments with a comma, e.g., print("Hello,", "world!"). An "empty" print() function outputs an empty line to the screen.
  4. Python strings are delimited with quotes, e.g., "I am a string" (double quotes), or 'I am a string, too' (single quotes).
  5. Computer programs are collections of instructions. An instruction is a command to perform a specific task when executed, e.g., to print a certain message to the screen.
  6. In Python strings the backslash \ is a special character which announces that the next character has a different meaning, e.g., \n (the newline character) starts a new output line.
  7. Positional arguments are the ones whose meaning is dictated by their position, e.g., the second argument is outputted after the first, the third is outputted after the second, etc.
  8. Keyword arguments are the ones whose meaning is not dictated by their location, but by a special word (keyword) used to identify them.
  9. The end and sep parameters can be used for formatting the output of the print() function. The sep parameter specifies the separator between the outputted arguments, e.g., print("H", "E", "L", "L", "O", sep="-"), whereas the end parameter specifies what to print at the end of the print statement.

source: Python Institute

Python

Python Essentials 1 (PCEP)

Introduction to Python and computer programming

Data types, variables, basic I/O operations, and basic operators

Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations

Clean Code

Algorithms

Django

Django Rest Framework

API

pip

SQLAlchemy

FastAPI

Pytest

TDD

Git

Linux

Docker

Python Testing

Interview Questions

Clone this wiki locally