Skip to content

Basic Syntax of Python Programming

Python shares similarities with other programming languages like Perl, C, and Java, but it also introduces some distinct differences that set it apart. Let’s dive into writing and executing our first Python program, and explore the different modes in which Python can be executed.

Let’s write and execute our 1st Python Program. Python can be executed in different modes:

  • Interactive Shell Mode
  • Script Mode Programming

The Interactive Shell, also known as the Python REPL (Read-Eval-Print Loop), allows you to execute Python code line by line and immediately see the results. This is especially useful for testing small code snippets or experimenting with Python commands.

  • Open a terminal (Linux/macOS) or Command Prompt (Windows).
  • Type python (or python3 if Python 3 is installed alongside Python 2) and press Enter.

You’ll see a Python prompt >>>, indicating that the Python interpreter is ready to execute commands. Here, the print() function outputs text to the console, and you see the result instantly.

Terminal window
Microsoft Windows [Version 10.0.26100.3775]
(c) Microsoft Corporation. All rights reserved.
C:\Users\ThisPC>python
Python 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 14:47:33) [MSC v.1943 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World
>>> 5*1
5
>>> 5*2
10
>>> 5*3
15
>>> 5*4
20
>>> 5*5
25
>>> 5*6
30
>>> 5*7
35
>>> 5*8
40
>>> 5*9
45
>>> 5*10
50
>>>exit()
C:\Users\This Pc>
  • Immediate feedback: Every line of code is executed as soon as you press Enter.
  • Great for quick calculations, testing functions, or learning Python basics.
  • You can exit the shell by typing exit() or pressing Ctrl + D.

In this mode, you write your Python code in a file (with a .py extension) and execute the file. This is typically used for writing complete Python programs. We will use this mode or method throughout this tutorial.

print("Hello World!")

By this point, I guess we all have the same Question?

How did this .py file got executed by Python? Is python an Interpreted or a Compiled Language?


Comments are used to write something which the programmer does not want to execute. This can be used to mark author name, date etc.

  1. Single Line Comment
    It is used to write a single line comment just add a ‘#’ at the start of the line.

    # This is a Single-Line Comment
  2. Multi Line Comment
    Multiline Comments: To write multi-line comments you can use ‘#’ at each line or you can use the multiline string (""" """). It is often referred as Python Doc String, which is important for Python based projects to let other programmers know what the function does. We will know about functions in the upcoming chapters!

    """This is an amazing example of a Multiline comment!"""

  • The print () function prints the specified message to the screen, or other standard output device.
  • The message can be a string, or any other object, the object will be converted into a string before written to the screen.
print(object(s), sep=separator, end=end, file=file, flush=flush)
ParameterDescription
object/ objectsAny object, and as many as you like. Will be converted to string before being printed.
sepOptional. Specifies how to separate the objects if there is more than one. Default is ' '.
endOptional. Specifies what to print at the end. Default is '\n' (line feed).
fileOptional. An object with a write method. Default is sys.stdout.
flushOptional. Boolean. If True, the output is flushed. If False, it is buffered. Default is False.

1. Print More Than One Object: You can print multiple objects or strings by separating them with commas.

print("Hello", "how are you?")
# Output: Hello how are you?

2. Print Two Messages with a Custom Separator: The sep parameter lets you specify how multiple objects will be separated in the output.

print("Hello", "how are you?", sep="---")
# Output: Hello---how are you?

3. Print a Variable: You can easily print variables in Python.

x = "Akash"
print(x)
# Output: Akash

4. Multiline String: Python supports multi-line strings using triple quotes (''' or """). This is useful for longer texts or formatting large outputs.

multiline_text = """This is a multiline string.
You can write across multiple lines.
It's very useful for longer outputs."""
print(multiline_text)

5. Formatted Print Statement Using f-strings: With f-strings (formatted string literals), you can embed expressions inside string literals using curly braces {}. This is useful for dynamically displaying values in strings.

name = "Akash"
age = 20
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Akash and I am 20 years old.


  • A variable is the name given to a memory location in a program.
  • This means that when you create a variable you reserve some space in the memory.

Based on the data type of a variable, Python interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, Python assign’s different data types to variables. For example:

a = 30 # variables = container to store a value.
b = "Akash" # keywords = reserved words in python
c = 71.22 # identifiers = class/function/variable name

Rules for Choosing an identifier / Variable:

Section titled “Rules for Choosing an identifier / Variable:”

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables are:-

  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • A variable name cannot be any of the Python keywords.

You can also view this, in the Interactive Shell Mode as discussed Earlier

Terminal window
>>> help()
Welcome to Python 3.13's help utility...Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules...enter "modules spam"...enter "q", "quit" or "exit".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
myVar = "Akash"
MYVAR = "Akash"
myvar2 = "Akash"
myvar = "Akash"
my_var = "Akash"
_my_var = "Akash"

  • In general, the data types are used to define the type of a variable. It represents the type of data we are going to store in a variable and determines what operations can be done on it.
  • Python data types are actually classes, and the defined variables are their instances or objects.
  • Since Python is dynamically typed, the data type of a variable is determined at runtime based on the assigned value.
  • Numeric Data Types

    • int
    • flot
    • complex
  • String Data Types

  • Sequence Data Types

    • list
    • tuple
    • range
  • Binary Data Types

    • bytes
    • bytearray
    • memoryview
  • Dictionary Data Type

  • Set Data Type

    • set
    • frozenset
  • Boolean Data Type

  • None Data Type

We can also check the type of datatype in python using the type() function like this:

a = 71
b =88.44
name = "Akash"
print (type(a))
print (type(b))
print (type(name))
  • Typecasting refers to converting one data type into another. Python allows us to change the type of a variable using built-in functions such as int(), float(), and str().
  • However, the conversion is only possible if the content of the variable can logically be converted to the target type.
str (31) =>"31" # integer to string conversion
int ("32") => 32 # string to integer conversion
float (32) => 32.0 # integer to float conversion
#...and so on

  • The input() function in Python is used to take user input from the keyboard via the terminal as a string.
  • It allows the program to interact with the user, letting them provide data, which is then processed during the execution of the program.
name = input("Enter your name: ")
print(f"Hello, {name}!")

Output:

Enter your name: Akash
Hello, Akash!

The value returned by the input() function is always a string by default, even if the user enters a number.

age = input("Enter your age: ")
print(type(age)) # This will show <class 'str'>

If you want to work with numbers (e.g., for calculations), you’ll need to convert the input into the appropriate data type using typecasting.

age = int(input("Enter your age: "))
print(f"You are {age} years old.")
price = float(input("Enter the price: "))
print(f"The price is {price}.")