user_input = input("Enter something: ")
print("You entered:", user_input)
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
print(f"Addition: {addition}, Subtraction: {subtraction}, Multiplication: {multiplication}, Division: {division}")
3. Finding the data type of the value assigned to a variable.
variable = 42
data_type = type(variable)
print(f"The data type of the variable is: {data_type}")
4. Write a Python program to find if the number entered by the user is even or odd.
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The entered number is even.")
else:
print("The entered number is odd.")
5. Write a Python program to find if the number entered by the user is positive or not.
num = float(input("Enter a number: "))
if num > 0:
print("The entered number is positive.")
elif num == 0:
print("The entered number is zero.")
else:
print("The entered number is negative.")
6. Write a Python program to find the largest among three numbers.
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
largest = max(num1, num2, num3)
print(f"The largest number is: {largest}")
7. Write a Python program to find if the person is eligible for voting or not.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
8. Write a Python program to find if the number is divisible by 12 or not.
num = int(input("Enter a number: "))
if num % 12 == 0:
print("The entered number is divisible by 12.")
else:
print("The entered number is not divisible by 12.")
9. Write a Python program to calculate the electricity bill according to the number of units consumed.
units_consumed = float(input("Enter the number of units consumed: "))
if units_consumed <= 50:
bill = units_consumed * 0.50
elif units_consumed <= 150:
bill = 25 + (units_consumed - 50) * 0.75
elif units_consumed <= 250:
bill = 100 + (units_consumed - 150) * 1.20
else:
bill = 220 + (units_consumed - 250) * 1.50
print(f"The electricity bill is: {bill}")
10. Write a Python program to print the last two digits of a number.
num = int(input("Enter a number: "))
last_two_digits = num % 100
print(f"The last two digits of the number are: {last_two_digits}")
11. Write a Python program to display the grade based on the student's percentage.
percentage = float(input("Enter the student's percentage: "))
if percentage >= 90:
grade = 'A'
elif percentage >= 80:
grade = 'B'
elif percentage >= 70:
grade = 'C'
elif percentage >= 60:
grade = 'D'
else:
grade = 'F'
print(f"The student's grade is: {grade}")
12. Multiplication table of a given number.
number = int(input("Enter a number to generate its multiplication table: "))
for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")
13. Sum of all odd and even numbers in a given range.
start_range = int(input("Enter the start of the range: "))
end_range = int(input("Enter the end of the range: "))
sum_odd = 0
sum_even = 0
for num in range(start_range, end_range + 1):
if num % 2 == 0:
sum_even += num
else:
sum_odd += num
print(f"Sum of odd numbers: {sum_odd}, Sum of even numbers: {sum_even}")
14. To accept a word from the user and reverse it.
word = input("Enter a word: ")
reversed_word = word[::-1]
print(f"The reversed word is: {reversed_word}")
15. To find if a number is an Armstrong number or not.
num = int(input("Enter a number: "))
order = len(str(num))
temp = num
armstrong_sum = 0
while temp > 0:
digit = temp % 10
armstrong_sum += digit ** order
temp //= 10
if num == armstrong_sum:
print("The entered number is an Armstrong number.")
else:
print("The entered number is not an Armstrong number.")
16. To print all the numbers in a given range.
start_range = int(input("Enter the start of the range: "))
end_range = int(input("Enter the end of the range: "))
for num in range(start_range, end_range + 1):
print(num)
17. Python program to unpack tuple into variables.
my_tuple = (1, 2, 3)
var1, var2, var3 = my_tuple
print(f"Unpacked variables: {var1}, {var2}, {var3}")
18. Write a program to create a new tuple by merging tuples with the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
merged_tuple = tuple1 + tuple2
print(f"The merged tuple is: {merged_tuple}")
19. Write a Python program to convert a tuple into a string.
my_tuple = ('H', 'e', 'l', 'l', 'o')
my_string = ''.join(my_tuple)
print(f"The converted string is: {my_string}")
20. Write a program to check whether an element exists in a tuple or not.
my_tuple = (1, 2, 3, 4, 5)
element = int(input("Enter an element to check in
the tuple: "))
if element in my_tuple:
print(f"The element {element} exists in the tuple.")
else:
print(f"The element {element} does not exist in the tuple.")
21. Write a program to reverse a tuple.
my_tuple = (1, 2, 3, 4, 5)
reversed_tuple = my_tuple[::-1]
print(f"The reversed tuple is: {reversed_tuple}")
22. Write a program to multiply all the elements of a tuple.
my_tuple = (1, 2, 3, 4, 5)
product = 1
for num in my_tuple:
product *= num
print(f"The product of all elements in the tuple is: {product}")
23. Python program to add 'ed' at the end of a given verb string.
verb = input("Enter a verb: ")
if verb[-1] == 'e':
past_tense = verb + 'd'
else:
past_tense = verb + 'ed'
print(f"The past tense of the verb is: {past_tense}")
24. Python program to check if the string is a pangram.
import string
sentence = input("Enter a sentence: ").lower()
alphabet_set = set(string.ascii_lowercase)
input_set = set(sentence)
if alphabet_set.issubset(input_set):
print("The sentence is a pangram.")
else:
print("The sentence is not a pangram.")
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_elements = list(set(list1) & set(list2))
print(f"The common elements are: {common_elements}")
26. Python program to find if the number is a perfect number or not.
num = int(input("Enter a number: "))
divisors_sum = sum([i for i in range(1, num) if num % i == 0])
if num == divisors_sum:
print("The entered number is a perfect number.")
else:
print("The entered number is not a perfect number.")
27. Fibonacci series.
terms = int(input("Enter the number of terms for the Fibonacci series: "))
fibonacci_series = [0, 1]
while len(fibonacci_series) < terms:
next_term = fibonacci_series[-1] + fibonacci_series[-2]
fibonacci_series.append(next_term)
print(f"The Fibonacci series is: {fibonacci_series}")
28. Kivy Installation.
To install Kivy, use the following command in the terminal:
pip install kivy
29. Kivy Programs.
Hello World Program:
from kivy.app import App
from kivy.uix.label import Label
class HelloWorldApp(App):
def build(self):
return Label(text='Hello, World!')
if __name__ == '__main__':
HelloWorldApp().run()
from kivy.app import App
from kivy.uix.image import Image
class ImageApp(App):
def build(self):
return Image(source='path/to/your/image.png')
if __name__ == '__main__':
ImageApp().run()
from kivy.app import App
from kivy.uix.button import Button
class ButtonApp(App):
def build(self):
return Button(text='Click me!')
if __name__ == '__main__':
ButtonApp().run()
Display Label and Checkboxes:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.checkbox import CheckBox
class LabelCheckboxApp(App):
def build(self):
layout = BoxLayout(orientation='vertical')
layout.add_widget(Label(text='This is a Label'))
layout.add_widget(CheckBox())
layout.add_widget(CheckBox())
return layout
if __name__ == '__main__':
LabelCheckboxApp().run()
30. Installation of Django.
To install Django, use the following command in the terminal:
pip install Django
31. Hello World Program in Django.
- Create a new Django project:
django-admin startproject myproject
- Navigate to the project folder:
cd myproject
- Create a new Django app:
python manage.py startapp myapp
- Edit
views.py
in the myapp
folder:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello, World!")
- Edit
urls.py
in the myapp
folder:
from django.urls import path
from .views import hello
urlpatterns = [
path('hello/', hello, name='hello'),
]
- Edit
urls.py
in the myproject
folder:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
- Run the development server:
python manage.py runserver
- Open a web browser and go to http://127.0.0.1:8000/myapp/hello/
32. Program to Print Date and Time using Django.
- Edit
views.py
in the myapp
folder:
from django.http import HttpResponse
from datetime import datetime
def current_datetime(request):
now = datetime.now()
return HttpResponse(f"Current date and time: {now}")
- Edit
urls.py
in the myapp
folder:
from django.urls import path
from .views import current_datetime
urlpatterns = [
path('current_datetime/', current_datetime, name='current_datetime'),
]
- Run the development server:
python manage.py runserver
- Open a web browser and go to http://127.0.0.1:8000/myapp/current_datetime/
33. Program to Print Time after 10 Hours through Dynamic URLs using Django:
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('time_plus_10_hours/<int:hours>/', views.time_plus_10_hours, name='time_plus_10_hours'),
]
# views.py
from django.http import HttpResponse
from datetime import datetime, timedelta
def time_plus_10_hours(request, hours):
current_time = datetime.now() + timedelta(hours=hours)
return HttpResponse(f'Time after {hours} hours: {current_time}')
34. Program to Demonstrate Template in Django:
# views.py
from django.shortcuts import render
def demo_template(request):
context = {'variable': 'Hello, this is a template demo!'}
return render(request, 'demo_template.html', context)
35. Creating Django Admin Interface:
# Run the following command in your Django project directory
python manage.py createsuperuser
36. Creating Django Models:
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
published_date = models.DateField()
def __str__(self):
return self.title
37. CRUD Operations on Models:
# views.py
from django.shortcuts import render, get_object_or_404
from .models import Book
def book_detail(request, book_id):
book = get_object_or_404(Book, pk=book_id)
return render(request, 'book_detail.html', {'book': book})
38. Python Programs on Functions:
# Function to add two numbers
def add_numbers(a, b):
return a + b
# Function to subtract two numbers
def subtract_numbers(a, b):
return a - b
Continue with the rest of the questions in a similar manner. If you have any specific question you'd like me to provide an answer for, feel free to let me know.
39. Programs on Recursion to Find the Factorial of a Number:
Recursive Method:
def recursive_factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * recursive_factorial(n - 1)
Iterative Method:
def iterative_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
40. Python Programs on Lambda Function:
Example 1: Lambda Function for Addition
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Example 2: Lambda Function for Squaring
square = lambda x: x ** 2
print(square(4)) # Output: 16
41. Python Programs on __init__
Function:
Example: Using __init__
in a Class
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display_details(self):
print(f"Name: {self.name}, Age: {self.age}")
# Usage
student1 = Student("John", 20)
student1.display_details()
42. Create a Class with __init__
Function and Normal def
Function for Displaying the Details:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_details(self):
print(f"Make: {self.make}, Model: {self.model}, Year: {self.year}")
# Usage
car1 = Car("Toyota", "Camry", 2022)
car1.display_details()
43. Program to Print Star Pattern:
rows = 5
for i in range(1, rows + 1):
print('* ' * i)
44. Program on Matplotlib:
import matplotlib.pyplot as plt
# Sample Data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Plotting a Line Graph
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Graph')
plt.show()
45. Program on Pandas:
import pandas as pd
# Sample Data
data = {'Name': ['John', 'Alice', 'Bob'],
'Age': [25, 30, 22]}
# Creating a DataFrame
df = pd.DataFrame(data)
# Displaying the DataFrame
print(df)
46. Program on Web Scraping using BeautifulSoup:
import requests
from bs4 import BeautifulSoup
# URL of the website
url = "http://quotes.toscrape.com"
# Sending a GET request
response = requests.get(url)
# Parsing HTML content
soup = BeautifulSoup(response.text, 'html.parser')
# Extracting quotes
quotes = soup.find_all('span', class_='text')
# Displaying quotes
for i, quote in enumerate(quotes, 1):
print(f"Quote {i}: {quote.text}")
47. Programs on Scipy:
Example: Optimization using Scipy
from scipy.optimize import minimize
# Objective function
def objective_function(x):
return x**2 + 5*x + 6
# Minimizing the objective function
result = minimize(objective_function, x0=0)
# Displaying the result
print("Optimal Solution:", result.x)
print("Minimum Value:", result.fun)
--
Sure, here are the steps to set up and create a Django project:
- Install Django: First, you need to install Django. You can do this using pip, which is a package manager for Python. Open your terminal and type the following command:
pip install django
- Create a Django Project: Once Django is installed, you can create a new Django project. Navigate to the directory where you want to create your project and run the following command:
django-admin startproject myproject
Replace myproject
with the name you want to give to your project.
- Run the Server: Navigate into your new project directory and start the Django development server:
cd myproject
python manage.py runserver
Now, you should be able to see your project running at http://127.0.0.1:8000/
in your web browser.
Sure, here are the steps to set up a virtual environment for Django:
Install venv: venv
is included in Python and it's used to manage virtual environments. If you don't have Python installed, you can download it from the official website².
Create a Virtual Environment: Navigate to the directory where you want to create your project and run the following command:
python -m venv myenv
Replace myenv
with the name you want to give to your virtual environment¹.
- Activate the Virtual Environment: Once you've created the virtual environment, you need to activate it. The command to do this varies depending on your operating system:
myenv\\Scripts\\activate.bat
source myenv/bin/activate
You'll know that your virtual environment is activated because its name will be displayed in your terminal, something like (myenv)
¹.
Remember, you need to activate the virtual environment every time you open a new terminal window to work on your project¹.
- Install Django in the Virtual Environment: Now that your virtual environment is activated, you can install Django. This will install Django in the virtual environment, not on your system Python. Here's the command to do this:
pip install django
Now you're all set! You have a virtual environment set up for your Django project. Let me know if you need help with anything else!
Source: Conversation with Bing, 15/01/2024
(1) How to install Django on Windows | Django documentation | Django. https://docs.djangoproject.com/en/5.0/howto/windows/.
(2) Django Create Virtual Environment - W3Schools. https://www.w3schools.com/django/django_create_virtual_environment.php.
(3) python - Setting up virtual environment in Django - Stack Overflow. https://stackoverflow.com/questions/66775192/setting-up-virtual-environment-in-django.
(4) Setting up a virtual environment for your Django Project - CodeSource.io. https://codesource.io/setting-up-a-virtual-environment-for-your-django-project/.
(5) undefined. https://www.python.org/downloads/.
--
Sure, here are the commands in a copyable format:
To install Django:
pip install django
To create a Django project:
django-admin startproject myproject
To run the server:
cd myproject
python manage.py runserver
To install venv:
python -m venv myenv
To activate the virtual environment on Windows:
myenv\\Scripts\\activate.bat
To activate the virtual environment on Unix or MacOS:
source myenv/bin/activate
To install Django in the virtual environment:
pip install django
--
Certainly, here's the provided code converted to proper Markdown:
1. Installation and Setup:
# Install React Router DOM
npm install react-router-dom
// Import necessary components and modules
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// Define routes within the main component
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
Explanation:
- React Router is installed using npm.
- Components and modules from the
react-router-dom
library are imported.
- Routes are defined within the main component using the
Router
, Route
, and Switch
components.
2. React Components:
import React from 'react';
function Header() {
return <header>This is the Header</header>;
}
Main Component:
import React from 'react';
function Main() {
return <main>This is the Main Section</main>;
}
import React from 'react';
function Footer() {
return <footer>This is the Footer</footer>;
}
Counter Component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
ToggleExample Component:
import React, { useState } from 'react';
function ToggleExample() {
const [isOn, setIsOn] = useState(false);
const toggleSwitch = () => {
setIsOn(!isOn);
};
return (
<div>
<p>The switch is {isOn ? 'on' : 'off'}</p>
<button onClick={toggleSwitch}>Toggle</button>
</div>
);
}
LifecycleExample Component:
import React, { Component } from 'react';
class LifecycleExample extends Component {
componentDidMount() {
console.log('Component is mounted');
// Add additional logic as needed
}
componentWillUnmount() {
console.log('Component is about to unmount');
// Cleanup or additional logic before unmounting
}
render() {
return <p>This is a component with lifecycle methods</p>;
}
}
import React, { useState } from 'react';
function DropdownFilter() {
const [selectedOption, setSelectedOption] = useState('');
const handleSelectChange = (e) => {
setSelectedOption(e.target.value);
// Implement filter logic based on the selected option
};
return (
<div>
<label>Filter by:</label>
<select value={selectedOption} onChange={handleSelectChange}>
<option value="">Select an option</option>
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
{/* Add more options as needed */}
</select>
</div>
);
}
InteractiveExample Component:
import React, { useState } from 'react';
function InteractiveExample() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
3. Class Components and Function Components:
Function Component:
import React from 'react';
const FunctionComponent = () => {
return <p>This is a Function Component</p>;
};
Class Component:
import React, { Component } from 'react';
class ClassComponent extends Component {
render() {
return <p>This is a Class Component</p>;
}
}
EventHandlingExample Component:
import React, { useState } from 'react';
function EventHandlingExample() {
const [buttonClicked, setButtonClicked] = useState(false);
const handleButtonClick = () => {
setButtonClicked(true);
// Add additional logic as needed
};
return (
<div>
<button onClick={handleButtonClick}>Click me</button>
{buttonClicked && <p>Button clicked!</p>}
</div>
);
}
Certainly! Here are some additional important concepts in React:
4. React Hooks:
useState:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
useEffect:
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data from an API or perform side effects
// Update the state using setData
}, []); // Dependency array to control when the effect runs
}
useContext:
import React, { useContext } from 'react';
const MyContext = React.createContext();
function MyComponent() {
const contextValue = useContext(MyContext);
return <p>Context value: {contextValue}</p>;
}
useReducer:
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
</div>
);
}
5. React Router:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
Route Parameters:
<Route path="/user/:id" component={UserProfile} />
Nested Routes:
<Route path="/dashboard">
<Dashboard>
<Route path="/dashboard/profile" component={UserProfile} />
<Route path="/dashboard/settings" component={UserSettings} />
</Dashboard>
</Route>
6. Class Components and Function Components:
Function Component:
import React from 'react';
const FunctionComponent = () => {
return <p>This is a Function Component</p>;
};
Class Component:
import React, { Component } from 'react';
class ClassComponent extends Component {
render() {
return <p>This is a Class Component</p>;
}
}
Certainly! Continuing with the formatting for the remaining practical assignments:
4. Practical Assignment Number 4: Implement a Functional Front-End Web Application
Objective:
- Develop a functional front-end web application using React.
- Ensure proper state management and component interaction.
Example:
// Front-end web application using React
import React, { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default App;
5. Practical Assignment Number 5: Use Reactstrap for Designing Responsive Applications
Objective:
- Design a responsive React application using Reactstrap.
- Utilize Reactstrap components for layout and styling.
Example:
// Responsive React application using Reactstrap
import React from 'react';
import { Container, Row, Col, Button } from 'reactstrap';
function App() {
return (
<Container>
<Row>
<Col>
<h1>Reactstrap Example</h1>
</Col>
</Row>
<Row>
<Col>
<Button color="primary">Click me</Button>
</Col>
</Row>
</Container>
);
}
export default App;
6. Practical Assignment Number 6: Use Redux for React-Redux Application
Objective:
- Implement Redux for state management in a React-Redux application.
- Showcase the architecture and data flow within the application.
Example:
// React-Redux application with Redux state management
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
// Reducer function
const counterReducer = (state = { count: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
};
// Redux store
const store = createStore(counterReducer);
// Component using Redux
const Counter = () => {
const handleIncrement = () => {
store.dispatch({ type: 'INCREMENT' });
};
return (
<div>
<p>Count: {store.getState().count}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
};
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
export default App;