Python Syntax

Python is a high-level, interpreted programming language that is widely used for scripting, automation, web development, data analysis, and machine learning. The syntax of Python is concise, expressive, and easy to learn, making it a favorite language for beginners and experts alike.

In this blog, we will discuss the basic syntax of Python with the help of some code snippets.

  1. Variables

Variables are used to store data values in Python. To create a variable, you just need to assign a value to it using the assignment operator (=). Python supports dynamic typing, which means you can assign a value of any type to a variable without declaring its type.

Example:

#creating variables
a = 10
b = "hello"
c = True

#printing variables
print(a)
print(b)
print(c)

Output:

10
hello
True
  1. Data Types

Python supports several built-in data types such as integer, float, string, boolean, list, tuple, set, and dictionary. You can also define your own custom data types using classes.

Example:

#declaring variables of different data types
num = 10 #integer
pi = 3.14 #float
name = "John" #string
is_male = True #boolean
fruits = ['apple', 'banana', 'orange'] #list
person = ('John', 30, 'Male') #tuple
ages = { 'John': 30, 'Mary': 25, 'Bob': 40 } #dictionary

#printing the values
print(num)
print(pi)
print(name)
print(is_male)
print(fruits)
print(person)
print(ages)

Output:

10
3.14
John
True
['apple', 'banana', 'orange']
('John', 30, 'Male')
{'John': 30, 'Mary': 25, 'Bob': 40}
  1. Conditional Statements

Conditional statements are used to execute different code blocks based on a certain condition. Python supports if, elif, and else statements for conditional execution.

Example:

#using if statement
a = 10
b = 20
if a > b:
    print("a is greater than b")
else:
    print("b is greater than a")

#using if-elif-else statement
age = 30
if age < 18:
    print("You are a minor")
elif age >= 18 and age < 60:
    print("You are an adult")
else:
    print("You are a senior citizen")

Output:

b is greater than a
You are an adult
  1. Loops

Loops are used to iterate over a sequence of values and perform some operations on each value. Python supports two types of loops – for loop and while loop.

Example:

#for loop
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(fruit)

#while loop
i = 1
while i <= 10:
    print(i)
    i += 1

Output:

apple
banana
orange
1
2
3
4
5
6
7
8
9
10
  1. Functions

Functions are used to group a set of statements into a reusable code block. Python allows you to define your own functions using the def keyword.

Example:

#defining a function
def greet(name):
    print("Hello, " + name)

#calling a function
greet("John")
greet("Mary")

Output:

Hello, John
Hello, Mary