Online Computer Courses Classes and Training Program

Python Syntax Tutorial

 

Python Syntax Tutorial

Introduction

Python is known for its simplicity and readability. Its syntax is straightforward and beginner-friendly, making it a popular choice for learning programming. In this tutorial, you will learn the basics of Python syntax, including how to write and structure code effectively.


1. Writing Your First Python Program

Python programs are written in plain text and saved with the .py extension.

Example: Hello World Program

# This is a comment
print("Hello, World!")

Explanation:

  • # is used for comments; these are ignored by Python.
  • print() is a built-in function to display output.

Output:

Hello, World!

2. Python Indentation

Python uses indentation to define blocks of code instead of braces {} like other languages.

Example: If-Else Statement

age = 18
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Explanation:

  • The if block starts with an indented line.
  • Indentation ensures the code is properly structured.

Output:

You are eligible to vote.

3. Python Variables and Data Types

Variables are containers for storing data. You don’t need to declare their type explicitly.

Example:

# Integer
x = 10
# Float
y = 20.5
# String
name = "Python"
print(x, y, name)

Output:

10 20.5 Python

4. Comments in Python

  • Single-line comment: Starts with #.
  • Multi-line comment: Enclosed in triple quotes (''' or """).

Example:

# This is a single-line comment
"""
This is a 
multi-line comment
"""
print("Comments are ignored by Python.")

Output:

Comments are ignored by Python.

5. Python Input and Output

  • Use input() to take user input.
  • Use print() for output.

Example:

name = input("Enter your name: ")
print("Hello, " + name)

Output:

Enter your name: Ajay  
Hello, Ajay

6. Conditional Statements

Python supports if, elif, and else for decision-making.

Example:

num = 10
if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

Output:

Positive number

7. Loops in Python

Python has for and while loops.

For Loop Example:

fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
    print(fruit)

Output:

Apple  
Banana  
Cherry

While Loop Example:

count = 1
while count <= 5:
    print(count)
    count += 1

Output:

1  
2  
3  
4  
5

8. Python Functions

Functions are reusable blocks of code.

Example:

def greet(name):
    print("Hello, " + name)

greet("Ajay")

Output:

Hello, Ajay

9. Python Syntax Rules

  1. Case Sensitivity: Python is case-sensitive (Name and name are different).
  2. Statements End with Newline: No need for semicolons (;).
  3. Comments: Use # for comments.
  4. Indentation: Use spaces or tabs, but be consistent.

10. Real-Life Example: Simple Calculator

# Simple Calculator
def calculator(a, b, operation):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        return a / b
    else:
        return "Invalid operation"

# Input
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
operation = input("Enter operation (add, subtract, multiply, divide): ")

# Output
result = calculator(a, b, operation)
print("Result:", result)

Output Example:

Enter first number: 10  
Enter second number: 5  
Enter operation (add, subtract, multiply, divide): add  
Result: 15

Conclusion

This tutorial covers the basics of Python syntax. Mastering these concepts will help you write clean and efficient Python code. Practice these examples and explore more advanced topics like classes, modules, and libraries to enhance your Python programming skills.


Here is a set of MCQs, Fill in the Blanks, True/False, and Question-Answer based on Python Syntax:


Multiple Choice Questions (MCQs)

Q1. What is the correct syntax to print "Hello, World!" in Python?
a) echo "Hello, World!"
b) print("Hello, World!")
c) printf("Hello, World!")
d) System.out.println("Hello, World!")

Answer: b) print("Hello, World!")


Q2. In Python, indentation is used for:
a) Separating statements
b) Defining code blocks
c) Comments
d) Importing modules

Answer: b) Defining code blocks


Q3. Which of the following is a valid variable name in Python?
a) 1name
b) name_1
c) name-1
d) name 1

Answer: b) name_1


Q4. Which data type is used to store a collection of key-value pairs in Python?
a) List
b) Tuple
c) Dictionary
d) Set

Answer: c) Dictionary


Q5. What is the output of the following code?

x = 5  
y = 3  
print(x // y)

a) 1
b) 1.666
c) 1.0
d) 2

Answer: d) 1


Fill in the Blanks

  1. The ______ function is used to display output in Python.
    Answer: print

  2. Python programs are saved with the extension ______.
    Answer: .py

  3. A block of code in Python is defined by proper ______.
    Answer: Indentation

  4. In Python, ______ is used to take input from the user.
    Answer: input()

  5. A ______ is an immutable data type in Python.
    Answer: Tuple


True/False

  1. Python is a case-sensitive language.
    Answer: True

  2. Indentation is optional in Python.
    Answer: False

  3. The # symbol is used for multi-line comments in Python.
    Answer: False

  4. Python supports both single-line and multi-line comments.
    Answer: True

  5. In Python, variables need to be declared with a specific data type.
    Answer: False


Question and Answer

Q1. What is Python used for?
Answer: Python is used for web development, data analysis, machine learning, automation, game development, and more.

Q2. How does Python handle blocks of code?
Answer: Python uses indentation to define blocks of code instead of braces {}.

Q3. What is the difference between a list and a tuple in Python?
Answer:

  • A list is mutable, meaning its elements can be modified.
  • A tuple is immutable, meaning its elements cannot be changed after creation.

Q4. How do you create a comment in Python?
Answer: Use the # symbol for single-line comments and triple quotes (''' or """) for multi-line comments.

Q5. What is the output of the following code?

name = "Python"  
print(name.upper())  

Answer: The output is PYTHON.


This structure covers multiple types of questions, making it easy for students to learn and revise Python Syntax.

Post a Comment

0 Comments