First Python Program
In this section, we will explore the fundamental syntax of Python and execute a straightforward program that outputs "Hello World" to the console.
Python offers two methods for executing a program:
- Employing the interactive interpreter prompt
- Utilizing a script file
Let's discuss each one of them in detail.
Interactive interpreter prompt
Python offers the capability to run Python statements sequentially at the interactive prompt. This is particularly advantageous when we need to monitor the output of each individual line in our Python script.
To initiate interactive mode, access the terminal (or command prompt) and enter python (use python3 if both Python2 and Python3 are installed on your machine).
This will bring up the subsequent prompt, allowing us to run the Python command and observe its effects on the console.
Once you have completed the print statement, hit the Enter key.
In this instance, the output "Hello World !" is displayed on the console.
Using a script file (Script Mode Programming)
The interpreter prompt is ideally suited for executing single-line code statements. However, entering code directly into the terminal each time is not practical, and it proves to be inefficient for writing multiple lines of code.
By utilizing script mode, it is possible to compose multiple lines of code within a file that can be executed at a later time. To accomplish this, one must launch an editor such as Notepad, create a file with an appropriate name, and save it with a .py extension, indicating "Python." We will now proceed to implement the aforementioned example using script mode.
print ("hello world"); #here, we have used print() function to print the message on the console.
To execute the file designated as first.py, the subsequent command must be entered in the terminal.
Step - 1: Launch the Python interactive shell, click on "File," and select "New." This action will create a new blank script where we can input our code.
Step -2: At this point, input the code and use "Ctrl+S" to save the document.
Step - 3: Once the code has been saved, you can execute it by selecting "Run" or "Run Module". The output will then be shown in the shell.
The output will be shown as follows.
Step - 4: In addition, we can execute the file through the terminal of the operating system. However, it is important to know the directory path where our file is located.
- Access the command line interface and move to the directory.
- We must enter the python keyword, followed by the filename, and then press enter to execute the Python file.
Multi-line Statements
Multi-line statements are created in an editor resembling Notepad and are saved with a .py file extension. The subsequent example illustrates the execution of several lines of code utilizing a Python script.
Code:
name = "Sarah Ahmed"
branch = "Computer Science"
age = "25"
print("My name is: ", name, )
print("My age is: ", age)
Script File:
Pros and Cons of Script Mode
The script mode has few advantages and disadvantages as well. Let's understand the following advantages of running code in script mode.
- We can run multiple lines of code.
- Debugging is easy in script mode.
- It is appropriate for beginners and also for experts.
Let’s examine the drawbacks of the script mode.
- We must save the code each time we modify it.
- It can become cumbersome when executing just a single line or a small number of lines of code.
Get Started with PyCharm
In our initial program, we employed gedit as the editing tool on our CentOS system. For Windows users, alternatives such as Notepad or Notepad++ are available for code editing. Nonetheless, these editors do not function as integrated development environments (IDEs) for Python, as they lack the capability to provide syntax-related suggestions.
JetBrains offers PyCharm, a highly popular and extensively utilized cross-platform integrated development environment (IDE) for executing Python programs.
PyCharm installation
As previously mentioned, PyCharm is an integrated development environment (IDE) that is compatible across multiple platforms, allowing it to be installed on various operating systems. In this segment of the tutorial, we will discuss the steps necessary to install PyCharm on Windows, MacOS, CentOS, and Ubuntu.
Windows
The installation of PyCharm on a Windows system is quite straightforward. To begin the installation process, navigate to the link https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows to obtain the executable installer. After downloading, double-click the installer (.exe) file and proceed with the installation by selecting "Next" at each stage.
To develop an initial program in PyCharm, adhere to the subsequent steps.
Step - 1. Launch the Pycharm editor. Select the "Create New Project" option to initiate the creation of a new project.
Step - 2. Select a location to save the project.
- We can save the newly created project at desired memory location or can keep file location as it is but atleast change the project default name untitled to "FirstProject" or something meaningful.
- Pycharm automatically found the installed Python interpreter.
- After change the name click on the "Create" Button.
Step - 3. Navigate to the "File" menu and choose "New." Upon selecting the "New" option, a range of file formats will be displayed. Choose the "Python File."
Step - 4. Next, enter the name of the Python file and select "OK". We have created "FirstProgram".
Step - 5. Next, input the initial program - print("Hello World"), and then select the "Run" menu to execute the program.
Step - 6. The results will be displayed at the lower section of the screen.
Basic Syntax of Python
Indentation and Comment in Python
Indentation serves as a crucial concept within the Python programming language. Incorrect application of indentation can lead to an "IndentationError" in your code.
Indentation refers to the inclusion of whitespace before a statement when necessary. In the absence of proper indentation, Python cannot determine the subsequent statement to execute. Additionally, indentation clarifies the association of statements within specific blocks. If indentation is missing or incorrect, an "IndentationError" will be raised, halting the execution of the code.
In Python, indentation indicates which statements are part of a specific block. In contrast, programming languages like C, C++, and Java utilize curly braces {} to delineate code blocks.
In Python, statements that are aligned at the same level to the right are considered part of the same block. We can utilize four spaces to establish indentation. Examine the following lines of code.
Example -
list1 = [1, 2, 3, 4, 5]
for i in list1:
print(i)
if i==4:
break
print("End of for loop")
Output:
1
2
3
4
End of for loop
Explanation:
In the code provided, the for loop contains its own block of code, and the if statement includes a code block nested within the for loop. Both of these are indented using four spaces. The final print statement is not indented, indicating that it is not part of the for loop.
Comments in Python
Annotations play a crucial role in clarifying the code, aiding both ourselves and others in comprehending it. By examining the comments, we can swiftly grasp the purpose behind each line of code we have crafted. Additionally, this facilitates the identification of errors, allowing us to rectify them efficiently and apply the solutions in other projects.
In Python, comments can be created using the # symbol. Lines that follow a hash symbol are completely disregarded by the Python interpreter. A proficient programmer consistently utilizes comments to enhance code clarity. Consider the subsequent example of a comment.
name = "Rahul" # Assigning string value to the name variable
It is possible to insert comments on each line of the Python code.
Fees = 10000 # defining course fees is 10000
Fees = 20000 # defining course fees is 20000
Inserting comments into any segment of the code where the function is not immediately clear is advisable. This practice is essential for developers to adopt while engaged in coding activities.
Types of Comment
Python offers the capability to create comments in two forms: single-line comments and multi-line comments.
Single-Line Comment - A single-line comment begins with the hash # symbol, succeeded by text for additional clarification.
# defining the marks of a student
Marks = 90
Additionally, it is possible to include a comment adjacent to a code statement. Take a look at the example below.
Name = "James" # the name of a student is James
Marks = 90 # defining student's marks
Branch = "Computer Science" # defining student branch
Multi-Line Comments - Python lacks direct support for multi-line comments; however, we can utilize the hash # symbol to comment out several lines. For instance -
# we are defining for loop
# To iterate the given list.
# run this code.
We can also use another way.
" " "
This is an example
Of multi-line comment
Using triple-quotes
" " "
This is the fundamental overview of comments. For an in-depth understanding, please refer to our Python Comment tutorial.
Python Identifiers
Python identifiers refer to a name used to identify a variable, function, module, class, module or other objects. There are few rules to follow while naming the Python Variable.
- A variable name must start with either an English letter or underscore (_).
- A variable name cannot start with the number.
- Special characters are not allowed in the variable name.
- The variable's name is case sensitive.
Let's understand the following example.
Example -
number = 10
print(num)
_a = 100
print(_a)
x_y = 1000
print(x_y)
Output:
10
100
1000
We have outlined the fundamental syntax of the Python programming language. It is essential to understand the core principles common to all programming languages. Once we internalize these concepts, the process of learning Python will become more manageable.
CentOS
To set up PyCharm on CentOS, navigate to the link how-to-install-pycharm-on-centos. This link will provide instructions for installing PyCharm on your CentOS system.
MacOS
To set up PyCharm on MacOS, navigate to the link how-to-install-pycharm-on-mac. This link will provide instructions for installing PyCharm on your MacOS system.
Ubuntu
To set up PyCharm on Ubuntu, refer to the link how-to-install-pycharm-in-ubuntu. This link will provide you with instructions on installing PyCharm on your Ubuntu system.