7.1 Programming Language

Basic Definitions

  • Command: The specific instruction.
  • Syntax: The grammatical rules and structure of cmd
  • ​PL: The syntax of command.
  • ​High-level PL: The human-friendly syntax of cmd.
  • ​Low-level PL: The machine-friendly syntax of cmd.
  • ​Programming: The process of cmd.
  • ​Programmer: The author of cmd.
  • ​Program: The set of cmd.
  • ​Software: The collection of cmd.
  • ​Software Engineer: The designer of cmd.

Logic & Design

  • ​Algorithm: The logic of cmd.
  • ​Flowchart: The diagram of cmd.
  • ​Coding: The writing of cmd.
  • Bugs: The hidden error of cmd.
  • Syntax Error: The grammatical mistake of cmd
  • ​Debugging: The correction of cmd.
  • ​Testing: The verification of cmd.

Translators

  • ​Compiler: The whole-translator of cmd.
  • ​Interpreter: The line-translator of cmd.

Syntax & Structure

  • ​Python: The simple-syntax of cmd.
  • Comments: The non executable note of cmd.
  • ​I/O statement: The communication-syntax of cmd.
  • Keyword: The reserved cmd.
  • ​Conditional statements: The decision-making of cmd.
  • ​Iteration: The repetition of cmd.
  • ​Operator: The symbol of cmd.
  • ​Expression: The combination of cmd.

Data & Storage

  • ​Data Types: The categories of cmd.
  • ​Variables: The containers of cmd.
  • ​Type casting: The data types conversion of cmd.
  • ​List: The ordered-sequence of cmd.
  • ​Dictionary: The key-value-mapping of cmd.
  • ​Library: The pre-written-collection of cmd.
  • Function: The reusable block of cmd.
  • ​Database: The data storage of cmd.
  • DBMS: The data management-system of cmd.

7.2 Types of programming language:

High level programming language is source code.

Low level programming language is compiled machine code.

7.3 Programming tools 

Algorithm is a  pseudocode "pronounce sudo-code" that guides a computer on how to solve a problem.

Flowchart is visual diagram of an algorithm.

7.4 Coding is writing instructions, Testing is checking for mistakes. Debugging is fixing them.

7.5 Compiler translates at once and display error at end. e.g.c. Interpreter translate line-by-line and display errors. e.g. Python.

7.6 Python: Guido Van Rossum in 1991 and uses in web development, data science, machine learning, AI etc.

Features: Easy to read, write, versatile, beginner friendly.

7.7 Comment syntax 

#Singleline,    '''3'Multiline '''

7.8 I/O statement.  Name=input("Name:")

a,b,c=input("Enter three String as space  /','/'-'  ").split('  '/","/"-")

a,b,c = map(int, input (" Three Numbers by space: ").split())

print(f'Given numbers: {a},{b},{c} Sum={a+b+c}')

n = list(map(int, input("Numbers: ").split()))

print(n)

print(*n)

Or print(n[0],n[1])

n = [int(n) for n in input('Input any numbers with comma to sum').split(',')]  

print(n)

s=sum(n)

print(s)

OR

print(sum(int(n) for n in input('Input any numbers with a comma to sum: ').split(',')))

A,B,C=(1,2,3)

X,Y,Z=1,"Hi",True

SWAP N=[1,2] =>N[0], N[1] =N[1],N[0]  =>N=[2,1]

Print("Hello")

If name="Ram" & age=25

print("Name is %s and old %d." %(name,age)

print("Name is {} and old {}." .format(name,age))

print(f"Name is {name} and old {age}.")

7.9 Data types and variables 

int, float, str, bool, a=5, b=1.2, name="Ram"


7.10 Type casting 

a. Automatic type conversion 

x=10, y=5.5, z=x+y print(z)

b. Intentionally 

x=4.5, int(x) print(x); x=4, float(x) print(x)

7.11 Operators and expressions 

1. Arithmetic: +,-,*,/,%,**

2. Relational: ==,!=,>,<,>=,<=

3. Logical: AND, OR, NOT

4.Assignment:=,+=,-,*=, /=,%=,**=

5. Expression: I= (p*t*r)/100

e.g: a=float(input("a="))

b=float(input(b="))

c=a+b

print(f"a={a}, b={b} & c={c}.")

7.12 Conditional statement 

1. if condition: ... ... ...

2. if condition: ... ... ... else

3.if c1: ...elif c2: ... else..

e.g. n=int(input("n="))

if n>0:

print("+ve")

elif n==0:

print("zero")

else:

print("-ve")

OR n=int(input("n="))

print("+ve" if n>0

else "zero" if n==0

else "-ve)

7.13 Iteration 

1. for item in sequence:

e.g. for x in range(5): print(x)

2. if condition: ..else: pass

3. for number in range(1,6):

if number==3: continue print(number)

4. for number in range(1,6):

if number==3: break print(number)

5. While condition:

e.g. count=1

While count<=5:

(4space)print (count)

(4space)count+=1

7.14 Python list and Dictionary 

Mylist=["CS","Sc", 20, True]

print (Mylist), print(len(Mylist))

mydict={"Student":"Pen", "Teacher":"Marker", "Tailer:"Needle"}

print(mydict)

7.15 Use of library 

String Methods

# center()

print("hello".center(10, '*'))**hello***

# upper()

print("Hello".upper()HELLO

# lower()

print("Hello".lower()hello

Built-in Functions

# len()

print(len("world"))5

# sum()

print(sum([1, 2, 3]))6

# abs()

print(abs(-5))5

# round()

print(round(3.14159, 2))3.14

# max()

print(max([1, 5, 2])) 5

# min()

print(min([1, 5, 2])) 1

math Module Functions

import math

# math.sqrt()

print(math.sqrt(9)) 3.0

# math.ceil()

print(math.ceil(4.2)) 5

# math.floor()

print(math.floor(4.8))4

# math.factorial()

print(math.factorial(4)) 24

# math.pow()

print(math.pow(2, 3)) 8.0

# math.sin()

print(math.sin(math.pi / 2)) 1.0

# math.log()

print(math.log(100, 10)) 2.0



Python Practice Tasks

#1. Adding two numbers (Constant initialization)

number_1 = 5

number_2 = 7

add = number_1 + number_2

print("The addition of number_1 and number_2 is: ", add)


#2. Adding two numbers (User input)

number_1 = int(input("Enter the first number: "))

number_2 = int(input("Enter the second number: "))

result = number_1 + number_2

print(f"The sum of {number_1} and {number_2} is: {result}")


#3. Calculating the area of a circle

radius = float(input("Enter the radius of the circle: "))

area = 3.14159 * (radius ** 2)

print("The area of the circle is: ", area)


#4. Calculating the area of a rectangle

length = float(input("Enter the length of the rectangle: "))

width = float(input("Enter the width of the rectangle: "))

area = length * width

print("The area of the rectangle is: ", area)


#5. Greeting a user (String formatting)

user_name = input("Enter your name: ")

greeting = (f"Hello! {user_name}")

print(greeting)


#6. Temperature check (Warm day)

temperature = float(input("Enter the current temperature in Celsius: "))

if temperature > 25:

    print("It's a warm day.")


#7. Odd or even number check

number = int(input("Enter an integer: "))

if number % 2 == 0:

    print("The number is even.")

else:

    print("The number is odd.")


#8. Finding the greatest of two numbers

number_1 = input("Enter the first number: ")

number_2 = input("Enter the second number: ")

if (number_1 > number_2):

    greater_number = number_1

else:

    greater_number = number_2

print("The greater number is: ", greater_number)


#9. Number range check (10-100)

number = float(input("Enter a number: "))

if 10 <= number <= 100:

    print("The number is within the range.")

else:

    print("The number is outside the range.")


#10. Divisibility check (by 7)

number = int(input("Enter a number: "))

if number % 7 == 0:

    print(f"{number} is divisible by 7.")

else:

    print(f"{number} is not divisible by 7.")


#11. Greatest of three numbers

number_1 = int(input("Enter the first number: "))

number_2 = int(input("Enter the second number: "))

number_3 = int(input("Enter the third number: "))

if (number_1 > number_2) and (number_1 > number_3):

    print("number_1 is greater.", number_1)

elif (number_2 > number_1) and (number_2 > number_3):

    print("number_2 is greater.", number_2)

else:

    print("number_3 is greater.", number_3)


#12. Leap year check

year = int(input("Enter the year: "))

if year % 100 == 0:

    if year % 400 == 0:

        print("Entered year is a leap year")

    else:

        print("Entered year is not a leap year")

elif year % 4 == 0:

    print("Entered year is a leap year")

else:

    print("Entered year is not a leap year")


#13. Middle number among three

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

num3 = float(input("Enter the third number: "))

if num1 <= num2 <= num3 or num3 <= num2 <= num1:

    middle_number = num2

elif num2 <= num1 <= num3 or num3 <= num1 <= num2:

    middle_number = num1

else:

    middle_number = num3

print(f"The middle number among {num1}, {num2}, and {num3} is: {middle_number}")


#14. Student grading system

score = float(input("Enter the student's score: "))

if score >= 90:

    grade = 'A'

elif score >= 80:

    grade = 'B'

elif score >= 70:

    grade = 'C'

elif score >= 60:

    grade = 'D'

else:

    grade = 'F'

print(f"The student's grade is: {grade}")


#15. Triangle classification

angle1 = float(input("Enter the first angle: "))

angle2 = float(input("Enter the second angle: "))

angle3 = float(input("Enter the third angle: "))

if angle1 + angle2 + angle3 == 180:

    if angle1 == angle2 == angle3:

        print("It's an Equilateral triangle.")

    elif angle1 == angle2 or angle2 == angle3 or angle1 == angle3:

        print("It's an Isosceles triangle.")

    else:

        print("It's a Scalene triangle.")

else:

    print("Invalid triangle angles.")


#16. Print 1 to 10 (for loop)

for number in range(1, 11):

    print(number)


#17. Sum of first 10 natural numbers

sum_of_numbers = 0

for number in range(1, 11):

    sum_of_numbers += number

print("The sum of the first 10 natural numbers is:", sum_of_numbers)


#18. Print even numbers in range (for loop)

for i in range(2, 11, 2):

    print(i)


#19. Reverse order numbers 10 to 1

for i in range(10, 0, -1):

    print(i)


#20. Calculate factorial of 10

num = 10

factorial = 1

for i in range(1, num + 1):

    factorial *= i

print(f"Factorial of {num}: {factorial}")


#21. Star pattern triangle

for i in range(1, 6):

    print('*' * i)


#22. Average of numbers in a list

numbers = [5, 8, 12, 3, 6]

average = sum(numbers) / len(numbers)

print("Average:", average)


#23. Sum of N numbers (User input)

N = int(input("Enter the value of N: "))

total = 0

for i in range(N):

    num = float(input(f"Enter number {i+1}: "))

    total += num

print(f"The sum of {N} numbers is: {total}")


#24. Print 1 to 15 (while loop)

number = 1

while number <= 15:

    print(number)

    number += 1


#25. First 10 integers and their squares

i = 1

while i <= 10:

    print(f"Number: {i}, Square: {i**2}")

    i += 1


#26. Sum of first 10 natural numbers (while loop)

sum_of_numbers = 0

number = 1

while number <= 10:

    sum_of_numbers += number

    number += 1

print("The sum of the first 10 natural numbers is: ", sum_of_numbers)


#27. Product of digits of a number

number = int(input("Enter a number: "))

product = 1

while number > 0:

    digit = number % 10

    product *= digit

    number //= 10

print("Product of the digits:", product)


#28. Reverse a number (while loop)

number = int(input("Enter a number: "))


reversed_number = 0


while number > 0:

    digit = number % 10

    

    reversed_number = (reversed_number * 10) + digit

    number //= 10


print("Reversed number: ", reversed_number)


#29. Fibonacci series till n terms

n = int(input("Enter the number of terms in the Fibonacci series: "))

first_term, second_term = 0, 1

count = 0

while count < n:

    print(first_term, end=", ")

    next_term = first_term + second_term

    first_term = second_term

    second_term = next_term

    count += 1


#30. Armstrong number check

number = int(input("Enter a number: "))

original_number = number

num_digits = len(str(number))

sum_of_digits = 0

while number > 0:

    digit = number % 10

    sum_of_digits += digit ** num_digits

    number //= 10

if original_number == sum_of_di

gits:

    print(f"{original_number} is an Armstrong number.")

else:

    print(f"{original_number} is not an Armstrong number.")

Exercise 

a) Explain programming languages with its types.

Programming languages are sets of instructions used to interact with computers.

 * Low-Level: Machine-specific languages like Machine Code (binary) and Assembly.

 * High-Level: Human-readable languages like Python, Java, and C++.

b) Differentiate between compiler and interpreter.

| Feature | Compiler | Interpreter |

|---|---|---|

| Execution | Scans entire program at once. | Translates line-by-line. |

| Speed | Faster execution after compilation. | Slower execution. |

| Errors | Displays all errors at the end. | Stops at the first error found. |

c) Define algorithm and flowchart.

 * Algorithm: A step-by-step logical procedure to solve a specific problem.

 * Flowchart: A visual or graphical representation of the steps in an algorithm.

d) Five flowchart symbols and functions.

 * Oval (Terminal): Represents Start and End points.

 * Parallelogram (I/O): Represents Input or Output operations.

 * Rectangle (Process): Represents calculations or assignments.

 * Diamond (Decision): Represents conditions (Yes/No).

 * Arrow (Flow line): Shows the direction of the process.

e) Algorithm & Flowchart: Odd or Even

Algorithm:

 * Start.

 * Input number N.

 * If N \pmod 2 == 0, then Print "Even".

 * Else, Print "Odd".

 * Stop.

f) Explain Python programming with its features.

Python is a high-level, interpreted programming language known for simplicity.

 * Easy to read: Syntax resembles English.

 * Portable: Runs on Windows, Mac, and Linux.

 * Large Libraries: Supports data science, AI, and web dev.

g) Describe use of input/output statements in Python.

 * input(): Takes data from the user (always returns a string).

 * print(): Displays data or results on the screen.

h) Formatted string literals (f-strings).

F-strings allow embedding expressions inside string literals using curly braces {}.

Example Program:

user_name = input("Enter your name: ")

print(f"Hello {user_name}! Welcome to our program")

i) Explain data types with examples.

Data types define the kind of value a variable can hold.

 * Integer (int): Whole numbers (e.g., 10, -5).

 * Float (float): Decimal numbers (e.g., 10.5, 3.14).

 * String (str): Text wrapped in quotes (e.g., "Hello").

 * Boolean (bool): Logical values (True or False).

j) Describe typecasting with its types.

Typecasting is converting one data type into another.

 * Implicit: Done automatically by the compiler/interpreter (e.g., adding int to float).

 * Explicit: Done manually by the programmer (e.g., int("10") converts a string to an integer).

k) Types of operators.

Common types: Arithmetic, Relational, Logical, Assignment, and Bitwise.

 * Arithmetic Operators: Used for mathematical calculations.

   * Example: + (Addition), - (Subtraction), * (Multiplication), / (Division).

   * 10 % 3 results in 1 (Remainder).

l) Explain a conditional statement with an example.

Conditional statements execute code only if a specific condition is met.

 * Example:

   age = 18

if age >= 18:

    print("You can vote.")

else:

    print("Too young.")


m) Define iteration & Differentiate Loops.

Iteration: The process of repeating a block of code multiple times.

| Feature | for Loop | while Loop |

| :--- | :--- | :--- |

| Usage | Used when number of iterations is known. | Used when a condition must be met. |

| Control | Iterates over a sequence (list/range). | Continues as long as a condition is True. |

n) Differentiate between list and dictionary.

 * List: An ordered collection of items accessed by index (e.g., [1, 2, 3]).

 * Dictionary: An unordered collection of key-value pairs (e.g., {"name": "Ram", "age": 20}).

o) List Operations.

cities = ["Kathmandu", "Biratnagar", "Nepalgunj", "Pokhara", "Butwal", "Birendranagar", "Mahendranagar", "Balefi"]


# a. Add Malangawa

cities.append("Malangawa")


# b. Remove Balefi

cities.remove("Balefi")


# c. Print items one by one

for city in cities:

    print(city)




Practical Task

8 Download and install python

9 Setup IDE and customize interface.

10 Demonstrate the use of I/O statements.

11 Demonstrate the concept of constant, variable and data types.

12 Demonstrate the use of various operators.

13 Demonstrate the use of if, if else and elif.

14 Demonstrate the use of for loop

15 Demonstrate the use of while loop

16 Demonstrate the list Demonstrate the directory with relevant example. 

17 Demonstrate and use string functions and mathematical functions

Project work

a) Develop a simple real life project using Python programming and libraries such as

calculators, mathematical operations, etc


Practical Activities 

• Download and install the latest version of the Python program at 

https://www.python.org/downloads/.

• Select and install any Python IDEs and code editors such as IDLE, Jupyter, 

Sublime Text, PyCharm, Visual Studio Code, or similar tools.

• Use Python's interactive shell to demonstrate live coding, allowing students 

to experiment with code snippets and see immediate results.

• Discuss the programming logic development tools and group work to 

develop a flowchart and algorithm.

• Demonstrate each programming concept with syntax and code.

• Document each programming code for internal and practical evaluation