Welcome to our comprehensive guide on mobile app development with Python! In this post, we will cover everything from the basics of Python programming to advanced mobile app development frameworks. Whether you’re a beginner or an experienced developer, this guide will provide valuable insights and practical examples to help you create your own mobile applications.
Table of Contents
- Introduction to Python
- Setting Up Python
- Basic Syntax and Data Types
- Control Structures
- Functions
- Advanced Data Structures
- Error Handling
- Modules and Packages
- Decorators
- Generators
- Useful Libraries and Frameworks
- Concurrency and Parallelism
- Advanced Python Concepts
- Testing
- Web Development with Flask and Django
- Advanced Data Analysis with Pandas
- Data Visualization with Matplotlib and Seaborn
- Developing Mobile Applications with Python
- Practical Project: To-Do List App
- Additional Resources
- Conclusion
1. Introduction to Python
Python is a high-level, interpreted programming language known for its readability and simplicity. It’s widely used for web development, data analysis, scientific computing, artificial intelligence, and mobile app development.
2. Setting Up Python
First, you need to have Python installed on your computer. You can download it from the official Python website. Once installed, you can use an Integrated Development Environment (IDE) like PyCharm, VSCode, or Jupyter Notebook for writing and running Python code.
3. Basic Syntax and Data Types
Learn the basics of Python syntax and fundamental data types, including integers, floats, strings, and booleans.
Hello World
print("Hello, World!")
Variables and Data Types
# Integer
a = 10
# Float
b = 3.14
# String
c = "Hello, Python"
# Boolean
d = True
Comments
# This is a single-line comment
"""
This is a
multi-line comment
"""
Practice
Exercise: Print Your Details
Write a Python script that prints your name, age, and city.
Answer:
name = "John Doe"
age = 30
city = "New York"
print(f"My name is {name}, I am {age} years old, and I live in {city}.")
Exercise: Experiment with Data Types
Experiment with different data types and print their values.
Answer:
integer_value = 42
float_value = 3.14159
string_value = "Hello, World!"
boolean_value = True
print(integer_value)
print(float_value)
print(string_value)
print(boolean_value)
4. Control Structures
Control structures are used to control the flow of execution in a program.
Conditional Statements
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
Loops
# For loop
for i in range(5):
print(i)
# While loop
i = 0
while i < 5:
print(i)
i += 1
Practice
Exercise: Check Number
Write a Python program that checks if a number is positive, negative, or zero.
Answer:
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Exercise: Print Numbers
Create a loop that prints numbers from 1 to 20.
Answer:
for i in range(1, 21):
print(i)
5. Functions
Functions help you to organize your code into reusable blocks.
Defining Functions
def greet(name):
return f"Hello, {name}"
print(greet("Alice"))
Practice
Exercise: Factorial Function
Write a function that calculates the factorial of a number.
Answer:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Exercise: Palindrome Checker
Create a function that checks if a string is a palindrome.
Answer:
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("radar")) # Output: True
print(is_palindrome("hello")) # Output: False
6. Advanced Data Structures
Learn about list comprehensions, dictionary comprehensions, and more.
List Comprehensions
# Create a list of squares
squares = [x ** 2 for x in range(10)]
print(squares)
Dictionary Comprehensions
# Create a dictionary with numbers and their squares
squares_dict = {x: x ** 2 for x in range(10)}
print(squares_dict)
Practice
Exercise: Even Numbers
Use list comprehensions to create a list of even numbers from 1 to 20.
Answer:
even_numbers = [x for x in range(1, 21) if x % 2 == 0]
print(even_numbers)
Exercise: Cubes Dictionary
Create a dictionary that maps numbers to their cubes.
Answer:
cubes_dict = {x: x ** 3 for x in range(1, 11)}
print(cubes_dict)
7. Error Handling
Error handling in Python is done using try
and except
blocks.
Try-Except Blocks
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Custom Exceptions
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e)
Practice
Exercise: File Reading Error
Write a program that handles file reading errors.
Answer:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
Exercise: Custom Exception
Create a custom exception for invalid inputs in a function.
Answer:
class InvalidInputError(Exception):
pass
def check_positive(number):
if number < 0:
raise InvalidInputError("Negative numbers are not allowed.")
return number
try:
print(check_positive(-5))
except InvalidInputError as e:
print(e)
8. Modules and Packages
Learn how to create and use modules and packages in Python.
Creating Modules
# my_module.py
def greet(name):
return f"Hello, {name}"
# main.py
import my_module
print(my_module.greet("Alice"))
Creating Packages
# my_package/__init__.py
# my_package/module1.py
# my_package/module2.py
Practice
Exercise: Shape Area Module
Create a module with a function that calculates the area of different shapes.
Answer:
# shapes.py
def area_of_circle(radius):
return 3.14159 * radius ** 2
def area_of_rectangle(length, width):
return length * width
# main.py
import shapes
print(shapes.area_of_circle(5)) # Output: 78.53975
print(shapes.area_of_rectangle(4, 6)) # Output: 24
Exercise: Organize Code into Packages
Organize your code into packages and import them in a main script.
Answer:
# my_package/__init__.py
# my_package/module1.py
def greet(name):
return f"Hello, {name}"
# my_package/module2.py
def farewell(name):
return f"Goodbye, {name}"
# main.py
from my_package import module1, module
2
print(module1.greet("Alice"))
print(module2.farewell("Bob"))
9. Decorators
Decorators are a powerful tool to modify the behavior of functions or classes.
Function Decorators
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Class Decorators
def add_methods(cls):
cls.new_method = lambda self: print("New method added")
return cls
@add_methods
class MyClass:
pass
obj = MyClass()
obj.new_method()
Practice
Exercise: Execution Time Logger
Create a decorator that logs the execution time of a function.
Answer:
import time
def time_logger(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time: {end_time - start_time} seconds")
return result
return wrapper
@time_logger
def slow_function():
time.sleep(2)
print("Function finished")
slow_function()
Exercise: Class Method Adder
Implement a class decorator that adds a new method to a class.
Answer:
def add_greeting(cls):
cls.greet = lambda self: print("Hello, world!")
return cls
@add_greeting
class MyClass:
pass
obj = MyClass()
obj.greet()
10. Generators
Generators allow you to iterate over data without storing the entire dataset in memory.
def my_generator():
for i in range(10):
yield i
for value in my_generator():
print(value)
Practice
Exercise: Even Number Generator
Write a generator function that yields even numbers up to a given limit.
Answer:
def even_numbers(limit):
for i in range(limit + 1):
if i % 2 == 0:
yield i
for num in even_numbers(10):
print(num)
Exercise: Line by Line File Reader
Use a generator to read large files line by line.
Answer:
def read_lines(file_path):
with open(file_path, "r") as file:
for line in file:
yield line.strip()
for line in read_lines("large_file.txt"):
print(line)
11. Useful Libraries and Frameworks
Explore libraries like NumPy, Pandas, Matplotlib, Flask, and Django.
NumPy
import numpy as np
array = np.array([1, 2, 3, 4, 5])
print(array.mean())
Pandas
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Sample Plot')
plt.show()
Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Django
# This is an example of a simple Django view
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
Practice
Exercise: NumPy Operations
Create a NumPy array and perform basic arithmetic operations.
Answer:
import numpy as np
array = np.array([1, 2, 3, 4, 5])
print(array + 10)
print(array * 2)
print(array.mean())
Exercise: Load CSV with Pandas
Load a CSV file using Pandas and perform data analysis.
Answer:
import pandas as pd
df = pd.read_csv("data.csv")
print(df.head())
print(df.describe())
Exercise: Plot Graph with Matplotlib
Plot a simple graph using Matplotlib.
Answer:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sample Plot')
plt.show()
Exercise: Flask Web App
Build a basic web application using Flask.
Answer:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to my Flask app!"
@app.route('/about')
def about():
return "This is the about page."
if __name__ == '__main__':
app.run(debug=True)
Exercise: Django Project
Create a simple Django project and add new views.
Answer:
# Install Django
pip install django
# Create a new Django project
django-admin startproject myproject
# Create a new app
cd myproject
python manage.py startapp myapp
# Add 'myapp' to INSTALLED_APPS in settings.py
# Create a view in myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
def about(request):
return HttpResponse("About this site")
# Add the view to myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('about/', views.about),
]
# Include myapp.urls in myproject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
# Run the server
python manage.py runserver
12. Concurrency and Parallelism
Learn about threading and multiprocessing for concurrent and parallel execution.
Threading
import threading
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
Multiprocessing
import multiprocessing
def print_numbers():
for i in range(10):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
Practice
Exercise: Multithreading
Create a multithreaded program that prints numbers in parallel.
Answer:
import threading
def print_numbers():
for i in range(5):
print(f"Thread {threading.current_thread().name}: {i}")
threads = []
for i in range(3):
thread = threading.Thread(target=print_numbers, name=f"Thread-{i}")
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
Exercise: Multiprocessing Tasks
Implement a multiprocessing program to perform computational tasks.
Answer:
import multiprocessing
def compute_square(n):
print(f"The square of {n} is {n * n}")
numbers = [1, 2, 3, 4, 5]
processes = []
for number in numbers:
process = multiprocessing.Process(target=compute_square, args=(number,))
processes.append(process)
process.start()
for process in processes:
process.join()
13. Advanced Python Concepts
Explore context managers, type hinting, and more.
Context Managers
with open("example.txt", "w") as file:
file.write("Hello, World!")
Type Hinting
def greeting(name: str) -> str:
return f"Hello, {name}"
print(greeting("Alice"))
Practice
Exercise: Custom Context Manager
Create a custom context manager using __enter__
and __exit__
methods.
Answer:
class CustomContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with CustomContextManager():
print("Inside context")
Exercise: Add Type Hints
Add type hints to your functions and classes.
Answer:
def add(a: int, b: int) -> int:
return a + b
class Person:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def greet(self) -> str:
return f"Hello, my name is {self.name} and I am {self.age} years old."
person = Person("Alice", 30)
print(person.greet())
14. Testing
Learn how to write unit tests using unittest
and pytest
.
Unit Testing with unittest
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == '__main__':
unittest.main()
Unit Testing with pytest
# Save this in a file named test_example.py
def add(a, b):
return a + b
def test_add():
assert add(1, 2) == 3
assert add(-1, 1) == 0
assert add(0, 0) == 0
# Run the tests with: pytest test_example.py
Practice
Exercise: Unit Tests with unittest
Write unit tests for your functions using unittest
.
Answer:
import unittest
def multiply(a, b):
return a * b
class TestMath(unittest.TestCase):
def test_multiply(self):
self.assertEqual(multiply(2, 3), 6)
self.assertEqual(multiply(-1, 1), -1)
self.assertEqual(multiply(0, 5), 0)
if __name__ == '__main__':
unittest.main()
Exercise: Parameterized Tests with pytest
Use pytest
to create parameterized tests.
Answer:
import pytest
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(2, 3, 5),
(3, 4, 7),
])
def test_add(a, b, expected):
assert add(a, b) == expected
# Run the tests with: pytest test_example.py
15. Web Development with Flask and Django
Build web applications using Flask and Django.
Flask – REST API
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def get_data():
return jsonify({"message": "Hello, World!"})
@app.route('/api', methods=['POST'])
def post_data():
data = request.json
return jsonify(data), 201
if __name__ == '__main__':
app.run(debug=True)
Django – Basic Setup
# Install Django
pip install django
# Create a new Django project
django-admin startproject myproject
# Create a new app
cd myproject
python manage.py startapp myapp
# Add 'myapp' to INSTALLED_APPS in settings.py
# Create a view in myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
def about(request):
return HttpResponse("About this site")
# Add the view to myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('about/', views.about),
]
# Include myapp.urls in myproject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
# Run the server
python manage.py runserver
Practice
Exercise: Flask REST API
Create a simple REST API using Flask.
Answer:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/greet', methods=['GET'])
def greet():
name = request.args.get('name', 'World')
return jsonify({"message": f"Hello, {name}!"})
if __name__ == '__main__':
app.run(debug=True)
Exercise: Django Views
Build a basic website with Django and add new views.
Answer:
# Install Django
pip install django
# Create a new Django project
django-admin startproject myproject
# Create a new app
cd myproject
python manage.py startapp myapp
# Add 'myapp' to INSTALLED_APPS in settings.py
# Create a view in myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
def contact(request):
return HttpResponse("Contact us at contact@example.com")
# Add the view to myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('contact/', views.contact),
]
# Include myapp.urls in myproject/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
# Run the server
python manage.py runserver
16. Advanced Data Analysis with Pandas
Perform advanced data analysis with Pandas.
Grouping and Aggregation
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob'],
'Score': [85, 92, 78, 95, 85]}
df = pd.DataFrame(data)
# Group by name and calculate mean score
grouped = df.groupby('Name').mean()
print(grouped)
Merging DataFrames
data1 = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df1 = pd.DataFrame(data1)
data2 = {'Name': ['Alice', 'Bob', 'David'],
'Salary': [70000, 80000, 90000]}
df2 = pd.DataFrame(data2)
merged = pd.merge(df1, df2, on='Name', how='outer')
print(merged)
Practice
Exercise: Group and Aggregate
Load a dataset and perform grouping and aggregation.
Answer:
import pandas as pd
data = {'Department': ['Sales', 'HR', 'IT', 'Sales', 'IT'],
'Employee': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Salary': [50000, 60000, 70000, 55000, 65000]}
df = pd.DataFrame(data)
# Group by department and calculate mean salary
grouped = df.groupby('Department')['Salary'].mean()
print(grouped)
Exercise: Merge DataFrames
Merge two DataFrames and perform data analysis.
Answer:
data1 = {'Employee': ['Alice', 'Bob', 'Charlie'],
'Department': ['Sales', 'HR', 'IT']}
df1 = pd.DataFrame(data1)
data2 = {'Employee': ['Alice', 'Charlie', 'Eve'],
'Project': ['Project A', 'Project B', 'Project C']}
df2 = pd.DataFrame(data2)
merged = pd.merge(df1, df2, on='Employee', how='outer')
print(merged)
17. Data Visualization with Matplotlib and Seaborn
Visualize data using Matplotlib and Seaborn.
Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sample Plot')
plt.show()
Seaborn
import seaborn as sns
import pandas as pd
data = {'X': [1, 2, 3, 4, 5], 'Y': [10, 20, 25, 30, 35]}
df = pd.DataFrame(data)
sns.lineplot(x='X', y='Y', data=df)
plt.title('Sample Seaborn Plot')
plt.show()
Practice
Exercise: Matplotlib Line Plot
Create a line plot using Matplotlib.
Answer:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot Example')
plt.grid(True)
plt.show()
Exercise: Seaborn Visualization
Use Seaborn to visualize a dataset.
Answer:
import seaborn as sns
import pandas as pd
data = {'Category': ['A', 'B', 'C', 'A', 'B', 'C'],
'Values': [10, 20, 15, 25, 30, 35]}
df = pd.DataFrame(data)
sns.barplot(x='Category', y='Values', data=df)
plt.title('Seaborn Bar Plot Example')
plt.show()
18. Developing Mobile Applications with Python
Explore various frameworks for developing mobile applications using Python, such as Kivy, BeeWare, and Python-for-Android.
Kivy
Kivy is an open-source Python library for developing multitouch applications. It runs on Linux, Windows, OS X, Android, and iOS.
Basic Kivy Application
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
return Label(text="Hello, Kivy!")
if __name__ ==
'__main__':
MyApp().run()
BeeWare
BeeWare allows you to write native applications in Python for iOS, Android, and other platforms.
Basic BeeWare Application
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
class MyApp(toga.App):
def startup(self):
main_box = toga.Box(style=Pack(direction=COLUMN))
name_label = toga.Label('Your name: ', style=Pack(padding=(0, 5)))
self.name_input = toga.TextInput(style=Pack(flex=1))
greet_button = toga.Button(
'Greet',
on_press=self.say_hello,
style=Pack(padding=5)
)
main_box.add(name_label)
main_box.add(self.name_input)
main_box.add(greet_button)
self.main_window = toga.MainWindow(title=self.formal_name)
self.main_window.content = main_box
self.main_window.show()
def say_hello(self, widget):
print(f"Hello, {self.name_input.value}!")
def main():
return MyApp()
if __name__ == '__main__':
main().main_loop()
Python-for-Android (p4a)
Python-for-Android is a tool to create standalone Android APKs.
Creating an APK
p4a create --dist_name=myapp --bootstrap=sdl2 --requirements=kivy --package=org.example.myapp --name "MyApp" --version=0.1
cd myapp
p4a apk --dist_name=myapp --release --signkey=~/path/to/your.keystore
KivyMD
KivyMD is a collection of Material Design widgets for use with Kivy.
Basic KivyMD Application
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
class MyApp(MDApp):
def build(self):
return MDLabel(text="Hello, KivyMD!", halign="center")
if __name__ == '__main__':
MyApp().run()
Practice
Exercise: Kivy Mobile App
Create a basic mobile application using Kivy.
Answer:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
class MyApp(App):
def build(self):
layout = BoxLayout(orientation='vertical')
self.label = Label(text="Press the button")
button = Button(text="Press me", on_press=self.on_button_press)
layout.add_widget(self.label)
layout.add_widget(button)
return layout
def on_button_press(self, instance):
self.label.text = "Button pressed!"
if __name__ == '__main__':
MyApp().run()
Exercise: BeeWare App
Develop a simple app with BeeWare and deploy it on your mobile device.
Answer:
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
class MyApp(toga.App):
def startup(self):
main_box = toga.Box(style=Pack(direction=COLUMN))
self.label = toga.Label('Press the button', style=Pack(padding=(0, 5)))
button = toga.Button('Press me', on_press=self.on_button_press, style=Pack(padding=5))
main_box.add(self.label)
main_box.add(button)
self.main_window = toga.MainWindow(title=self.formal_name)
self.main_window.content = main_box
self.main_window.show()
def on_button_press(self, widget):
self.label.text = "Button pressed!"
def main():
return MyApp()
if __name__ == '__main__':
main().main_loop()
Exercise: Python-for-Android APK
Use Python-for-Android to package a Kivy application into an APK.
Answer:
# Ensure you have the necessary dependencies installed
pip install python-for-android
# Create the Kivy app directory and main.py file
mkdir mykivyapp
cd mykivyapp
echo "from kivy.app import App\nfrom kivy.uix.label import Label\n\nclass MyApp(App):\n def build(self):\n return Label(text='Hello, Kivy!')\n\nif __name__ == '__main__':\n MyApp().run()" > main.py
# Build the APK
p4a create --dist_name=mykivyapp --bootstrap=sdl2 --requirements=kivy --package=org.example.mykivyapp --name "MyKivyApp" --version=0.1
cd mykivyapp
p4a apk --dist_name=mykivyapp --release --signkey=~/path/to/your.keystore
19. Practical Project: To-Do List App
Let’s put everything together and create a complete project: a To-Do List App using Kivy and SQLite.
Installing Dependencies
pip install kivy sqlite3
Main Application Code
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
import sqlite3
class ToDoApp(App):
def build(self):
self.conn = sqlite3.connect('todos.db')
self.create_table()
self.layout = BoxLayout(orientation='vertical')
self.task_input = TextInput(hint_text='Enter a task')
self.layout.add_widget(self.task_input)
self.add_button = Button(text='Add Task', on_press=self.add_task)
self.layout.add_widget(self.add_button)
self.tasks_layout = BoxLayout(orientation='vertical')
self.layout.add_widget(self.tasks_layout)
self.display_tasks()
return self.layout
def create_table(self):
with self.conn:
self.conn.execute('CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task TEXT)')
def add_task(self, instance):
task = self.task_input.text
if task:
with self.conn:
self.conn.execute('INSERT INTO tasks (task) VALUES (?)', (task,))
self.task_input.text = ''
self.display_tasks()
def display_tasks(self):
self.tasks_layout.clear_widgets()
cursor = self.conn.execute('SELECT * FROM tasks')
for row in cursor:
task_label = Label(text=row[1])
self.tasks_layout.add_widget(task_label)
def on_stop(self):
self.conn.close()
if __name__ == '__main__':
ToDoApp().run()
Practice
Exercise: Extend To-Do List App
Extend the To-Do List App to include functionality for deleting and updating tasks.
Answer:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
import sqlite3
class ToDoApp(App):
def build(self):
self.conn = sqlite3.connect('todos.db')
self.create_table()
self.layout = BoxLayout(orientation='vertical')
self.task_input = TextInput(hint_text='Enter a task')
self.layout.add_widget(self.task_input)
self.add_button = Button(text='Add Task', on_press=self.add_task)
self.layout.add_widget(self.add_button)
self.tasks_layout = GridLayout(cols=3)
self.layout.add_widget(self.tasks_layout)
self.display_tasks()
return self.layout
def create_table(self):
with self.conn:
self.conn.execute('CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task TEXT)')
def add_task(self, instance):
task = self.task_input.text
if task:
with self.conn:
self.conn.execute('INSERT INTO tasks (task) VALUES (?)', (task,))
self.task_input.text = ''
self.display_tasks()
def delete_task(self, task_id):
with self.conn:
self.conn.execute('DELETE FROM tasks WHERE id = ?', (task_id,))
self.display_tasks()
def update_task(self, task_id, new_task):
with self.conn:
self.conn.execute('UPDATE tasks SET task = ? WHERE id = ?', (new_task, task_id))
self.display_tasks()
def display_tasks(self):
self.tasks_layout.clear_widgets()
cursor = self.conn.execute('SELECT * FROM tasks')
for row in cursor:
task_id, task_text = row
task_label = Label(text=task_text)
delete_button = Button(text='Delete', on_press=lambda instance, task_id=task_id: self.delete_task(task_id))
update_button = Button(text='Update', on_press=lambda instance, task_id=task_id: self.update_task(task_id, self.task_input.text))
self.tasks_layout.add_widget(task_label)
self.tasks_layout.add_widget(delete_button)
self.tasks_layout.add_widget(update_button)
def on_stop(self):
self.conn.close()
if __name__ == '__main__':
ToDoApp().run()
Exercise: Mark Tasks as Completed
Add a feature to mark tasks as completed.
Answer:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import
Button
from kivy.uix.gridlayout import GridLayout
from kivy.properties import BooleanProperty
import sqlite3
class ToDoApp(App):
def build(self):
self.conn = sqlite3.connect('todos.db')
self.create_table()
self.layout = BoxLayout(orientation='vertical')
self.task_input = TextInput(hint_text='Enter a task')
self.layout.add_widget(self.task_input)
self.add_button = Button(text='Add Task', on_press=self.add_task)
self.layout.add_widget(self.add_button)
self.tasks_layout = GridLayout(cols=4)
self.layout.add_widget(self.tasks_layout)
self.display_tasks()
return self.layout
def create_table(self):
with self.conn:
self.conn.execute('CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task TEXT, completed BOOLEAN)')
def add_task(self, instance):
task = self.task_input.text
if task:
with self.conn:
self.conn.execute('INSERT INTO tasks (task, completed) VALUES (?, ?)', (task, False))
self.task_input.text = ''
self.display_tasks()
def delete_task(self, task_id):
with self.conn:
self.conn.execute('DELETE FROM tasks WHERE id = ?', (task_id,))
self.display_tasks()
def update_task(self, task_id, new_task):
with self.conn:
self.conn.execute('UPDATE tasks SET task = ? WHERE id = ?', (new_task, task_id))
self.display_tasks()
def toggle_task_completion(self, task_id, current_state):
with self.conn:
self.conn.execute('UPDATE tasks SET completed = ? WHERE id = ?', (not current_state, task_id))
self.display_tasks()
def display_tasks(self):
self.tasks_layout.clear_widgets()
cursor = self.conn.execute('SELECT * FROM tasks')
for row in cursor:
task_id, task_text, completed = row
task_label = Label(text=task_text, color=(0, 1, 0, 1) if completed else (1, 0, 0, 1))
delete_button = Button(text='Delete', on_press=lambda instance, task_id=task_id: self.delete_task(task_id))
update_button = Button(text='Update', on_press=lambda instance, task_id=task_id: self.update_task(task_id, self.task_input.text))
toggle_button = Button(text='Complete' if not completed else 'Uncomplete', on_press=lambda instance, task_id=task_id, current_state=completed: self.toggle_task_completion(task_id, current_state))
self.tasks_layout.add_widget(task_label)
self.tasks_layout.add_widget(delete_button)
self.tasks_layout.add_widget(update_button)
self.tasks_layout.add_widget(toggle_button)
def on_stop(self):
self.conn.close()
if __name__ == '__main__':
ToDoApp().run()
20. Additional Resources
Here are some additional free resources to help you learn and practice Python and mobile app development:
Online Courses
- Coursera: Python for Everybody – Free to audit.
- edX: Introduction to Computer Science using Python – Free to audit.
- Khan Academy: Intro to Python – Free to access.
Books and Tutorials
- Automate the Boring Stuff with Python by Al Sweigart – Free to read online.
- W3Schools Python Tutorial – Free online tutorial.
- Real Python – Free tutorials and articles.
Tools
- PyCharm Community Edition – Free IDE for Python.
- Visual Studio Code – Free code editor with Python support.
- Jupyter Notebook – Free tool for interactive data science and scientific computing.
Practice Platforms
- LeetCode – Free coding challenges and practice problems.
- HackerRank – Free coding challenges and practice problems.
- Codewars – Free coding challenges and practice problems.
21. Conclusion
We hope this guide has provided you with valuable insights into mobile app development using Python. At New Waves App Development, we specialize in creating high-quality mobile applications tailored to your needs. Contact us via WhatsApp https://wa.me/97460077635, call +97455574988, or email info@new-waves.net to discuss your app development needs.
By following these steps and using the provided code snippets, you can start developing mobile applications with Python. Happy coding!