Basic Syntax of Python Programming
Basic Syntax
Section titled “Basic Syntax”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.
First Python Program
Section titled “First Python Program”Let’s write and execute our 1st Python Program. Python can be executed in different modes:
- Interactive Shell Mode
- Script Mode Programming
1. Interactive Shell Mode
Section titled “1. Interactive Shell Mode”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.
How to access Interactive Shell Mode?
Section titled “How to access Interactive Shell Mode?”- 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.
Microsoft Windows [Version 10.0.26100.3775](c) Microsoft Corporation. All rights reserved.
C:\Users\ThisPC>pythonPython 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 14:47:33) [MSC v.1943 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> print("Hello World")Hello World>>> 5*15>>> 5*210>>> 5*315>>> 5*420>>> 5*525>>> 5*630>>> 5*735>>> 5*840>>> 5*945>>> 5*1050>>>exit()C:\Users\This Pc>
Key features of Interactive Shell Mode:
Section titled “Key features of Interactive Shell Mode:”- 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 pressingCtrl + D
.
2. Script Mode Programming
Section titled “2. Script Mode Programming”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!")
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 in Python
Section titled “Comments in Python”Comments are used to write something which the programmer does not want to execute. This can be used to mark author name, date etc.
Types of Comments
Section titled “Types of Comments”-
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 -
Multi Line Comment
Multiline Comments: To writemulti-line comments
you can use ‘#’ at each line or you can use the multiline string(""" """)
. It is often referred asPython Doc String
, which is important for Python based projects to let other programmers know what thefunction
does. We will know about functions in the upcoming chapters!"""This is an amazing example of a Multiline comment!"""
Print Function
Section titled “Print Function”- 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.
Syntax:
Section titled “Syntax:” print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Values:
Section titled “Parameter Values:”Parameter | Description |
---|---|
object/ objects | Any object, and as many as you like. Will be converted to string before being printed. |
sep | Optional. Specifies how to separate the objects if there is more than one. Default is ' ' . |
end | Optional. Specifies what to print at the end. Default is '\n' (line feed). |
file | Optional. An object with a write method. Default is sys.stdout . |
flush | Optional. Boolean. If True , the output is flushed. If False , it is buffered. Default is False . |
Examples:
Section titled “Examples:”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 = 20print(f"My name is {name} and I am {age} years old.")# Output: My name is Akash and I am 20 years old.
Variables and Data Types
Section titled “Variables and Data Types”Variables
Section titled “Variables”- 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 pythonc = 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.
List of Python keywords:
Section titled “List of Python keywords:”You can also view this, in the Interactive Shell Mode as discussed Earlier
>>> help()Welcome to Python 3.13's help utility...Enter the name of any module, keyword, or topic to get help on writingPython 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 orNone continue global passTrue def if raiseand del import returnas elif in tryassert else is whileasync except lambda withawait finally nonlocal yieldbreak for not
Examples:
Section titled “Examples:” myVar = "Akash" MYVAR = "Akash" myvar2 = "Akash" myvar = "Akash" my_var = "Akash" _my_var = "Akash"
2myvar = "John" my-var = "John" my var = "John"
Data types
Section titled “Data types”- 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.
Built-In Data Types in Python
Section titled “Built-In Data Types in Python”-
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))
<class 'int'> <class 'float'> <class 'str'>
Typecasting - Type Conversion
Section titled “Typecasting - Type Conversion”- 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()
, andstr()
. - 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 conversionint ("32") => 32 # string to integer conversionfloat (32) => 32.0 # integer to float conversion#...and so on
Input Function
Section titled “Input Function”- The
input()
function in Python is used to take user input from the keyboard via the terminalas 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.
Examples
Section titled “Examples”1. Taking Simple Input & Printing It
Section titled “1. Taking Simple Input & Printing It”name = input("Enter your name: ")print(f"Hello, {name}!")
Output:
Enter your name: AkashHello, Akash!
2. Input Data as Strings
Section titled “2. Input Data as Strings”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'>
3. Converting Input to Other Data Types
Section titled “3. Converting Input to Other Data Types”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.
• Convert Input to Integer:
Section titled “• Convert Input to Integer:”age = int(input("Enter your age: "))print(f"You are {age} years old.")
• Convert Input to Float:
Section titled “• Convert Input to Float:”price = float(input("Enter the price: "))print(f"The price is {price}.")