Review of Python - 10

Python: Introduction

Python is a high-level, interpreted, and easy-to-read programming language, used in: Web Development, AI & Data Science, Automation, Software Development, etc.

Advantages of Python

1. Simple and Readable Syntax
2. Extensive Libraries and Frameworks
3. Highly Portable

Disdvantages of Python

1. High Memory Consumption
2. Weak in Mobile Computing
3. Runtime Errors

Python Syntax Basics

Printing Output
>>> print("Hello World")
Comments
# Single line comment
‘’’ Multi line comment ‘’’

Variables

Variables are identifiers that store data.
name = "Sujal"
age = 22
'name' and 'age' are variables that have value 'Sujal' and 22 respectively.
Rules
a. Cannot start with numbers
b. No spaces allowed
c. Case-sensitive

Data Types

Data Types Example
int 10
float 3.14
str "Hello"
bool True
list [1,2,3]
dict {"a":1}

Check Type
>>> print(type(age))

Input from User

>>> name = input("Enter name: ")
>>> age = int(input("Enter age: "))

Operators

Operators are symbols or keywords that tell a computer to perform specific actions, computations, or logical manipulations on data. They are the building blocks used to connect values and variables (called operands) into actionable expressions.

Arithmetic Operators

    +	:	Addition Operator
    -	:	Subtraction Operator
    *	:	Multiplication Operator
    /	:	Division Operator
    //	:	Integer Division Operator
    %	:	Modulus(Remainder) Operator
    **	:	Exponent Operator
    

Comparison Operators

    ==	:	Check if equal
    !=	:	Check if not equal
    >	:	Check if greater
    <	:	Check if lesser
    >=	:	Check if greater than or equal to
    <=	:	Check if lesser than or equal to
    

Logical Operators

    and	:	Both True
    or	:	Any True
    not	:	Opposite
    

Program Flow Structures

Program flow controls how code executes.

Sequential Flow

Statments execute one after another in a sequence. >>> #Program to add two numbers >>> a=5 >>> b=3 >>> print(a+b)

Selective/Conditional Flow

Such flow is to execute decision making and alternate outputs to a program.

Conditional Statements

if Statement >>> #Check if a person is adult. >>> age = 18 >>> if age >= 18: print("Adult") if-else Statement >>> #Check if a person is adult or minor. >>> if age >= 18: print("Adult") >>> else: print("Minor") if-elif Statement >>> marks = 75 >>> if marks >= 80: print("Distinction") >>> elif marks >= 60: print("First Division") >>> else: print("Pass")

Iterative/Loop Flow

Used to repeat same statements again and again while the need to repeat is there.

Looping Statements

for Loop >>> #Display natural numbers upto 4. >>> for i in range(5): >>> print(i) while Loop >>> # Print numbers upto 5. >>> count=1 >>> while count<=5: >>> print(count) >>> count+=1
Review Practice Programs
    1.	WAP to display the sum of two numbers.
        Solution:
        a=int(input("Enter first number:"))
        b=int(input("Enter second number:"))
        s=a+b
        print("The sum is ",s)
        
2. WAP to find the area of rectangle and circle. Solution: l=float(input("Enter length:")) b=float(input("Enter breadth:")) r=float(input("Enter radius:")) ArR=l*b ArC=(22/7)*r**2 print(ArR) print(ArC)
3. WAP to find the Simple Interest. Solution: p=float(input("Enter Principle:")) t=float(input("Enter Time:")) r=float(input("Enter Rate:")) si=(p*t*r)/100 print("The simple interest is Rs.",si)
4. WAP to convert Celsius to Fahrenheit scale of temperature. Solution: c=float(input("Enter Celsius:")) f=(9/5)*c+32 print("The converted temp value is",f,"F")
5. WAP to convert days into years, months and days. Solution: days=int(input("Enter days:")) years=days//365 rem_days=days%365 months=rem_days//30 final_days=rem_days%30 print(days,"days means",years,"years",months,"months", final_days,"days") #Write in the same line
6. WAP to check if a person is eligible to vote or not. Solution: age=int(input("Enter age:")) if age>=18: print("Eligible") else: print("Not Eligible")
7. WAP to check if a number is even or odd. Solution: a=int(input("Enter a number:")) if a%2==0: print("Even number") else: print("Odd number")
8. WAP to check if a number is positive, negative or zero. Solution: a=int(input("Enter number:")) if a==0: print("Zero") elif a>0: print("Positive") else: print("Negative")
9. WAP to find the greatest among three numbers. Solution: a=int(input("Enter first number:")) b=int(input("Enter second number:")) c=int(input("Enter third number:")) if (a>b>c): print("Greatest number is:",a) elif (b>a>c): print("Greatest number is:",b) else: print("Greatest number is:",c)
10. WAP to find the middle number among three numbers. Solution: a=int(input("Enter first number:")) b=int(input("Enter second number:")) c=int(input("Enter third number:")) if (a<b<c or a>b>c): print("Middle number is:",b) elif (b<a<c or b>a>c): print("Middle number is:",a) else: print("Middle number is:",c)
11. WAP to display the first 10 natural numbers. Solution: for i in range(1,11): print(i)
12. WAP to display even numbers from 200 to 300. Solution: for i in range(200,301,2): print(i)
13. WAP to display odd numbers from 300 to 200. Solution: for i in range(299,200,-2): print(i)
14. WAP to display the table of 21.(upto 10). Solution: for i in range(1,11): print(21,"*",i,"=",21*i)
15. WAP to display the following pattern: 1 12 123 1234 12345
	Solution:
	for i in range(1,6):
        	for j in range(1,i+1):
            		print(j,end="")
         	print()
    

    16. WAP to check if a number is a palindrome or not.
    	Solution:
        n=int(input("Enter number:"))
        z=n
        s=0
        while n>0:
        	r=n%10
                s=s*10+r
                n=n//10
        if s==z:
        	print("Palindrome")
        else:
        	print("Not Palindrome")
        
17. WAP to check if a number is a armstrong or not. Solution: n=int(input("Enter number:")) z=n s=0 while n>0: r=n%10 s=s+r**3 n=n//10 if s==z: print("Armstrong") else: print("Not Armstrong")
18. WAP to check if a number is a prime or composite. Solution: n=int(input("Enter number:")) f=0 for i in range(1,n+1): if (n%i==0): f+=1 if (f==2): print("Prime") else: print("Composite")
19. WAP to display the Fibonacci sequence 0,1,1,.... upto n terms. Solution: terms=int(input("Enter number of terms:")) a=0 #Decide the starting point from the question b=1 #Decide the starting point from the question for i in range(terms): print(a, end=" ") c=a+b a=b b=c
20. WAP to display the Hailstone sequence 7,22,11,.... upto n terms. Solution: terms=int(input("Enter number of terms:")) n=7 #Decide the starting point from the question for i in range(terms): print(n, end=" ") if (n%2==0): n=n//2 else: n=3*n+1

Python Lists

A list in Python is a data type that is used to store multiple items in a single variable.
Lists are:
  • Ordered
  • Changeable (Mutable)
  • Allow duplicate values
Syntax of List
    list_name = [item1, item2, item3]
    
Example
    fruits = ["Apple", "Mango", "Orange"]
    print(fruits)
    
Accessing List Items

List items are accessed using index numbers. These index numbers start at 0 by default. If need be to access the list in reverse order, one can also start the indexing from -1.

    fruits = ["Apple", "Mango", "Orange"]
    print(fruits[0])
    print(fruits[1])
    print(fruits[2])
    print(fruits[-1])
    print(fruits[-2])
    
Output:
    Apple
    Mango
    Orange
    Orange
    Mango
    
Changing List Items
    fruits = ["Apple", "Mango", "Orange"]
    fruits[1] = "Banana"
    print(fruits)
    
Output:
    ['Apple', 'Banana', 'Orange']
    
Adding Items to List
(a) append() Function

The append() function adds an item at the end of the list.

    fruits = ["Apple", "Mango"]
    fruits.append("Orange")
    print(fruits)
    
(b) insert() Function

The insert() function adds an item at a specific position.

    fruits = ["Apple", "Mango"]
    fruits.insert(1, "Banana")
    print(fruits)
    
Removing Items from List
(a) remove() Function - Remove a particular element from the list.
    fruits = ["Apple", "Mango", "Orange"]
    fruits.remove("Mango")
    print(fruits)
    
(b) pop() Function

The pop() function removes item using index number.

    fruits = ["Apple", "Mango", "Orange"]
    fruits.pop(1)
    print(fruits)
    
Length of List

The len() function returns the total number of items in a list.

    fruits = ["Apple", "Mango", "Orange"]
    print(len(fruits))
    
Output:
    3
    
Looping Through a List
    fruits = ["Apple", "Mango", "Orange"]

    for item in fruits:
        print(item)
    
Example Program Using List
Program: Store 5 Numbers and Find Their Sum
    numbers = [10, 20, 30, 40, 50]
    total=0
    for i in range(len(numbers)):
    	total+=numbers[i]
    print("Sum =", total)
    

Output

    Sum = 150
    

Dictionaries in Python

Dictionary

A dictionary a data type in python that is used to store data in key-value pairs.

Dictionaries are:

  • Ordered
  • Changeable
  • Do not allow duplicate keys
Syntax of Dictionary
    dictionary_name = {
        key1: value1,
        key2: value2
    }
    
Example
    student = {
        "name": "Ram",
        "age": 15,
        "grade": 10
    }
    print(student)
    
Accessing Dictionary Values
    student = {
        "name": "Ram",
        "age": 15
    }
    print(student["name"])
    print(student["age"])
    
Output:
    Ram
    15
    
Changing Dictionary Values
    student = {
        "name": "Ram",
        "age": 15
    }
    student["age"] = 16
    print(student)
    
Output:
    {"name": "Ram", "age": 16}
    
Adding Items to Dictionary
    student = {
        "name": "Ram",
        "age": 15
    }
    student["grade"] = 10
    print(student)
    
Output:
    {"name": "Ram", "age": 15, "grade": 10}
    
Removing Items from Dictionary
pop() Function
    student = {
        "name": "Ram",
        "age": 15
    }
    student.pop("age")
    print(student)
    
Dictionary Functions
Function Purpose
keys() Returns a list of all the keys
values() Returns a list of all the values
items() Returns a list of all the key-value pairs
clear() Removes all items

Looping Through Dictionary
    student = {
        "name": "Ram",
        "age": 15,
        "grade": 10
    }
    for key, value in student.items():
        print(key, ":", value)
    
Output:
    	name : Ram
        age  : 15
        grade: 10
    
Example Program
Program: Store Student Information
    student = {
        "name": "Sita",
        "age": 16,
        "grade": 10
    }
    print("Name =", student["name"])
    print("Age =", student["age"])
    print("Grade =", student["grade"])
    
Output
    Name = Sita
    Age = 16
    Grade = 10
    
Program: Check Whether Key Exists
    student = {
        "name": "Ram",
        "age": 15
    }
    if "name" in student:
        print("Key exists")
    else:
        print("Key does not exist")
    
Output:
    Key exists
    

Difference Between List and Dictionary

List Dictionary
Stores items Stores key-value pairs
Uses square brackets [ ] Uses curly brackets { }
Accessed using index Accessed using keys
Allows duplicate items Duplicate keys not allowed

Review Practice Programs(Lists and Dictionaries)
    21. WAP to input ten numbers from the user and store them in the list. The program should then display the greatest number among ten numbers.
        Solution:
        num=[]
        for i in range(10):
            n=int(input("Enter number:"))
            num.append(n)
        greatest=max(num)
        print("Greatest number is", greatest)
    
22. WAP to store five numbers in the list. The program should then display the product of all the numbers. Solution: num=[] product=1 for i in range(5): n=int(input("Enter number:")) num.append(n) for i in num: product=product*i print("Product =", product)
23. WAP to input ten numbers from the user and store them in the list. The program should then count the even and odd numbers separately. Solution: num=[] even=0 odd=0 for i in range(10): n=int(input("Enter number:")) num.append(n) for i in num: if i%2==0: even=even+1 else: odd=odd+1 print("Even numbers =", even) print("Odd numbers =", odd)
24. WAP to display the longest word among three different words. Solution: w1=input("Enter first word:") w2=input("Enter second word:") w3=input("Enter third word:") longest=w1 if len(w2)>len(longest): longest=w2 if len(w3)>len(longest): longest=w3 print("Longest word is", longest)
25. WAP to count the number of consonants present in the given word. Solution: word=input("Enter a word:").lower() count=0 vowels="aeiou" for ch in word: if (ch not in vowels): count=count+1 print("Number of consonants =", count)
26. WAP to count the number of characters N/n present in the given word. Solution: word=input("Enter a word:") count=0 for ch in word: if ch=="N" or ch=="n": count=count+1 print("Number of N/n =", count)