Deploy Flask App on Heroku

mkdir app
cd app

app.py

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello World!"

@app.route('/add')
def add():
    num1 = int(request.args.get('num1'));
    num2 = int(request.args.get('num2'));

    return f"{num1} + {num2} = {num1 + num2}"

#if __name__ == "__main__":
    #app.run(debug=True);
    #app.run(host="0.0.0.0", port=int("1234"), debug=True)

runtime.txt

python-3.10.2

Procfile

web: gunicorn app:app

requirements.txt

click==8.0.3
colorama==0.4.4
Flask==2.0.2
Flask-Cors==3.0.10
gunicorn==20.1.0
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
PyMySQL==1.0.2
six==1.16.0
Werkzeug==2.0.2

OR

You can output all dependencies using following command

python -m pip freeze > requirements.txt
heroku login

#onetime
heroku create <appname>
heroku git:remote -a <appname>
git init

#repeat whenever you make changes
git add .
git commit -m 'heroku push'
git push heroku master

Test API

https://myflaskapp2022.herokuapp.com/
https://myflaskapp2022.herokuapp.com/add?num1=5&num2=9

Troubleshoot

heroku logs --tail --app eflask-app-dusra

If still it is not working please do check spellings of files

https://devcenter.heroku.com/articles/buildpacks

Flask Cheat Sheet

keyword arguments

Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names.
keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.

The order of the arguments does not matter

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

arguments vs keyword arguments (*args vs **kwargs)

def foo(*args, **kwargs):
    print(args);
    print(kwargs);
    
foo(5, 6, 7, name="Shailesh", age=32, city="Nagpur");
output

Decorators

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure.
Decorators are usually called before the definition of a function you want to decorate.

### CREATE CUSTOM DECORATOR ###
from functools import wraps

def my_decorator(f):
    @wraps(f)
    def msg(*args, **kwargs):
        print("I am from custom decorator")
        print("Arguments:", args)
        print("Keyword Arguments:", kwargs)
        
        return f(*args, **kwargs)
        
    return msg;


@my_decorator    
def add(x, y):
    print(f"{x} + {y} = {x + y}")

    
@my_decorator
def sub(x, y):
    print(f"{x} - {y} = {abs(x - y)}")
    
    
#invoke functions
add(5, y=6)
sub(5, y=6)
output

Flask Framework

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries.
It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

install flask module

python -m pip install Flask

hello world

from flask import Flask, jsonify, request, render_template

app = Flask(__name__)

#YOUR FUNCTIONS HERE

if __name__ == "__main__":
    app.run(debug=True);
    #app.run(host="0.0.0.0", port=int("1234"), debug=True)

render html template [NOTE: MAKE SURE TO KEEP ALL TEMPLATE FILES IN templates DIRECTORY]

@app.route('/')
def index():
    #return "Hello World";
    
    data = {'company_name': "TCET"}
    return render_template('hello_world.html', data = data)

templates/hello_world.html

<h1>Hello World</h1>
<h3>Welcome to {{data['company_name']}}</h3>

read get value

@app.route('/sqr', methods=['GET'])
def getSqr():
    num1 = int(request.args.get('num1'));
    return f"Square of {num1} is {num1 * num1}"


@app.route('/add', methods=['GET'])
def add():
    num1 = int(request.args.get('num1'));
    num2 = int(request.args.get('num2'));
    
    return f"{num1} + {num2} = {num1 + num2}";

read post value

@app.route('/sub', methods=['POST'])
def sub():
    num1 = int(request.form.get('num1'));
    num2 = int(request.form.get('num2'));
    
    return f"{num1} - {num2} = {num1 - num2}";

read raw json

@app.route('/mul', methods=['POST'])
def mul():
    raw_json = request.get_json();
    num1 = int(raw_json['num1']);
    num2 = int(raw_json['num2']);
    
    return f"{num1} * {num2} = {num1 * num2}";

install pymysql module

python -m pip install PyMySQL

install cors module

python -m pip install -U flask-cors

get users from database

from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql

app = Flask(__name__)
cors = CORS(app)

@app.route('/users', methods=['GET'])
def get_users():
    # To connect MySQL database
    conn = pymysql.connect(host='localhost', user='root', password = "", db='databasename')
        
    cur = conn.cursor()
    cur.execute("select * from users LIMIT 10")
    output = cur.fetchall()

    print(type(output)); #this will print tuple	

    for rec in output:
        print(rec);
        
    # To close the connection
    conn.close()

    return jsonify(output);

fetch data using javascript fetch api

let url = "http://localhost:5000";
fetch(url)
    .then(response => response.json())
    .then(response => console.table(response));

Flask RESTful API

Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs.

install flask-restful

python -m pip install flask-restful

MyApi Resource

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class MyApi(Resource):
    def __init__(self):
        print("Constructor called...")
        
    def get(self):
        return {"msg" : "get method"}
        
    def post(self):
        return {"msg" : "post method"}
        
    def put(self):
        return {"msg" : "put method"}
    
    def delete(self):
        return {"msg" : "delete method"}
    
    
api.add_resource(MyApi, '/myapiurl')

if __name__ == "__main__":
    app.run(debug=True)

Authenticate REST API

from flask import Flask, request, make_response
from flask_restful import Resource, Api
from functools import wraps


app = Flask(__name__)
api = Api(app)


#define custom decorator @authorize
def authorize(f):
    @wraps(f)
    def kuchbhi(*args, **kwargs):
        err_msg = "Authentication required";
    
        if(request.authorization == None):
            return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
            
        unm = request.authorization.username
        pwd = request.authorization.password
        
        if(unm == 'admin' and pwd == 'admin@123'):
            print("Correct username and password")
            return f(*args, **kwargs)
        
        return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
    
    return kuchbhi


class MyApi(Resource):
    
    def __init__(self):
        print("Constructor called...")

    @authorize 
    def get(self):
        return {"msg" : "get method"}

    @authorize    
    def post(self):
        return {"msg" : "post method"}

    @authorize    
    def put(self):
        return {"msg" : "put method"}

    @authorize
    def delete(self):
        return {"msg" : "delete method"}
    
api.add_resource(MyApi, '/myapiurl')

if __name__ == "__main__":
    app.run(debug=True)


apply authorize decorator to all methods of call

from flask import Flask, request, make_response
from flask_restful import Resource, Api
from functools import wraps

app = Flask(__name__)
api = Api(app)

#define custom decorator authorize
def authorize(f):
    @wraps(f)
    def kuchbhi(*args, **kwargs):
        err_msg = "Authentication required";
    
        if(request.authorization == None):
            return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
            
        unm = request.authorization.username
        pwd = request.authorization.password
        
        if(unm == 'admin' and pwd == 'admin@123'):
            print("Correct username and password")
            return f(*args, **kwargs)
        
        return make_response('Not Authorized', 403, {'WWW-Authenticate' : err_msg})
    
    return kuchbhi


class MyApi(Resource):
    method_decorators = [authorize]
    
    def __init__(self):
        print("Constructor called...")
        
    def get(self):
        return {"msg" : "get method"}
        
    def post(self):
        return {"msg" : "post method"}
        
    def put(self):
        return {"msg" : "put method"}
    
    def delete(self):
        return {"msg" : "delete method"}
    
api.add_resource(MyApi, '/myapiurl')

if __name__ == "__main__":
    app.run(debug=True)

Testing API

test response status
test_myapiapp.py
where myapiapp.py is the file where all restful api defined

#from filename import app
from rest_api import app
import unittest
import base64

class RestAPITest(unittest.TestCase):
    
    def test_status(self):
        tester = app.test_client(self)
        response = tester.get('/myapiurl')
        self.assertEqual(response.status_code, 200)
   
if __name__ == "__main__":
    unittest.main()

test content type

def test_content_type(self):
    tester = app.test_client(self)
    response = tester.get('/myapiurl')

    self.assertEqual(response.content_type, "application/json")

test content data

def test_content(self):
    tester = app.test_client(self)
    response = tester.get('/myapiurl')        
    self.assertTrue(b'get' in response.data)

To pass Basic Auth credentials in header

creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})

complete test file code

#from filename import app
from rest_api import app
import unittest
import base64

class RestAPITest(unittest.TestCase):
    
    def test_status(self):
        tester = app.test_client(self)
        #response = tester.get('/myapiurl')
        
        creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
        response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})
        
        self.assertEqual(response.status_code, 200)
        
    
    def test_content_type(self):
        tester = app.test_client(self)
        #response = tester.get('/myapiurl')
        
        creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
        response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})
        
        self.assertEqual(response.content_type, "application/json")
        
        
    def test_content(self):
        tester = app.test_client(self)
        #response = tester.get('/myapiurl')
        
        creds = base64.b64encode(b"admin:admin@123").decode("utf-8")
        response = tester.get('/myapiurl', headers={"Authorization": f"Basic {creds}"})
        
        self.assertTrue(b'get' in response.data)
        
        
if __name__ == "__main__":
    unittest.main()
output

REST API CRUD

app.py

import pymysql

from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql

app = Flask(__name__)
cors = CORS(app)

# To connect MySQL database
conn = pymysql.connect(host='yourhost', user='youruser', password = "yourpassword", db='yourdatabase')

@app.route('/users', methods=['GET'])
def get_users():

    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute("select * from users LIMIT 10")
    output = cur.fetchall()

    print(type(output)); #this will print tuple

    for rec in output:
        print(rec);

    # To close the connection
    #conn.close()

    return jsonify(output);

@app.route('/users', methods=['DELETE'])
def deleteRecord():
    cur = conn.cursor()
    id = int(request.args.get('id'));

    query = f"delete from users where id = {id}";
    #print(query)
    res = cur.execute(query);
    conn.commit();
    print(cur.rowcount, "record(s) deleted")

    return "Record deleted sussesfully"

@app.route('/users', methods=['POST'])
def insertRecord():

        #get raw json values
        raw_json = request.get_json();
        name= raw_json['name'];
        age= raw_json['age'];
        city= raw_json['city'];

        sql="INSERT INTO users (id,name,age,city) VALUES (NULL,'"+name+"','"+str(age)+"','"+city+"')";
        cur= conn.cursor()

        cur.execute(sql);
        conn.commit()
        return "Record inserted Succesfully"

@app.route('/users', methods=['PUT'])
def updateRecord():

        raw_json = request.get_json();

        #print(type(raw_json));

        id = raw_json['id'];
        name= raw_json['name'];
        age= raw_json['age'];
        city= raw_json['city'];
        sql_update_quary=("UPDATE users SET name = '"+name+"',age = '"+str(age)+"',city = '"+city+"'WHERE id = '"+str(id)+"'");
        cur= conn.cursor()
        cur.execute(sql_update_quary);
        conn.commit()
        return "Record Updated Sussecfully";


if __name__ == "__main__":
    #app.run(debug=True);
    app.run(host="0.0.0.0", port=int("1235"), debug=True)

Django REST framework Cheat Sheet

Django Cheat Sheet (codeinsightacademy.com)

pip3 install djangorestframework
python3 manage.py startapp employee
Note: Make sure your sql service is running.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'webpage',
    'rest_framework',
    'employee',
]

employee/models.py

from django.db import models

class Employee(models.Model):
    post = models.CharField(max_length = 100)
    name = models.CharField(max_length = 100)
    salary = models.IntegerField()
    is_active = models.BooleanField(default=False)
    added_date = models.DateField(auto_created=True)
    updated_date = models.DateField(auto_now=True)

    def __str___(self):
        return self.title

to make and apply the migrations run

./manage.py makemigrations
./manage.py migrate

employee/serializers.py

from rest_framework import serializers
from employee.models import Employee

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = "__all__"

employee/views.py

from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.generics import CreateAPIView
from rest_framework.generics import DestroyAPIView
from rest_framework.generics import UpdateAPIView
from employee.serializers import EmployeeSerializer
from employee.models import Employee

class ListEmpAPIView(ListAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

class CreateEmpAPIView(CreateAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

class UpdateEmpAPIView(UpdateAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

class DeleteEmpAPIView(DestroyAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

employee/urls.py

from django.urls import path
from employee import views

urlpatterns = [
    path("",views.ListEmpAPIView.as_view(),name="employee_list"),
    path("create/", views.CreateEmpAPIView.as_view(),name="employee_create"),
    path("update/<int:pk>/",views.UpdateEmpAPIView.as_view(),name="update_employee"),
    path("delete/<int:pk>/",views.DeleteEmpAPIView.as_view(),name="delete_employee")
]

main urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/employee/',include("employee.urls"))
]

Run the api in postman with urls

POST request : http://localhost:8000/api/v1/employee/create/ 
GET request : http://localhost:8000/api/v1/employee
UPDATE request : http://localhost:8000/api/v1/employee/update/1/ 
DELETE request : http://localhost:8000/api/v1/employee/delete/1/ 

Django Cheat Sheet

Install Django

python -m pip install Django==3.1.3

Verify Django Installation

python -m django --version

List all installed python modules / packages

python -m pip list

Create new django project

django-admin startproject projectname

Run Django Project

python manage.py runserver

Create New App

python manage.py startapp newappname

manage.py help

python manage.py help

MySql Database connection

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

open db shell with default connection

python manage.py dbshell

MySql Database Connection Troubleshoot in Windows OS
Download whl package which is compatible with your python version
https://www.lfd.uci.edu/~gohlke/pythonlibs/
Find: mysqlclient

To check whether python is 32 or 64 bit just run following command

python -m pip install mysqlclient-1.4.6-cp37-cp37m-win32.whl

open django project shell in terminal

python manage.py shell

open db shell with specific connection

python manage.py dbshell --database "connection_name"

Create model of legacy(existing) database table using inspectdb

python manage.py inspectdb --database='connection_name' table_name

Import Models in shell

from app.models import ModelName

Select data from table using Django ORM

queryset = ModelName.objects.all()
print(queryset.query)
print(list(queryset))

Filter data using ORM

queryset = ModelName.objects.filter(column=value)
queryset = ModelName.objects.get(column=value) #this will give you single record
queryset = ModelName.objects.filter(column__iexact=value, column2__exact=value2)
queryset = ModelName.objects.filter(col__subcol=value) #for relationship

Limit records in ORM

queryset = ModelName.objects.all()[:10]

Order by in ORM

queryset = ModelName.objects.all().order_by('columnname')
queryset = ModelName.objects.all().order_by('-columnname')
queryset = ModelName.objects.all().order_by('columnname').reverse()

Relationship in models.py (this should be in Model which has foreign key)

foreign_key_col = models.ForeignKey(PrimaryModelName, related_name = 'related_name', on_delete = models.CASCADE, db_column = 'foreign_key_column_name')

install packages from requirements.txt for your project

python -m pip install -r requirements.txt"

Django restframework Cheat Sheet (codeinsightacademy.com)

OOPS

  1. Design a class Rectangle
    data members
    length
    breadth
    member functions/methods
    setDimension()
    area()
    perimeter()

  2. Design a class Worker
    data members
    wages
    wdays
    member function / method
    setData()
    payment()

  3. Design a class Box
    data members
    length
    breadth
    height
    member functions / methods
    setDimension()
    volume()

  4. Design a class Rectangle (only for Java / C++)
    data members
    length
    breadth
    member functions / methods
    setDimension()
    area()
    perimeter()
    It must overload setDimension() method twice:
    1. by passing 1 argument
    2. by passing 2 arguments

  5. Design a class Box (only for Java / C++)
    data members
    length
    breadth
    height
    member functions / methods
    volume()
    It must contain 3 constructors
    1. 1 parameter
    2. 2 parameter
    3. 3 paramter
  6. Design a class Account
    data members
    balance
    member functions / methods
    deposit(amt)
    withdraw(amt)
    showBalance()

  7. Design a class Set
    data members
    3 numbers
    member functions / methods
    SUM()
    MEAN()
    MAX()
    MIN()

  8. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  9. Design a class Account
    data members
    balance
    interest_rate
    interest_rate must be shared by all objects (static modifier) and its default value 10.25
    interest(no_of_years)

  10. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  11. Design a class Account
    account_number
    balance
    interest_rate
    member functions / methods
    interest(no_of_years)

  12. Design a class Student
    data members
    roll_number
    name
    member function / methods
    getData()
    roll_number must be automatically generated.It also keep track of total number of Students.

  13. Design a package MyCircle and MyRectangle (Only for Java)
    radius
    length
    breadth
    member functions / methods:
    area()
    circumference()
    perimeter()

  14. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    getData()
    showData()
    Create 5 objects of Student using Array

  15. Design a class Student and List ClassRoom
    add list of Students in ClassRoom
    display List

  16. Design a class Account and List Bank
    add list of Account in Bank
    display List

  17. Create array of Student Objects
    data members
    roll_no
    name
    college
    member functions / methods
    readData()
    showData()

  18. Create a class RBI (Only for Java)
    data members
    balance
    member functions
    RBI()
    deposit(int amt)
    withdraw(int amt)
    showBalance()

Hello World django

Here are simple steps to create hello world web application in python using django framework

  1. Step 1: Install virtual environment and create virtual environment for your project
    pip install virtualenvwrapper-win
    
    mkvirtualenv myproject
  2. pip install virtualenv
  3. virtualenv name_to_your_env
    
  4. name_to_your_env\Scripts\activate
  5. After activation 
    
    $ django-admin.py startproject HelloWorld  $ cd HelloWorld 
    $ ls HelloWorld manage.py
  6. $ python manage.py runserver 
    Validating models... 
    0 errors found ... 
    Django version 1.6.5, using settings 'HelloWorld.settings' 
    Starting development server at http://127.0.0.1:8000/ 
    Quit the server with CONTROL-C.
  7. $ django-admin startapp HelloWorldApp
    $ ls
    HelloWorld HelloWorldApp manage.py
  8. edit settings.py under HelloWorld project directory
    # Application definition
    INSTALLED_APPS = ( ‘django.contrib.admin’,
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
    ‘django.contrib.sessions’,
    ‘django.contrib.messages’,
    ‘django.contrib.staticfiles’,
    ‘HelloWorldApp’, )
  9. modify the urls.py which is under the project directory, HelloWorld
    from django.conf.urls import patterns, include, url 
    from HelloWorldApp.views import foo 
    
    #from django.contrib import admin 
    #admin.autodiscover() 
    
    urlpatterns = patterns('', 
    # Examples: 
    # url(r'^$', 'HelloWorld.views.home', name='home'), 
    # url(r'^blog/', include('blog.urls')), 
    #url(r'^admin/', include(admin.site.urls)), 
    url(r'HelloWorldApp/$', foo), 
    )
  10. modify views.py under app directory, HelloWorldApp
    # Create your views here. 
    from django.http import HttpResponse 
    def foo(request): 
        return HttpResponse("Hello World!")
  11. Run the server
    python manage.py runserver

     

  12. Hit this URL on browser
    http://localhost:8000/HelloWorldApp/

 

Ref Links:

  • https://docs.djangoproject.com/en/1.11/howto/windows/
  • http://www.bogotobogo.com/python/Django/Python_Django_hello_world.php
  • https://stackoverflow.com/questions/18684231/python-setup-command-not-found
  • https://stackoverflow.com/questions/8074955/cannot-import-name-patterns
  • https://scotch.io/tutorials/build-your-first-python-and-django-application
  • http://jinja.pocoo.org/docs/2.10/templates/

Arrays Programs (Multi Dimensional)

  1. WAP to read a matrix of size 3 X 5 and find their SUM
  2. WAP to read a matrix of size 3 X 5 and find sum of each ROW
  3. WAP to read a matrix of size 3 X 3 and check if it is NULL or NOT
  4. WAP to read a matrix of size 3 X 5 and count all EVEN and ODD numbers
  5. WAP to read matrix of size 3 X 3 and check if it is UNIT Matrix or NOT
  6. WAP to read 2 matrix of size 3 X 3 and find their Addition
  7. WAP to read 2 matrix of size 3 X 3 and find their Product
  8. WAP to read matrix of size 3 X 3 and find its Transpose
  9. WAP to read matrix of size 3 X 3 and find its Transpose without using second matrix
  10. WAP to read matrix of size 3 X 3 and find its Upper Triangular Matrix
  11. WAP to read matrix of size 3 X 3 and find its Lower Triangular Matrix
  12. WAP to read matrix of size 3 X 3 and check if sum of its diagonal is same or not
  13. WAP to read matrix of size 3 X 3 and check if sum of its middle row is same as sum of its middle column
  14. WAP to create TIC-TAC-TOE by showing number and take 9 inputs from 2 users.
    1 2 3
    4 5 6
    7 8 9

    X O X
    O X O
    O O X

    PLAYER 1 WIN
    O X O
    X O X
    O X O

    PLAYER 2 WIN

Arrays Programs (One Dimensional)

  1. WAP to read an array of 10 numbers and find their sum
  2. WAP to read temperature days of Week and find their Mean
  3. WAP to read an array of 10 numbers and find greatest of them
  4. WAP to read an array of 10 numbers and count all EVEN and ODD numbers
  5. WAP to rad an array of 10 numbers and find sum, mean, min, max
  6. WAP to read an array of 10 numbers and search a number in it
  7. WAP to read an array of 10 numbers and sort it in ascending order
  8. WAP to read an array of 10 numbers and sort it in descending order
  9. WAP to insert a number at given position in an array (optional)
  10. WAP to remove a number from given position from an array (optional)
  11. WAP to arrange all even numbers at top and all odd numbers at bottom of an array (optional)

FUNCTIONS

  1. WAF repeat to display a char specified no of times.
  2. WAF intrest to calculate simple intrest.
  3. WAF to return Volume of Sphere
  4. WAF to return mean of 3 numbers
  5. WAF to return greatest of 2 numbers
  6. WAF to return Factorial of given Number
  7. WAF to return Sum of Given Number.
  8. WAF to return Greatest of 3 numbers.
  9. WAF to print all numbers from 1 to given numbers
  10. WAF to repeat a given char given number of timest.
    e.g. repeat(‘#’, 25)
  11. Design a recursive function factorial to return factorial of given number.
  12. Design a recursive function intrest to return compound intrest.
  13. Design a recursive function SOD to return sum of digit of given number.
  14. WAF to return sum of number which is passed in a Array.
  15. WAF to return Mean of numbers which is passed in a Array.
  16. WAF to return Greatest number which is passed in a Array.

Loops Programs

EXACT OUTPUT IS OPTIONAL FOR PYTHON AND JAVASCRIPT

  1. WAP to read a number and print all numbers from 1 to that number
    input: enter a number: 5
    output:
    1
    2
    3
    4
    5
  2. WAP to read number and print all even numbers from 1 to that number
    input: enter a number: 5
    output:
    2
    4
  3. WAP to print all number from 1 to 10 by using while, for and do -while loop.
  4. WAP to read a number and find sum of all numbers from 1 to that number
    input: enter a number: 5
    output: 1 + 2 + 3 + 4 + 5 = 15
  5. WAP to read a number and find factorial of that number
    input: enter a number: 5
    output: 1 * 2 * 3 * 4 * 5 = 120
  6. WAP to read a number and find reverse of that number (optional)
    input: enter a number: 1234
    output: 4321
  7. WAP to read a number and check if it is a prime number or not
    input: enter a number: 5
    output: 5 is a prime number
  8. WAP to print all prime number in range from 1 to 100
    output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
  9. WAP to print first 10 fibonacci number
    output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
  10. WAP to read a number and find sum of its digits (optional)
    input: 12345
    output: 1 + 2 + 3 + 4 + 5 = 15
  11. WAP to find a 3 digit armstrong number (optional)
    output: 153
  12. WAP to print all armstrong numbers from 1 to 999(optional)
    output: 153, 370, 371, 407
  13. WAP to print ASCII chars and values from 1 to 255
  14. WAP to print alphabets from A to Z using loop
  15. WAP to read a number and count all numbers which divides the given number perfectly
  16. WAP to read 2 numbers and print their common factors
  17. WAP to read 2 numbers and print HCF
  18. WAP to print factorial of all numbers from 1 to 10
  19. WAP to read 2 numbers a and b and print all numbers from a to b
  20. WAP to repeatedly read a number until it is in range from 10 to 20
  21. WAP to read a number and print all numbers which divides the given number perfectly
  22. WAP to find sum of series
    S = 1 + 2 + 3 + …. + N
  23. WAP to find sum of series
    S = 1 + 2! + 3! + …. N!
  24. WAP to find sum of series
    S = 1 + 1/2 + 1/3 + 1/4 + 1/5 + …. + 1/N
  25. WAP to find sum of series
    S = 1 – 1/2 + 1/3 – 1/4 + 1/5 – …. 1/N
  26. WAP to read a number and print tables from 1 to that number
  27. WAP to print following output
    • 12345
      1234
      123
      12
      1
    • 54321
      4321
      321
      21
      1
    • *****
      ****
      ***
      **
      *
    • 1234554321
      1234554321
      1234554321
      1234554321
      1234554321
    • 12345123451234512345
      12345123451234512345
      12345123451234512345
    • ABCDE
      ABCD
      ABC
      AB
      A
    • ABCDEFEDCBA
      ABCDE  EDCBA
      ABCD      DCBA
      ABC           CBA
      AB                BA
      A                     A
    • *********
        *******
         *****
          ***
            *
  28. WAP to print table of number in following format using 1 for loop
    input: enter a number: 5
    5 * 1 = 5 5 * 10 = 50
    5 * 2 = 10 5 * 9 = 45
    5 * 3 = 15 5 * 8 = 40
    5 * 4 = 20 5 * 7 = 35
    5 * 5 = 25 5 * 6 = 30
    5 * 6 = 30 5 * 5 = 25
    5 * 7 = 35 5 * 4 = 20 
    5 * 8 = 40 5 * 3 = 15
    5 * 9 = 45 5 * 2 = 10
    5 * 10 = 50 5 * 1 = 5
  29. WAP to create random jackpot number and take input from user to guess the number. Based on level the attempt to guess the number should change
    1. Easy – 20 attempts
    2. Medium – 10 attempts
    3. Difficult – 5 attempts
  30. WAP to execute Fizz Buzz Problem / Print number 1 to 100
    1. if number is divisible by 3 then print Fizz
    2. if number is divisible by 5 then print Buzz
    3. if number is divisible by both 3 and 5 then print Fizz Buzz