-
Notifications
You must be signed in to change notification settings - Fork 4
Your first program
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.
- 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.
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.
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.
- 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("\\")
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 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 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.
- The
print()
function is a built-in function. It prints/outputs a specified message to the screen/console window. - 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.
- To call a function (this process is known as
function invocation
orfunction 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. - Python strings are delimited with quotes, e.g.,
"I am a string"
(double quotes), or'I am a string, too'
(single quotes). - 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.
- 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. -
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. -
Keyword arguments
are the ones whose meaning is not dictated by their location, but by a special word (keyword) used to identify them. - The
end
andsep
parameters can be used for formatting the output of theprint()
function. Thesep
parameter specifies the separator between the outputted arguments, e.g.,print("H", "E", "L", "L", "O", sep="-")
, whereas theend
parameter specifies what to print at the end of the print statement.
source: Python Institute
- Introduction
- Variables
- Data Types
- Numbers
- Casting
- Strings
- Booleans
- Operators
- Lists
- Tuple
- Sets
- Dictionaries
- Conditionals
- Loops
- Functions
- Lambda
- Classes
- Inheritance
- Iterators
- Multi‐Processing
- Multi‐Threading
- I/O Operations
- How can I check all the installed Python versions on Windows?
- Hello, world!
- Python literals
- Arithmetic operators and the hierarchy of priorities
- Variables
- Comments
- The input() function and string operators
Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations
- Comparison operators and conditional execution
- Loops
- [Logic and bit operations in Python]
- [Lists]
- [Sorting simple lists]
- [List processing]
- [Multidimensional arrays]
- Introduction
- Sorting Algorithms
- Search Algorithms
- Pattern-matching Algorithm
- Graph Algorithms
- Machine Learning Algorithms
- Encryption Algorithms
- Compression Algorithms
- Start a New Django Project
- Migration
- Start Server
- Requirements
- Other Commands
- Project Config
- Create Data Model
- Admin Panel
- Routing
- Views (Function Based)
- Views (Class Based)
- Django Template
- Model Managers and Querysets
- Form
- User model
- Authentification
- Send Email
- Flash messages
- Seed
- Organize Logic
- Django's Business Logic Services and Managers
- TestCase
- ASGI and WSGI
- Celery Framework
- Redis and Django
- Django Local Network Access
- Introduction
- API development
- API architecture
- lifecycle of APIs
- API Designing
- Implementing APIs
- Defining the API specification
- API Testing Tools
- API documentation
- API version
- REST APIs
- REST API URI naming rules
- Automated vs. Manual Testing
- Unit Tests vs. Integration Tests
- Choosing a Test Runner
- Writing Your First Test
- Executing Your First Test
- Testing for Django
- More Advanced Testing Scenarios
- Automating the Execution of Your Tests
- End-to-end
- Scenario
- Python Syntax
- Python OOP
- Python Developer position
- Python backend developer
- Clean Code
- Data Structures
- Algorithms
- Database
- PostgreSQL
- Redis
- Celery
- RabbitMQ
- Unit testing
- Web API
- REST API
- API documentation
- Django
- Django Advance
- Django ORM
- Django Models
- Django Views
- Django Rest Framework
- Django Rest Framework serializers
- Django Rest Framework views
- Django Rest Framework viewsets