Quillix.blogspot.com delivers concise, step-by-step guides on email migration, file conversion, and cloud productivity tools. Stay ahead with quick tips and trusted software recommendations for smoother digital workflows.
If you want to enhance your skills as a Python programmer or learn a new course like Data Science or Data Analytics, start by practicing these 30 problems. Before looking for answers online, take the time to fully understand and learn how to solve each problem on your own.
30 Python Problems — Helpful for Data Science Beginners
Level 1 — Basic Logic
1. Even or Odd
Take a number from the user and print whether it is even or odd.
We have learned how to create classes and objects. Now, we will explore class variables and instance variables in Python, including how they are used and when to use each one. This chapter also explains how data is stored in variables. If you are still confused about these concepts, this chapter will help clarify them.
What is Variable?
A variable is like a container that stores data or a value. It can store different types of data, such as strings, integers, floats, booleans, and more.
We have already explained the OOP concepts of classes and objects. In this tutorial, we will take a deeper dive into the four core pillars of Object-Oriented Programming: Encapsulation, Inheritance, Polymorphism, and Abstraction. These concepts are essential for writing scalable, maintainable, and reusable code in real-world applications.
What is Encapsulation?
Encapsulation is the practice of bundling data (variables) and the methods (functions) that operate on that data into a single unit, known as a class. It restricts direct access to some of an object's components, which prevents accidental modification. To read or update this private data safely, public methods called getters and setters are used.
We have covered Lambda functions in the Python tutorial; now, let's understand Decorators. Grasping this concept all at once might be a bit challenging, but it will become easier with practice.
What are Decorators in Python programming?
Decorators are essentially functions, they take another function as input and return a modified version of that function.
In other worlds, Decorators are one of the most powerful features of the Python language. They allow coders to modify or extend the behavior of a function without altering its source code.
A Lambda function is a small, anonymous, and single-line function used to define small and simple operations where writing a full function using 'def' is unnecessary.
Syntax: lambda arguments: experssion
It can take multiple arguments but only one experssion.
Example
add = lambda a, b: a+b
print(add(3, 5))
Normal Function
def add(a, b): return a + b
Using with one argument
square = lambda a: a*a print(square(5))
Using with multiple argument
multiply = lambda a, b, c: a * b * c print(multiply(2, 4, 6))
Note: x[0] sorts by the first element, while x[1] sorts by the second element. Use reverse=True for descending order. ("vicky", 1): vicky: first element and 1: second element.
Practice
Task 1: Sort Even number using Lambda
Task 2: Print Cubes of each number
Task 3: Sorted Number from 1 to 10 from scramble list.
Conclusion
We have complete the Lambda function. It is all about on practic try above code and practice each one and understand the logic behind this.
We have completed the Beginner series in Python language, and we are now dive in Intermediate-level chapters. If you haven't read the beignner chapters yet, read them first so that you understand this chapter even better.
What is a List Comprehension?
List comprehension is a concise way to write code that generates lists in a single line, instead of using multiple lines with loops. It is powerful, readable, and easy to understand for simple operations. In short "We create a new list by iterating over an old list".
However, when you have multiple nested loops or complex conditions, list comprehensions can become hard to read and understand.
Syntax: new_list = [expression for item in iterable]
Note: List use [ ] bracket.
Example - Without Comprehension
num = [1, 2, 3, 4, 5]
square = []
for x in num:
square.append(x**2)
print(square)
Example - With List Comprehension
square = [x**2 for x in range(1, 6)]
print(square)
List Comprehension with Condition
We can also filter items using "if" statement.
Syntax: new_list = [expression for item in iterable if condition]
Example: Find ODD numbers
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
oddnumber = [x for x in number if x%2 != 0]
print (oddnumber)
Using if-else
if-else condition is also used in list comprehension but it changes the output value.
Syntax: new_list = [true_expr if condition else false_expr for item in interable]
When programs grow bigger, writing everything in a single file can become messy and hard to manage. Multiple functions, classes, and static variables can make code confusing, difficult to read, and hard to reuse.
Python provides modules and packages to help organize code in a clean, reusable way.
You can also give a aliases (nick name) name to the moudle like: import mymath as mt and access using the nick name: print(mt.add(5, 6))
We can also import specific function
from mymath import add
print(add(2, 3))
Package: A package is a folder containing multiple modules, along with a special __init__.py file. Packages help organize modules into a directory structure. This allows large projects to remain clean and modular.
Example:
Myfolder __init__.py mymath.py mycode.py
Note:__init__.py can be empty or contain initialization code. It tells Python that this folder should be treated as a package
Using a module from Package
from Myfolder import mymath
print(mymath.add(20, 30)) print() print(mymath.multiply(10, 10))
Python built-in Module
Python has many built-in modules like math, random, etc.
import math print(math.sqrt(25)) print() print(math.pi)
import random print(random.randint(1, 5)
Tasks:
Create a module with a function to find square of a number.
Import that module in another file and use it.
Create a package with two modules.
Use math module to calculate square root.
Mini Project: Generate Random Password
import random
import string
def gen_password(length):
new = (string.ascii_letters + string.digits)
password = "".join(random.choice(new) for i in range(length))
return(password)
# in place of "i" we can also use "_" because we don't need this value
# this is just a placeholder
print(gen_password(7))
In this chapter, I explained modules and packages. They help make your programs shorter, more organized, and reusable. If you want to learn Python effectively, understanding modules and packages is very important, because they allow you to structure your code in a clean and maintainable way.
OOP Concept is the backbone of Python because everything in Python is an object ranging from classes to methods. It helps coders maintain program durability, clarity, and ease of debugging. Additionally, OOP prevents the need for writing long, repetitive code by allowing the reuse of the same class or object attributes throughout the program.
In programming language: OOP is a programming style that helps you organize your code into classes and objects, similar to how real-world things are structured.
Example:
A Car has properties (or attributes or variables) like color, brand name, and speed.
It also has actions (or methods) like stop, start, and accelerate.
What is Class, Variable, Method & Objects?
Class: A class defines variables and methods that tell how the object will behave. A class is also known as a blueprint or template for an object. We can reuse its functionality without rewriting the same code.
Syntax:
class Student:
pass
Here:
Student is the class name
pass means empty class (no data yet)
Example with Data
class Student:
Name = "John"
Age = 28
This class has two properties: Name and Age.
Variable: This is also know as properties and it defines the stae of object under the class. To initialize (or access) variable, we use "self" keyword and set the value with _init_ method constructor. Let's break in part:
Properties (Attributes): These are the variables located within a class that represent the state of an object.
self: We use "self" to initialize (or access) the attributes of an object.
__init__ method: This is a special method known as a constructor. Its function is to set the attributes automatically when an object is created.
Example
class Student:
def __init__(self, name, age): #self refer the object. name and age are input.
self.name = name
self.age = age
s1 = Student("Ravi", 22)
print(s1.name)
Method: Methods are use to define or modify object behaviour (or action) in class.
Object: We have already stated that all things are objects; this does not imply that we intend to rename them or assign them a new name. An object is created within a class with the aid of variables and methods. These are utilized to execute the class or to obtain the desired output.
Example
s1 = Student() #s1 is an object and it use the Student class. print(s1.name)
Example with all above topics
#define a class
class Book:
#Use constructor (_init_) to initialize the attribute of the oject.
def __init__(self, title, author, year):
self.title = title #title is an attribute that stores book's title
self.author = author #author is an attribute that stores book's author
self.year = year #year is an attribute that stores book's year
#method to display the book's details
def display_info(self):
print(f"Book Title:{self.title}") #f is used to insert variables or values or input values into a string.
print(f"Author:{self.author}")
print(f"Year Publish:{self.year}")
#method to check if the book is an old book
def is_old_book(self):
if self.year > 1940:
return True
return False
#Create objects (instances) of the "Book" class
book1 = Book("Untouchable","Mulk Raj", 1935) #book1 is an object of the Book class
book2 = Book("Maulgudi Days","R.K Narayan", 1943)#book2 is an object of the Book class
#Call the "display_info" method to show the details of book1
book1.display_info()
#Call the "is_old_book" method to check if book1 is old
if book1.is_old_book():
print(f"{book1.title} is an old book.")
else:
print(f"{book1.title} is a latest book.")
print()
#Call the "display_info" method to show the details of book2
book2.display_info()
#Call the is_old_book" method to check if book2 is old
if book2.is_old_book():
print(f"{book2.title} is an old book.")
else:
print(f"{book2.title} is a latest book.")
Note: In Python, inside a class you should only define
__inti__ Constructor to initialize attributes.
Methods functions that belong to the class.
Anything else, like creating objects or calling methods, must be outside the class, at the main program level.
Task 1: Create City Class, initialize Population and Name then use ojbect to acccess City with population.
Conclusion
OOPs concepts are a very important chapter as they help you make programs more structured and easier to understand. The topics covered above include methods, variables, classes, and objects. In the next chapter, we will go further and explore the four principles of Python OOP: Encapsulation, Inheritance, Polymorphism, and Abstraction. Understanding these principles will take your coding skills a step further, enabling you to write more secure, maintainable, and robust programs.
We have learned how to create and use variables in Python. However, this is a temporary arrangement; they cease to exist once the program finishes executing. Python provides the capability to store data permanently, allowing it to be used even after the program has terminated. This is known as 'file handling'.
For example: Storing Records, Read file data, Store notes etc.
What is File Handling in Python?
"File Handling" is a concept used to read, write and modify file in Python language. With this, we can:
Create a File
Read a File
Write data to a File
Update a File
There are several methods and fuctions avaliable in file handling like: open(), write(), read() etc.
File Mode
Python file handling has multiple modes that serves the specific purpose.
Mode
Meaning
Behavior
"r"
Read
Open a file only for reading. File must exist.
"w"
Write
Open a file for writing. Creates a new file or overwrites an existing file.
"a"
Append
Open a file to add data at the end. Existing content is preserved.
"x"
Exclusive creation
Create a new file. Fails if the file already exists.
"rb"
Read Binary
Read a file in binary mode (images, videos).
"wb"
Write Binary
Write a file in binary mode.
"r+"
Read & Write
Open a file for reading and writing. File must exist.
"w+"
Write & Read
Open a file for reading and writing. Overwrites existing file.
"a+"
Append & Read
Open a file for reading and appending. Adds new content at the end.
With the help of the "a" mode, we can add new lines without deleting the existing data. If the file does not exist, it also creates it.
Example
file = open("note.text", "a") file.write("\nLearn from Scratch") file.close
Closing File
Always close files after using them.
file.close()
This saves resources.
Use "With" statment
This statement helps us to automatically close the file after execution
Example
with open("note.text", "r") as file: print(file.read())
Save User Input
We can also save the user input direct in our text file.
Example
name = input("Enter your name: ") with open("note.text", "w") file.write("name +\n")
Practice Excercise
Task 1: Create a file and write your name into it.
Task 2: Read data from a file.
Task 3: Append your city name to an existing file.
Task 4: Store 5 student names in a file.
Conclusion
This covers the basics of file handling at an introductory level. Practice these exercises and study this chapter in depth, as the concept of file handling enables applications to store data permanently. Next Chapter: OOPs in Python
Programming is not a one day or one week syllabus to learn and start coding. To become proficient in it, consistent practice, handling errors, manage codes and staying up-to-date the latest programming knowledge are essential.
When we start learning then we know that mistakes are common and indeed, every beginner learns through them.
In Python, "exception handling" refers to the process of addressing errors that arise while excuting the codes. This is a very important for any coder because if we don't pay attention on it, we will not able to expert in Programming.
From the previous chapters, we learned how to use string, loop, functions and methods to write a code in Python language. Now we can go one step ahead and learn how to take a input from the user.
Suppose, we are going to design an application and also want to intract with user or use in real world. Then it is must to learn how to accomplish this. This concept is very important to go further in this python tutorial, so ensure you understand every line and practice as much as possible.
What is input function?
The Input function is used to get input or data from the user via the keyboard. It stores the value provided by the user in a variable.
Syntax: input("Message")
Example:
name = input("Enter Your Name: ")
print(name) #Output: Anything you type is convert into output including number.
Note: If you type any number, it also appears in the output. From this, you can understand that the "input()" function always returns data as a string, even if the user enters a number.
Example: With Number
age = input("What is your age: ")
print(age)
print(type(age)) #Show data type
Now, as you can see in the image, the output of the data type is String (str).
Convert Input to Interger
If you want to use the input as an integer, you can convert it using the int() function.
age = int(input("What is your age: "))
print(age)
print(type(age)) #Show data type
Your value is convert to integer.
How to take two input from user?
print("Add Two Numbers") Num1 = int(input("Enter First Number: ")) Num2 = int(input(Enter Second Number: "))
print(Num1 + Num2) #print addition of give number
Taking String Input
When we want to generate output with user string input then we can create default value with print function.
name = input(Enter Your Name: ") city = input("Enter Your City: ") print("Hello", name) print("You live in", city)
Convert Input to Float
If we want number in decimal then we can use Float().
price = float(input("What is the price: ")) print(price)
Create Simple Calculator with Input()
print("This is simple calculator") num1 = int(input("Enter First Number: ")) num2 = int(input("Enter Second Number: ")) print() print("Addition", num1+num2) print("Substraction", num1-num2) print("Multiply", num1*num2) print("Divide", num1/num2)
How to take multiple input in one line?
You can also take a input in one line.
a,b = int(input(Type Two numbers: ")).split() print(a) print(b)
Tasks
Write a program to take user's name and age.
Write a program to add two numbers entered by user.
Write a program that asks for city and country.
Conclusion
This is all about the input() method. Now practice this method as much as possible to stay ahead in Python. The next chapter will be "Exception Handling".
Welcome Quillix Python Tutorial. In previous chapter, we have covered some Python string methods. Now we will learn about other string methods that help us to modify and write program.
String Methods or Functions
Replace()
Using this method, user can replace character or word with another.
"Python strings" – We have already seen how to write strings in the previous chapters. In this guide, we will dive deeper into strings to understand how they are used in real programming and explore the different use cases we can create with them.
A string is a text format used to store alphabets, symbols, spaces, and numbers. It is a sequence of characters written inside single quotes (' ') or double quotes (" ").
We have recently finished the chapter "Python Functions". Now our next chapter is "Data Structures". This is an important chapter because it helps us store and manage multiple values at once.
What is Data Structure?
We have seen variables that store a single value at a time. But what should we do when we want to store multiple values? Here, data structures provide an efficient way to store more than one value in Python. There are 4 types of main built-in data structures: List, Tuple, Sets, and Dictionaries. Each one has different features and use cases.
In the previous blogs/chapter, we learned that small code increases a program clarity to read and modify. As we continue learning Python, we will see large codes. Now assume, we may need to write the same code again and again, it becomes very tedious task for programmer/coder.
To handle this issue, we use function which makes program clearer, well-structured and more understandable. Also, it is used anytime and anywhere within the program.
What is Function in Python programming?
Function is a block of code that we can use it in our existed code when needed.
We've learned about Python variables, data types, operations, and conditional statements in previous articles. Now we'll learn "loops." This is a crucial chapter for understanding how to save time and effort using the same code multiple times.
What is Loops in Python?
In Python, the loop is used to control flow or can say that repeat the same block of code without writting it again. In simple words, programmer uses loop concept to execute the same code again and again as their requirement.
It makes our code easy to understand, shorter, and efficient. Programmers often use when performing repetitive tasks such as numbers, processing items in a list, long calculations etc..
There are two types of loops in Python: For and While.
In the previous chapter, we learned about Python syntax,variables, and data types. These basics help you install Python, run programs,
and write code correctly to get the results you want. If you haven’t finished
the previous tutorial, make sure to go back and complete it before moving on.
Why use Operators?
An operator is a symbol that allows us to perform operations on values. The values on which the operator works are called operands.
Example: 5 + 3
Here 5 and 3 are operand and "+" is operator. They are generally divided into three main categories
Python is widely used in web development, artificial intelligence, automation, and other field It is quite easy to learn, write and execute without any prior experience or programming knowledge. However, if you have even a little programming background, you can learn it very quickly.
Origin and Development of Python
Python programming was created by Guido van Rossum in the 1980s. Guido wanted to create a language that was easy to read and write, a successor to the ABC language. Therefore, work on it resumed in 1989, and it was officially released in 1991. Interestingly, its name doesn't come from a snake, but from the comedy group Monty Python's Flying Circus.