In the previous post, we installed Python and configured IDE. You can read about it in the following post.
Now, it's time to dive into code a bit to understand Python basics. We will start with the sample PyCharm Python script.
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Comments
Our Python script starts with the following lines.
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
A hash sign # that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. A comment is a readable explanation or annotation in the Python source code. They are added with the purpose of making the source code easier for humans to understand. Just like most modern languages, Python supports single-line and block comments.
Above comment could have been replaced with the block comment as follows.
'''
This is a sample Python script.
Press ⌃R to execute it or replace it with your code.
Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
'''
Keywords
Now let's take a look at another portion of the code.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
The line starts with def. It is a keyword. It is a reserved word that has predefined meanings and purposes. Keywords serve as fundamental building blocks and play a crucial role in defining the syntax and structure of the language. Keywords cannot be used as variable names or identifiers because their meanings are fixed and cannot be changed by the programmer. Python has multiple keywords and here is a full list of them.
Keyword Description and A logical operator used to combine conditions, which returns True if both conditions are True. as Used in import statements to create an alias for a module or to assign a new name to an object. assert Used for debugging purposes to check if a given condition is True, raising an exception if it is False. break Used to exit a loop prematurely, skipping the remaining iterations. class Used to define a new class, which serves as a blueprint for creating objects. continue Used to skip the current iteration in a loop and continue with the next iteration. def Used to define a new function or method. del Used to delete a variable or an item from a collection. elif Short for “else if,” used in conditional statements to test multiple conditions. else Used in conditional statements to specify the block of code to execute if the condition is False. except Used in exception handling to specify a block of code to execute when an exception is raised. False A boolean value representing the logical False. finally Used in exception handling to specify a block of code that always executes, regardless of whether an exception occurred or not. for Used to create loops that iterate over a sequence like a list, tuple, or string. from Used in import statements to import specific attributes or functions from a module. global Used inside a function to indicate that a variable declared within the function should be treated as global. if Used in conditional statements to check if a condition is True and execute a block of code accordingly. import Used to import modules or packages into the current script to access their functionality. in Used to check if a value is present in a sequence, such as a list or a string. is Used to check if two variables refer to the same object in memory. lambda Used to create anonymous functions (also known as lambda functions) quickly. None Represents the absence of a value, similar to null in other programming languages. nonlocal Used inside a nested function to indicate that a variable should refer to the variable in the enclosing scope, not the global scope. not A logical operator used to negate the value of a condition. or A logical operator used to combine conditions, which returns True if at least one of the conditions is True. pass Used as a placeholder when a statement is syntactically required but doesn’t need any code execution. raise Used to raise an exception manually. return Used to specify the value to be returned from a function. True A boolean value representing the logical True. try Used in exception handling to specify a block of code to test for exceptions. while Used to create loops that execute a block of code as long as a condition is True. with Used to simplify exception handling and resource management using context managers. yield Used in generator functions to produce a value to be returned.
Code blocks
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
Once we know what the def keyword means, we can get back to the sample code again. Here we can see that the print_hi function is defined, taking a single parameter - a name. The function's body consists of two lines:
Line with comment
# Use a breakpoint in the code line below to debug your script.
And line with another function call:
print(f'Hi, {name}') # Press ⌘F8 to toggle the breakpoint.
Calling the print function results in printing provided text, a string, on standard output, that in most cases is terminal. Later we will learn more about functions as well as built-in, library functions.
How can we know that mentioned function's body consists of 2 lines? The answer is pretty simple - it's defined by the code block.
In Python, a code block is a set of statements that are grouped together and executed as a single unit. Code blocks are defined using indentation. Indentation is a crucial aspect of Python and is used to determine the grouping of statements.
In this example, the code block is everything indented under the provided function named print_hi.
Strings
In Python, you can create strings using single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). In the following example, we use single quotes.
print_hi('PyCharm')
We can achieve the same using double quotes.
print_hi("PyCharm")
Or using triple quotes.
print_hi('''PyCharm''')
if __name__ == '__main__' idiom
It's time for another chunk of code which is called an idiom.
A programming idiom is the usual way to code a task in a specific language.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
The first line starts with an if statement - yet another keyword. Its purpose is to conditionally execute the code provided in the code block. Therefore it conditionally executes the print_me function.
Defining an entry point, a main function is useful if you want to write Python code which is intended to be "imported", but can also be run as a standalone shell script. The code protected by the if __name__
check runs when it's invoked as a command only, not when imported. Later we will learn more about modules and how to import them.
Interactive mode
In addition to scripting mode, Python offers interactive mode. It is known as the Python REPL (Read-Eval-Print Loop), which allows you to interactively run Python code line by line. It provides an environment where you can type Python commands or expressions, and they are immediately executed, displaying the results in real-time. This mode is useful for testing code snippets, experimenting with Python features, and learning Python interactively without writing complete scripts or programs. You can access Python’s interactive mode by running the python3
command in your terminal or command prompt without specifying a script to execute.
Let’s go through a simple example of Python’s interactive mode. If you have Python installed on your computer, you can open your terminal and type python3
to enter the interactive mode.
❯ python3
Python 3.11.4 (main, Jun 20 2023, 16:59:59) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
After entering the interactive mode, you’ll see the >>> prompt, indicating that you can start typing Python code.
Now, let’s try a simple arithmetic calculation:
>>> 2 + 3
5
>>>
In this example, we entered the expression 2 + 3, and Python immediately evaluated it, showing the result 5 on the next line.
To exit the Python interactive mode, simply type exit() or press Ctrl + D.
That’s the basic idea of Python’s interactive mode. It’s a great way to experiment with code and get immediate feedback on your expressions and statements.