Python Syntax Essentials: Your Guide to Writing Smarter Code

Updated on September 14, 2024

Article Outline

Python is a widely used general-purpose, high-level programming language. It was developed by Guido van Rossum in 1991 and further developed by the Python Software Foundation. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions: Python 2 and Python 3. Both versions are quite different.

Running Basic Python Program

There are many ways to run Python programs. Look at the most widely used and common ways to run the Python program.

Python Hello World

The following program demonstrates the Print the Hello World ten times.

 

Program

def print_hello_world(count): for i in range(count): print("Hello, World! ({i + 1})") def main(): times_to_print = 10 print("Printing 'Hello, World!' {times_to_print} times:n") print_hello_world(times_to_print) if __name__ == "__main__": main()

Output

Printing 'Hello, World!' 10 times:  Hello, World! (1) Hello, World! (2) Hello, World! (3) Hello, World! (4) Hello, World! (5) Hello, World! (6) Hello, World! (7) Hello, World! (8) Hello, World! (9) Hello, World! (10)

Python Interactive Shell

The Python language also has an interactive shell. This shell is a command-line interface that allows you to execute the Python source code interactively. The Python shell supports functions, variables, and dynamically importing libraries. The Python shell includes built-in help functions for accessing documentation on various Python modules and functions.

 

Here is the step for running the Python interactive shell.

 

  • You can start the Python interpreter by typing python (or python3 on some systems) in the terminal or command prompt. We can run the Python commands interactively.
  • To exit, we must type the exit() or press Ctrl+D.
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Indentation in Python

Indentation is a fundamental aspect of Python’s syntax and is crucial for defining the structure of your source code. Other programming languages use the braces or block of keywords. However, Python language has the indentation to achieve this.  It is not just for the readability of the code. It affects the execution of the code.

 

The following program demonstrates the Indentation in Python.

 

Program

def greet(name): if name: print(f"Hello, {name}!") else: print("Hello, World!") greet("Alice") greet("") x = 10 name = "Alice" age = 30 height = 5.7 sum = 5 + 3 product = 4 * 7 is_equal = (5 == 5) is_greater = (5 > 3) and_result = (True and False) or_result = (True or False) print("Sum: {sum}, Product: {product}") print("Is equal: {is_equal}, Is greater: {is_greater}") print("Logical AND result: {and_result}, Logical OR result: {or_result}") temperature = 30 if temperature > 25: print("It's hot outside!") elif temperature > 15: print("The weather is pleasant.") else: print("It's cold outside!") for i in range(5): print(i) count = 0 while count < 5: print(count) count += 1 def add(a, b): return a + b result = add(3, 5) print("Addition result: {result}") fruits = ["apple", "banana", "cherry"] fruits.append("date") print("Fruits: {fruits}") student = {"name": "John", "age": 21} student["age"] = 22 print("Student: {student}") coordinates = (10.0, 20.0) print("Coordinates: {coordinates}") unique_numbers = {1, 2, 3, 4} print("Unique numbers: {unique_numbers}")

Output

Hello, Alice! Hello, World! Sum: 8, Product: 28 Is equal: True, Is greater: True Logical AND result: False, Logical OR result: True It's hot outside! 0 1 2 3 4 0 1 2 3 4   Addition result: 8 Fruits: ['apple', 'banana', 'cherry', 'date'] Student: {'name': 'John', 'age': 22} Coordinates: (10.0, 20.0) Unique numbers: {1, 2, 3, 4}

Python Variables

Python variables are very important for writing Python programs efficiently. Unlike other programming languages, you don’t need to explicitly declare a variable’s type. The Python language dynamically determines the type of variable based on the value. For example, we create a variable “num” and initialize it with an integer value, so the num type is int. Then, we store the float value in ‘nu.’ It becomes a ‘str’ type. This is called dynamic typing, which means a variable’s data type can change during runtime.

Python Identifiers

Python identifiers identify various entities in a Python program, such as variables, functions, classes, modules and other objects. Identifiers are fundamental to writing source code, allowing you to reference and manipulate these entities. Here are the rules for defining the Python Identifiers:

 

  • An identifier can include letters (a-z, A-Z), digits (0-9), and underscores (_).
  • The first character of identifiers must be a letter or an underscore. It cannot be a digit
  • Identifiers are case-sensitive. For example, myVar, MyVar, and MYVAR are considered different identifiers.
  • Identifiers are not the same as Python’s reserved keywords (e.g., if, else, while, class, etc.).
  • The identifier cannot include special characters like @, #, –

 

The following program demonstrates the Python Identifiers.

 

Program

my_var = 10 variable1 = 20 _hiddenVar = 30 className = "Example" def calculate_total(a, b): return a + b class MyClass: def __init__(self, value): self.value = value def display_value(self): print("The value is: {self.value}") result = calculate_total(5, 15) print("The result of the calculation is:", result) my_instance_variable = MyClass(42) my_instance_variable.display_value()

Output

The result of the calculation is: 20 The value is: 42

Python Keywords

Python keywords are reserved words that have special meaning in the programming language. We cannot use keywords as identifiers in Python (e.g., variable names and function names) because they are part of the language’s syntax. Below is the list of keywords in Python.

 

False None True and as assert break
class continue def del elif else except
finally for from global if import in
is lambda nonlocal Not or pass raise
return try while With yield

 

We can see all the Python keywords using the current version of Python using the source code.

import Keyword print(keyword.kwlist)

Comments in Python

Comments annotate source code in Python, making it easier to understand and maintain. The Python interpreter does not execute comments; they are meant purely for human readers. Here’s the breakdown of how comments work in Python.

Python Single Line Comment

In Python, Comments are used to explain and annotate the source code. The Python interpreter does not execute them, so they don’t affect the program’s behavior. They don’t affect the behavior of the program. Single-line comments are the simplest type and are meant to occupy just one line.

 

The following program demonstrates Comment in Python.

 

Program

first_name = "Neeraj" last_name = "Kumar" # print full name print(first_name, last_name)

Output

Neeraj Kumar

Python Multi-line Comment

Python does not have dedicated syntax for multi-line comments like other programming languages. However, you can achieve multi-line comments using two common approaches.  To create a multi-line comment, we can use multiple single-line comments by prefixing each line with the # symbol. This is the most straightforward method and is often preferred for its clarity

 

The following program demonstrates the multi-line comment example.

 

Program

""" This is a multi-line comment. You can write as much as you need here. The Python interpreter will ignore it. """ print("Hello, World!")

Multiple Line Statements

In Python, we can write multiple statements on a single line or split a long statement into multiple lines for better readability. We can separate multiple statements on the same line using a semicolon (;)). This feature makes the language more readable, so we have this feature and can break long statements in different ways.

Using Backslashes () 

In the Python language,  We can break statements into multiple lines using the backslash()> It is a very useful method when you are working with strings or mathematical operations in the Python language.

 

The following program demonstrates the program.

 

Program

sentence = "This is a very long sentence that we want to " "split over multiple lines for better readability." print(sentence) # For mathematical operations total = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 print(total)

Output

We want to split This long sentence over multiple lines for better readability. 45

Using Parentheses

We can split statements over multiple lines inside the parentheses without needing backslashes in the list, tuples, or function arguments.

 

The following program demonstrates the program.

 

Program

numbers = [1,2,3,4,5,7,8,9,] def total(num1, num2, num3, num4): print(num1+num2+num3+num4) total(54,53,44,33)

Output

184

Triple Quotes for Strings

We can also work with docstrings or multiline strings. We can use triple quotes (single “” or double “).

 

The following program demonstrates the Triple Quotes for Strings.

 

Program 

text = """HeroVired Interactive Live and Self-Paced Courses to help you enhance your programming. Practice problems and learn with live and online recorded classes with HeroVired courses. Offline Programs."""   print(text)

Output

HeroVired Interactive Live and Self-Paced Courses to help you enhance your programming. Practice problems and learn with live and online recorded classes with HeroVired courses. Offline Programs.

Quotation in Python

In Python, Strings can be enclosed using single, double, or triple quotes. Triple quotes allow for the creation of multiline strings. Double quotes are used to enclose a string that contains a single quote.

 

The following program demonstrates the Quotation in Python.

 

Program

text1 = "He said, 'I learned Python from the HeroVired" text2 =' He said," I have created a project using Python"' print(text1) print(text2)

Output

He said, 'I learned Python from the HeroVired He said," I have created a project using Python."

Continuation of Statements in Python 

In Python, when a statement spans multiple lines, you need a way to indicate that the statement continues on the next line. There are several methods for this.

Implicit Continuation 

Python language implicitly supports line continuation within parentheses (), square brackets [], and curly braces{}. This is often used in defining multi-line lists, tuples, and dictionaries of function arguments.

 

The following program demonstrates the implicit continuation.

 

Program

numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] result = max( 10, 20, 30, 40 ) dictionary = { "name": "Voldemort", "age": 25, "address": "123 Wonderland" } print(numbers) print(result) print(dictionary) numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] result = max( 10, 20, 30, 40 ) dictionary = { "name": "Computer ", "age": 25, "address": "1193 Wonderland" } print(numbers) print(result) print(dictionary)<strong> </strong>

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9] 40 {'name': 'Alice', 'age': 25, 'address': '123 Wonderland'}

Explicit Continuation

We can also use the backslash  ‘’ to indicate that a statement should continue on the next line.  It is known as an explicit line continuation.

 

The following program demonstrates the Explicit Continuation.

 

Program

# Explicit continuation str = "Hero Vired is computer science portal " "HeroVired uses that." print(str)<strong> </strong>

Output

Hero Vired is a computer science portal that HeroVired uses.

Strings

Strings in Python can span multiple lines using triple quotes (‘’’ or “). Furthermore, if two string literals are placed next to each other, Python will automatically concatenate them.

 

The following program demonstrates the Strings.

 

Program

text = ''' A Hero can help other Geek by writing an article on Hero''' message = "Hello, " "Vired!" print(text) print(message)

Output

A Hero can help other Geek by writing an article on Hero Hello, Vired!

Strings Literals in Python

String literals in Python are sequences of characters designed to represent textual data. They can be enclosed in single quotes (‘), double quotes (“), or triple quotes (‘’’ or “””). Each type of quoting method serves different purposes and offers flexibility in how text is represented and manipulated in the Python language.

 

The following program demonstrates the String Literals in Python.

 

Program

string1 = "Hello, Hero Vired" string2 =" Namaste Hero" multi_line_string = ''' Ram learned Python by reading a tutorial on HeroVired ''' print(string1) print(string2) print(multi_line_string)

Output

Hello, Hero Vired Namaste Hero   Ram learned Python by reading a tutorial on HeroVired

Command Line Arguments 

In Python, the command line arguments allow you to pass input to a script when executing it from the command line. This argument follows the script’s name and can be accessed within the script. 

 

The following program demonstrates the Command Line Arguments.

 

Program

import sys if len(sys.argv) < 2: print("Please provide numbers as arguments to sum.") sys.exit(1) try: total = sum(map(float, sys.argv[1:])) print(f"Sum: {total}") except ValueError: print("All arguments must be valid numbers.")<strong> </strong>

Output

Please provide numbers as arguments to sum.

Taking Input from User in Python

The ‘input()’ function in Python is used to get input from the user via the console. The function is called the program pauses and waits for the user to type in their input and press “Enter”. The function then returns the input data as a string. We can provide a prompt as an argument to the function to give the user instructions on what to enter.

 

The following program demonstrates the input function Python.

 

Program

def get_name(): """Prompt the user to enter their name and return it.""" return input("Please enter your name: ").strip() def get_age(): """Prompt the user to enter their age, validate the input, and return it.""" while True: try: age = int(input("Please enter your age: ").strip()) if age < 0: raise ValueError("Age cannot be negative.") return age except ValueError as e: print("Invalid input: {e}. Please enter a valid age.") def get_programming_experience(): """Prompt the user to enter whether they have programming experience and return it.""" while True: experience = input("Do you have any programming experience? (yes/no): ").strip().lower() if experience in ['yes', 'no']: return experience else: print("Invalid input. Please enter 'yes' or 'no'.") def main(): """Main function to interact with the user and provide feedback based on their input.""" name = get_name() age = get_age() experience = get_programming_experience() print("n--- User Profile ---") print("Name: {name}") print("Age: {age}") print("Programming Experience: {'Yes' if experience == 'yes' else 'No'}") if experience == 'yes': print("That's great! Keep up the good work with programming.") else: print("No worries! There are plenty of resources to help you get started with programming.") if __name__ == "__main__": main()

Output

Please enter your name: Neeraj Please enter your age: 23 Do you have any programming experience? (yes/no): yes  --- User Profile --- Name: {name} Age: {age} Programming Experience: {'Yes' if experience == 'yes' else 'No'} That's great! Keep up the good work with programming.

Conclusion

This article taught us about the Python syntax essentials, which are crucial for writing effective and efficient source code. Understanding fundamental elements such as variable assignments, control flow statements, functions, and data structures creates clear, maintainable, and robust programs. Embracing these essentials empowers you to solve problems more intuitively and innovate confidently in your programming endeavors.

FAQs
You create a string by enclosing text in single quotes (‘...’) or double quotes (“...”). For example   string1 = 'Hello' string2 = "World"
Lists are created using square brackets ([]) and can include multiple items separated by commas. For example   my_list =[1,2,3,4,5]
We can use a for loop to iterate over the items in a list. For example   for item in my_list: print(item)
The function name and parentheses use the def keyword, followed by a colon. for example   def greet(): print("Hello!")
Use the + operator to join strings together. For example   full_name = “Neeraj” + “ ”+ “Doe”

Updated on September 14, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved