Python Codes

Codes
Files to be installed in Python:-
pip install pandas

pip install matplotlib

Note :- It will install all kind of libraries
		
Print stars in Python:-
rows = 6
for i in range(0, rows):
    for j in range(0, i + 1):
        print("*", end=' ')
    print("\r")
		
Convert CSV to Dataframe and Read Data and Print Graph in Python:-
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('csv/Book2.csv')

Myname = input('Enter student Name')

for index, row in df.iterrows():
    if(Myname==row[1]):
        e = row['English']
        h = row['hindi']
        m = row['Maths']
        s = row['Science']
        print(e+h)


Marks =[e,h,m,s]
subject = ['English','Hinid','Maths','Science']
plt.plot(Marks,subject)
plt.xlabel('Marks')
plt.title('Student Record')
plt.ylabel('Subjects')
plt.show()

		
How to apply Breakpoint in Python:-
In this Part we show how to set Breakpoint in PYTHON

Step 1 :- set this line at top of page
import pdb

Step 2:- Now set this line where we start from debugging
pdb.set_trace()

Step 3 :- Now Run the program using F5 key
Now it will automatically stop at this point
Now to exectue next line Press "n"
It will automatically exectue the next line
		
List Operations in Python[using for loop]:-

myList = [22,4,16,38,13] #myList having 5 elements
choice = 0
for attempt in range (15):
    print("\nL I S T O P E R A T I O N S")
    print(" 1. Append an element")
    print(" 2. Insert an element at the desired position")
    print(" 3. Append a list to the given list")
    print(" 4. Modify an existing element")
    print(" 5. Delete an existing element by its position")
    print(" 6. Delete an existing element by its value")
    print(" 7. Sort the list in ascending order")
    print(" 8. Sort the list in descending order")
    print(" 9. Display the list")
    choice = int(input("ENTER YOUR CHOICE (1-9): "))

#append element
    if choice == 1:
        element = eval(input("Enter the element to be appended: "))
        myList.append(element)
        print("The element has been appended\n")
#insert an element at desired position
    elif choice == 2:
        element = eval(input("Enter the element to be inserted: "))
        pos = int(input("Enter the position:"))
        myList.insert(pos,element)
        print("The element has been inserted\n")
    #append a list to the given list

    elif choice == 3:
        newList = eval(input("Enter the list to be appended: "))
        myList.extend(newList)
        print("The list has been appended\n")
#modify an existing element
    elif choice == 4:
        i = int(input("Enter the position of the element to be modified: "))
        if i < len(myList):
            newElement = eval(input("Enter the new element: "))
            oldElement = myList[i]
            myList[i] = newElement
            print("The element",oldElement,"has been modified\n")
        else:
            print("Position of the element is more then the length of list")
#delete an existing element by position
    elif choice == 5:
        i = int(input("Enter the position of the element to be deleted: "))
        if i < len(myList):
            element = myList.pop(i)
            print("The element",element,"has been deleted\n")
        else:
            print("\nPosition of the element is more then the length of list")

    elif choice == 6:
        element = int(input("\nEnter the element to be deleted: "))
        if element in myList:
            myList.remove(element)
            print("\nThe element",element,"has been deleted\n")
        else:
            print("\nElement",element,"is not present in the list")
#list in sorted order
            
    elif choice == 7:
        myList.sort()
        print("\nThe list has been sorted")
#list in reverse sorted order
    elif choice == 8:
        myList.sort(reverse = True)
        print("\nThe list has been sorted in reverse order")
        
    elif choice == 9:
        print("\nThe list is:", myList)
    else:
        print("Choice is not valid")

		
Database Connectivity in MYSQL[using while loop]:-
import mysql.connector
from tabulate import tabulate

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="school"
)

mycursor = mydb.cursor()

def StudentRegistration():
    
  def inputNumber(message):
    while True:
      try:
        userInput = int(input(message))       
      except ValueError:
        print("Only Integer in Mobile No.")
        continue
      else:
       return userInput 
       break 
     
  StudentName = input("Enter student name :")
  EmailID = input("Enter EmailID :")
  MobileNo = inputNumber("Enter Your Mobile Number")
  genderInput = input("Enter 'M' for Male or 'F' for Female\n").upper()
  if genderInput == "M":
    gender = "Male"
    #print(gender)
  elif genderInput == "F":
    gender= "Female"

  if StudentName.isdigit():
    print('Integer are not allowed on Student Name')
  elif genderInput != "M" and genderInput != "F" :
    print("Invalid Entry for Gender")
  else:
   sql = "INSERT INTO stud(studname,emailid,mobileno,gender)VALUES(%s,%s,%s,%s)"
   val = (StudentName,EmailID,MobileNo,gender)
   mycursor.execute(sql, val)

   mydb.commit()
   main()




def ShowStudents():
  mycursor.execute("SELECT * FROM stud")
  myresult = mycursor.fetchall()
  """
  for x in myresult:
    print(x)
  """
  print(tabulate(myresult, headers=['Student ID','Student Name','EmailID','Mobile No', 'Gender'], tablefmt='psql'))
  main()



def DeleteRecordByID():
    #cs = mydb.cursor()
  StudentID = int(input('Enter Student ID '))
  mycursor.execute("SELECT * FROM stud WHERE studid = %s",(StudentID,))
  mycursor.fetchone()
  row_count = mycursor.rowcount
  #print("number of affected rows: {}".format(row_count))
  if row_count == 0:
      print("Invalid ID, Please Try Again...")
  else:
      mycursor.execute("delete FROM stud WHERE studid = %s",(StudentID,))
      print('Record Deleted Successfully..')
      mydb.commit()
      main()

  

def main():
    print("""
    1.Student Registration
    2.Show All Students
    3.Delete Record By ID
    """)
    choice=input("Enter Choice no.:")
    while True:
      if(choice=='1'):
          StudentRegistration()
      elif(choice=='2'):
          ShowStudents()
      elif(choice=='3'):
          DeleteRecordByID()
      else:
          print("wrong choice.........")
    main()
main()

		
CSV Operations in Python:-
		
from csv import writer
from csv import DictReader
import csv
import pandas as pd
from csv import DictWriter


ch=''

print("\tMAIN MENU")
print("\t1. NEW ENTRY")
print("\t2. Thanks Message")
print("\t3. SHOW ENTRY")
print("\t5. Show specific Record by Name")
print("\t6. Delete Record by Name")
print("\t7. Check Data Exist or Not")

print("\tSelect Your Option (1-4) ")
ch = input()

if ch == '1': 
    
    Rollno = int(input("Enter Rollno :"))
    StudentName = input("Enter Name :")
    Subject = input("Enter Subject :")


  
# The data assigned to the list 
    list_data=[Rollno,StudentName,Subject]
  
# Pre-requisite - The CSV file should be manually closed before running this code.

# First, open the old CSV file in append mode, hence mentioned as 'a'
# Then, for the CSV file, create a file object
    with open('csv/Book1.csv', 'a', newline='') as f_object:  
        # Pass the CSV  file object to the writer() function
        writer_object = writer(f_object)
    # Result - a writer object
    # Pass the data in the list as an argument into the writerow() function
        writer_object.writerow(list_data)  
    # Close the file object
        f_object.close()
                            

elif ch == '2':
        print("\tThanks for using system")
        
elif ch == '3':
    with open('csv/Book1.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                #print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                print(f'\t{row[0]}   {row[1]}    {row[2]}.')
                line_count += 1
                #print(f'Processed {line_count} lines.')

                
elif ch == '5':
    lines = list()
    #input number you want to search
    Myname = input('Enter name to find :')

#read csv, and split on "," the line
    csv_file = csv.reader(open('csv/Book1.csv', "r"), delimiter=",")


#loop through the csv list
    for row in csv_file:
        #if current rows 2nd value is equal to input, print that row
        if(Myname == row[1]):
            print(row)


elif ch == '6':
    #1. This code snippet asks the user for a username and deletes the user's record from file.
    updatedlist=[]
    with open("csv/Book1.csv",newline="") as f:
      reader=csv.reader(f)
      username=input("Enter the username of the user you wish to remove from file:")
      
      for row in reader: #for every row in the file
            
                if row[1]!=username: #as long as the username is not in the row .......
                    updatedlist.append(row) #add each row, line by line, into a list called 'udpatedlist'
      with open("csv/Book1.csv","w",newline="") as f:
        Writer=csv.writer(f)
        Writer.writerows(updatedlist)
        print("Record has Been deleted successfully")
    
        
elif ch == '7':
      RollNo=''
      MyRollno = input("Enter Roll no : ")
      inf = csv.reader(open('CSV_File/CSV22.csv','r'))
      for row in inf:
         if MyRollno in row:
            RollNo=row[0]

     if RollNo==MyRollno:
         print("Rollno Number Already Exist!!")
     else:
         a = input("Enter the Roll Number : ")
         b = input("Enter the Account Name : ")
         field_names = ['Account_Number','Account_Name']
         dict={'Account_Number':a,'Account_Name':b}
         with open('CSV_File/CSV22.csv', 'a',newline='') as f_object:
              dictwriter_object = DictWriter(f_object, fieldnames=field_names)
              dictwriter_object.writerow(dict)
              f_object.close()
              print("Registered Successfully..")


        



else :
        print("Invalid choice")



		
Free Web Hosting