Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“š Python Introduction: Practice Assignments

Python Introduction Practice Assignments

Build a strong foundation with these introductory Python practice problems.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • About These Assignments
  • Character Set
  • Tokens in Python
  • Variables & Identifiers
  • Data Types
  • Operators & Expressions
  • Constants
  • Assignment Statements
  • Input / Output
  • Simple Python Scripts
  • Namespace
  • Try It Yourself
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link

About These Assignments

This page contains practice assignments covering all the foundational concepts of Python programming. Each problem is designed to:

  • Reinforce your understanding of Python fundamentals
  • Apply concepts to real-world scenarios
  • Build problem-solving skills step by step
  • Prepare you for coding interviews
🟢 Beginner 🟠 Intermediate šŸ”“ Advanced

šŸ’” Tip: Try solving each problem on your own first. Click the "Show Solution" button only after you've attempted the problem. This approach will help you learn more effectively.

1. Character Set 3 Questions

šŸŽÆ Learning Goal: Understand Python's character set — letters, digits, and special symbols used in Python programs.
Beginner Q1: Identify Valid Characters
Scenario: You're learning Python basics. Write a program that prints all the letters from 'a' to 'z' and 'A' to 'Z' to understand Python's character set.
šŸ’” Solution:
import string
print("Lowercase letters:", string.ascii_lowercase)
print("Uppercase letters:", string.ascii_uppercase)
print("Digits:", string.digits)
print("Punctuation:", string.punctuation)
# Output shows all characters Python supports
šŸ“– Explanation:

Python's character set includes letters (a-z, A-Z), digits (0-9), and special symbols. This exercise helps you understand what characters are valid in Python programs.

Beginner Q2: Check if Character is Alphanumeric
Scenario: You're building a username validator. Write a program that checks if a character is a letter or a digit using isalnum().
šŸ’” Solution:
char = 'A'
print(f"'{char}' is alphanumeric: {char.isalnum()}") # True
char = '#'
print(f"'{char}' is alphanumeric: {char.isalnum()}") # False
šŸ“– Explanation:

Python's character set includes letters and digits as alphanumeric characters. The isalnum() method checks if a character belongs to this set. This is used in validation systems.

Intermediate Q3: Count Character Types
Scenario: You're analyzing a text document. Write a program that counts how many letters, digits, and special characters are in a given string.
šŸ’” Solution:
text = "Hello123!@#"
letters = sum(1 for c in text if c.isalpha())
digits = sum(1 for c in text if c.isdigit())
special = len(text) - letters - digits
print(f"Letters: {letters}, Digits: {digits}, Special: {special}")
# Output: Letters: 5, Digits: 3, Special: 3
šŸ“– Explanation:

This problem demonstrates how to classify characters using Python's character set categories. This is used in text processing and data cleaning applications.

2. Tokens in Python 4 Questions

šŸŽÆ Learning Goal: Master Python tokens — keywords, identifiers, literals, operators, and delimiters.
Beginner Q4: Identify Python Keywords
Scenario: You're learning Python syntax. Write a program that lists all Python keywords using the keyword module.
šŸ’” Solution:
import keyword
print("Python Keywords:")
print(keyword.kwlist)
print(f"Total keywords: {len(keyword.kwlist)}")
šŸ“– Explanation:

Keywords are reserved words in Python that have special meaning. They cannot be used as variable names. This exercise helps you identify and remember them.

Beginner Q5: Check if a Name is a Valid Identifier
Scenario: You're building a code validator. Write a program that checks if a given name is a valid Python identifier using isidentifier().
šŸ’” Solution:
names = ["my_var", "2var", "var_123", "if", "hello_world"]
for name in names:
print(f"'{name}' is valid: {name.isidentifier()}")
# Output: my_var: True, 2var: False, var_123: True, if: False, hello_world: True
šŸ“– Explanation:

Identifiers are names given to variables, functions, and classes. They must start with a letter or underscore, followed by letters, digits, or underscores. This is used in code analysis tools.

Intermediate Q6: Tokenize a Python Expression
Scenario: You're building a simple code analyzer. Write a program that splits a Python expression into tokens (keywords, identifiers, operators, literals).
šŸ’” Solution:
import tokenize
from io import StringIO
code = "x = 10 + 20 * 3"
tokens = tokenize.generate_tokens(StringIO(code).readline)
for tok in tokens:
print(f"{tok.type} -> {tok.string}")
# Shows token types and their values
šŸ“– Explanation:

Python code is broken into tokens (keywords, identifiers, operators, literals, etc.) during compilation. This demonstrates how Python parses code. Used in code analysis and linters.

3. Variables & Identifiers 4 Questions

šŸŽÆ Learning Goal: Master variable naming rules, assignment, and dynamic typing in Python.
Beginner Q7: Create Variables with Different Data Types
Scenario: You're storing user profile information. Create variables for name (string), age (integer), height (float), and is_student (boolean).
šŸ’” Solution:
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
print(f"Name: {name}, Age: {age}, Height: {height}, Student: {is_student}")
šŸ“– Explanation:

Variables store different types of data. Python is dynamically typed — you don't need to declare the type. This exercise demonstrates basic variable creation and usage.

Intermediate Q8: Swap Two Variables Without Using a Third Variable
Scenario: You're optimizing code. Write a program that swaps the values of two variables using Python's tuple unpacking feature.
šŸ’” Solution:
a = 10
b = 20
print(f"Before: a = {a}, b = {b}")
a, b = b, a # Swap using tuple unpacking
print(f"After: a = {a}, b = {b}")
# Output: Before: a = 10, b = 20
# After: a = 20, b = 10
šŸ“– Explanation:

Python's tuple unpacking allows elegant variable swapping without a temporary variable. This is a common Python idiom that demonstrates the power of Python's syntax.

4. Data Types 5 Questions

šŸŽÆ Learning Goal: Master Python's built-in data types — int, float, str, bool, list, tuple, dict, set.
Beginner Q9: Check the Type of Variables
Scenario: You're debugging a program. Write a program that checks and prints the data type of different variables using type().
šŸ’” Solution:
x = 10
y = 3.14
z = "Hello"
w = True
print(f"x is {type(x)}")
print(f"y is {type(y)}")
print(f"z is {type(z)}")
print(f"w is {type(w)}")
# Output: x is <class 'int'>, etc.
šŸ“– Explanation:

The type() function returns the data type of a variable. This is useful for debugging and understanding how Python handles different data types.

Intermediate Q10: Convert Between Data Types
Scenario: You're building a data processing application. Write a program that converts a string to an integer, a float to a string, and an integer to a float.
šŸ’” Solution:
str_num = "100"
int_num = int(str_num)
float_num = 3.14
str_float = str(float_num)
int_to_float = float(int_num)
print(f"String to int: {int_num} ({type(int_num)})")
print(f"Float to string: '{str_float}' ({type(str_float)})")
print(f"Int to float: {int_to_float} ({type(int_to_float)})")
šŸ“– Explanation:

Type conversion (casting) is essential in Python programming. This exercise demonstrates how to convert between different data types using int(), float(), and str(). Used in data validation and user input processing.

5. Operators & Expressions 5 Questions

šŸŽÆ Learning Goal: Master Python operators — arithmetic, assignment, relational, logical, and special operators.
Beginner Q11: Calculate with Arithmetic Operators
Scenario: You're building a calculator. Write a program that calculates the sum, difference, product, quotient, and remainder of two numbers.
šŸ’” Solution:
a, b = 15, 4
print(f"Sum: {a + b}")
print(f"Difference: {a - b}")
print(f"Product: {a * b}")
print(f"Quotient: {a / b}")
print(f"Remainder: {a % b}")
print(f"Floor Division: {a // b}")
print(f"Power: {a ** b}")
# Output: Sum: 19, Difference: 11, Product: 60, Quotient: 3.75, Remainder: 3, Floor Division: 3, Power: 50625
šŸ“– Explanation:

This problem demonstrates all arithmetic operators in Python. Used in everyday calculations in applications like calculators, billing systems, and scientific computing.

6. Constants 3 Questions

šŸŽÆ Learning Goal: Understand and implement constants — values that shouldn't change during program execution.
Beginner Q12: Define and Use Constants
Scenario: You're building a physics calculator. Define constants like PI, GRAVITY, and SPEED_OF_LIGHT using uppercase names (convention).
šŸ’” Solution:
PI = 3.14159
GRAVITY = 9.8
SPEED_OF_LIGHT = 299792458
radius = 5
area = PI * radius ** 2
print(f"Area of circle: {area:.2f}")
# Output: 78.54
šŸ“– Explanation:

Constants are values that don't change. By convention, constants are written in uppercase. This improves code readability and maintainability. Used in scientific and mathematical applications.

7. Assignment Statements 3 Questions

šŸŽÆ Learning Goal: Master assignment statements — simple, multiple, chain, and augmented assignment.
Beginner Q13: Basic and Multiple Assignment
Scenario: You're initializing multiple variables. Write a program that assigns values to variables using both single and multiple assignment statements.
šŸ’” Solution:
# Single assignment
name = "Python"
# Multiple assignment
x, y, z = 10, 20, 30
print(f"Name: {name}, x: {x}, y: {y}, z: {z}")
šŸ“– Explanation:

Python supports both single and multiple assignment. Multiple assignment allows you to assign values to multiple variables in one line, improving code readability.

8. Input / Output 4 Questions

šŸŽÆ Learning Goal: Master user input and output formatting in Python using input() and print().
Beginner Q14: Get User Input and Display Output
Scenario: You're building a simple greeting program. Write a program that asks the user for their name and greets them with a personalized message.
šŸ’” Solution:
name = input("What's your name? ")
print(f"Hello, {name}! Welcome to Python!")
# Output: What's your name? (user types: Alice)
# Hello, Alice! Welcome to Python!
šŸ“– Explanation:

The input() function reads user input as a string, and print() displays output. This is the foundation of interactive programs.

9. Simple Python Scripts 4 Questions

šŸŽÆ Learning Goal: Write complete Python scripts that solve real-world problems.
Intermediate Q15: Calculate Area and Perimeter
Scenario: You're building a geometry calculator. Write a Python script that calculates the area and perimeter of a rectangle given its length and width.
šŸ’” Solution:
# Rectangle Calculator Script
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
perimeter = 2 * (length + width)
print(f"Area: {area:.2f}")
print(f"Perimeter: {perimeter:.2f}")
šŸ“– Explanation:

This complete script demonstrates input handling, calculation, and formatted output. Used in geometry, architecture, and design applications.

10. Namespace 3 Questions

šŸŽÆ Learning Goal: Understand Python namespaces — local, global, and built-in namespaces.
Intermediate Q16: Demonstrate Local and Global Variables
Scenario: You're debugging variable scope issues. Write a program that demonstrates the difference between local and global variables.
šŸ’” Solution:
x = 10 # Global variable
def my_function():
x = 20 # Local variable
print(f"Local x: {x}")
my_function()
print(f"Global x: {x}")
# Output: Local x: 20
# Global x: 10
šŸ“– Explanation:

Global variables are accessible throughout the program, while local variables are only accessible within the function where they are defined. This is fundamental to understanding Python's scoping rules.

Try It Yourself!

Use the interactive editor below to test your solutions or write your own code.

Loading Pyodide... 0%
Python Code Editor
========================================
PYTHON INTRODUCTION PRACTICE
========================================
Name: Alice, Type: <class 'str'>
Age: 25, Type: <class 'int'>
Height: 5.6, Type: <class 'float'>
Is Student: True, Type: <class 'bool'>
What's your name? (user types: John)
Hello, John! Welcome to Python!

āœ… Write your solutions here!

šŸ“š Related Tutorials

šŸ What is Python

Learn about Python programming language

šŸ“Š Data Types

Review Python data types

šŸ“„ Input/Output

Learn about input and output in Python

šŸ“– Related Tutorials
  • What is Python
  • Tokens in Python
  • Variables and Identifiers
  • Data Types in Python
šŸ“– Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Namespace in Python Next: Arithmetic Operators →