Python Syntax
Python is a versatile and beginner-friendly programming language known for its clean and readable syntax. Let’s explore Python’s basic syntax with practical examples.
1. Variables and Data Types in Python
Python allows you to create variables without explicitly declaring their data type. The interpreter determines the type automatically.
Example: Variables and Data Types
# Assigning values to variables
name = "Dharmender" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
# Printing variable values
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
Output:
Name: Dharmender
Age: 25
Height: 5.6
Is Student: True
2. Conditional Statements (if-else)
Conditional statements help execute code based on certain conditions.
Example: if-else Statement
score = 85
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
print("Grade:", grade)
Output:
Grade: B
3. Loops in Python
Python supports two main types of loops: for
and while
.
Example: For Loop
# Printing numbers from 1 to 5 using a for loop
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
4. Functions in Python
Functions allow you to organize your code into reusable blocks.
Example: Defining and Calling a Function
def greet(name):
return f"Hello, {name}!"
# Calling the function
message = greet("Dharmender")
print(message)
Output:
Hello, Dharmender!
5. Lists in Python
Lists are used to store multiple items in a single variable.
Example: List Operations
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print("First fruit:", fruits[0])
# Adding a new element
fruits.append("orange")
print("Updated list:", fruits)
Output:
First fruit: apple
Updated list: ['apple', 'banana', 'cherry', 'orange']
Keep Learning 🙂