![]() |
VOOZH | about |
We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.
Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.
Follow TNS on your favorite social media networks.
Become a TNS follower on LinkedIn.
Check out the latest featured and trending stories while you wait for your first TNS newsletter.
Every programming language has a unique syntax. Some languages borrow syntax from others, while others create something wholly different. No matter the language you intend to use, you have to understand its syntax; otherwise, you’ll struggle to get anything done.
Syntax is a set of rules that define how code is written in a particular language. Some of the key elements of a language’s syntax include:
Let’s take a look at basic Python syntax, which is comprised of the same items above with the addition of:
Here’s a basic Python script that shows most of the elements that make up the basic syntax:
# Variable Declaration and Assignment
x = 5 # Integer variable assignment with ‘=’ symbol. The value of x is set to 5.
y = “Hello!” # String variable assignment – Strings are defined using the quotes “” around text content!
# Conditional Statements
if y == “Hello”:
print(“Greeting found!”)
else:
print(“No greeting message”)
# Loops & Repetition
fruits = [“apple”, “banana”, “cherry”] # Create a list of fruits, using square brackets!
for fruit in fruits: # Loop through the ‘fruits’ list. Each time it enters the loop, it will execute this line
print(fruit)
def greet_user(name):
“””This function greets a user by name.””” # A comment describing what the function does. It can be helpful to understand how it works!
print(f”Hello, {name}!”) # Using f-strings for string formatting (allows easy replacement of placeholders with variables)
greet_user(“Alice”) # Call ‘greet’ and pass in a name as an argument
A breakdown of the code looks like this:
Now that you’ve seen how the code is laid out, let’s write our first Python program. As is usually the case, we’ll create a Hello, World! application and demonstrate how it works in both interactive and script mode.
Interactive Mode is exactly what it sounds like: it’s a way to use Python interactively. Instead of creating a file with your code, you run statements through an interpreter via the terminal window.
To access Python’s Interactive Mode, open your terminal window and type:
python3
Your prompt should change to:
>>>
At that prompt, type the following:
print(“Hello, New Stack!”)
The output should be:
Hello, New Stack!
That was simple, right?
To exit interactive mode, type the following:
exit()
Hit Enter and you’ll be back at your usual prompt.
Let’s do the same thing with script mode.
With Script Mode, you create a file that houses your code. For example, let’s create the file helloworld.py with the command:
nano helloworld.py
If you’re using a different operating system than Linux, you’ll need to alter the above command to use your default text editor.
Notice the file ends in .py, which indicates the file is a Python script. You don’t have to use the .py extension, but it’s best to do so.
In that file, type the same line you entered during Interactive Mode like so:
print(“Hello, New Stack!”)
Save and close the file with the Ctrl-X keyboard shortcut.
Congratulations, you’ve just written your first Python program.
You’ve already seen how to run the Interactive Mode, but now let’s find out how to run that first program you created, helloworld.py. We do this by using the python3 command like so:
python3 helloworld.py
As expected, the output will be:
Hello, New Stack!
The key principles of Python indentation and whitespace include:
The Key Principles:
There are two types of comments in Python: single-line and multiple-line. A single-line comment might look like this:
# This is my comment
The best way to add a multiline comment in Python is with docstrings, which are encased in triple quotes like this:
“””This is my comment.
I love this comment.
It is the best comment.”””
Everything in between the triple quotes is ignored by Python.
There are different types of operators and expressions for Python. You have:
An if-else statement is used to execute a block of code when a certain condition is met. It checks for truth values and executes the corresponding code blocks based on these values.
The basic syntax of an if-else statement looks like this:
if expression:
# Code block to be executed if the condition is true
elif [optional]:
# Alternative code block to be executed if the initial condition is false, but this one evaluates to True
else:
# Default code block to be executed if none of the above conditions are met
Python has two different types of control statements that are used for repetition:
Here’s a simple example of a Python loop:
# example using an integer variable and range()
for i in range(5):
print(i)
fruits = [‘apple’, ‘banana’, ‘cherry’]
for fruit in fruits:
print(fruit)
A function is a block of code that can be executed multiple times from different parts of a program. Functions make up the core structure of any well-written piece of software and are defined as such:
Here’s a sample function definition:
def greet(name):
print(“Hello ” + name)
That function can be called from within a Python script like so:
greet(‘John’)
# Outputs: Hello John
You can also return values to their callers using the return statement like this:
def add(x,y):
return (x+y)
result = add(1,2) # Outputs:3
print(result)
Python also allows you to import and use various modules. Modules are pre-written Python source files that serve different purposes. For example, you could use the built-in datetime module like this:
print(“Current date:”,datetime.datetime.now())
You could also import modules for use in your code. For example, there’s the time module. To import a module, you use the import keyword like so:
import time
You could then call that module like this:
time.sleep(5) # Wait for 5 seconds. Outputs: Output nothing (sleeps)
Python provides several ways to handle errors, but the most important is the try-except block, which is used to catch and handle exceptions that may occur during the execution of your code.
There are two parts to the try-except block:
Here’s an example of a try-except block:
try:
num = int(input(“Enter a number: “))
result = 5 / num
except ZeroDivisionError:
print(“Cannot divide by zero!”)
except ValueError:
print(“Invalid input. Please enter an integer.”)
else:
# Code to be executed if no exception is raised
print(f”Result: {result}”)
PEP 8 provides a set of rules for writing clean and maintainable Python code, which are:
Python is one of the easiest programming languages to learn, which makes it a good choice for your first go at coding. If you follow the above suggestions, your experience will be far easier, especially as you get deeper involved with complex applications.