Categories
python trending

how to create and implementing contact book / address using python

Python programming language is used to create a list of contacts . Dictionaries’ are used to store the names and contact details of people  . Dictionary is the most preferred choice because it follows the method of keys and values i.e it assigns a key for every value stored in it  . In case of a phonebook , the keys reassemble the contacts name and the value equates with the phone number.

Source code to implementing contact book / address using python

Below are source code available please run this code in python IDE

contact_list={}
flag=True
def addContact(key,val):
if key not in contact_list:
contact_list[key]=val
else:
print("Already Existing")
def deleteContact(key):
if key in contact_list:
contact_list.pop(key)
else:
print("Contact not found")
def searchContact(key):
if key in contact_list:
print(key,contact_list[key])
else:
print("Contact not found")
def modifyName(key):
if key in contact_list:
name=input("Enter the name you want it to be saved")
contact_list[name]=contact_list[key]
del contact_list[key]
else:
print("Contact not found")
def modifyNo(key):
if key in contact_list:
no=int(input("Enter modified mobile no"))
contact_list[key]=no
else:

print("Contact not found")
def displayContacts():
for key,val in contact_list.items():
print(key,val)

while(flag):
print()
print("1.Add Contact 2.Delete Contact 3.Search Contact 4.Modify Contact 5.Display Conatacts
6.Exit")
ch=int(input("Enter your choice"))
if(ch==1):
key=input("Enter name")
val=int(input("Enter mobile no"))
addContact(key,val)
elif(ch==2):
key=input("Enter contact name to be deleted")
deleteContact(key)
elif(ch==3):
key=input("Enter the contact name to be searched")
searchContact(key)
elif(ch==4):
key=input("Enter contact name to be modified")
print("1.To change the name of existing contact 2.To change mobile no")
c=int(input())
if(c==1):
modifyName(key)
elif(c==2):
modifyNo(key)
else:
print("Wrong choice")
elif(ch==5):

displayContacts()
elif(ch==6):
flag=False;
else:
print("Wrong Choice")

Output windows for implementing contact book / address using python

this is a final output windows which shown after the run above code

how to create and implementing contact book / address using python

Summary :

In this article we saw how to create and implementing contact book / address using python so about this article yo have any query then free to ask me

Categories
python trending

How to refresh directory in Python

Hello friends in this article we will see How to refresh directory in Python 3.9 so Basically I am take one common example for refresh directory

How to refresh directory in Python 3.9

I want refresh the downloads directory for every 15 secs.
Source Code Available below:

flag=1
    while flag :
         print("15 secs...")
         time.sleep(155)
         for file in files:
              if (some condition):
                  print("found"+file)
                  flag =0

Summary :

In this article we saw How to refresh directory in Python so about this article you have any query then free to ask me

Categories
python trending

How to read and write file from remote server using python

Introduction to Remote Server in python :
The standard Python module multiprocessing got introduced in Python 2.6 and makes creating simple client and server applications in extremely easy way.

In this article we will learn how to read and write local/remote files.

But why ?

Reason is it allows accessing arbitrary file it is probably a good idea to not use it exactly like this, but rather to extend, or at least adjust the password.
For Example –
Method 01) Using py_remote_file_client.py in Squish test scripts

Prerequisites:

Script py_remote_file_client.py must reside in test suite directory

Script py_remote_file_server.py must running on the remote computer (started like this: python py_remote_file_server.py

function main()
{
    var remote_file_name = "C:\\test.txt";
    var local_file_name = "C:\\Users\\MyUser\\Desktop\\test.txt_from-remote";
    var cmd = 'python "' + squishinfo.testCase + '/../py_remote_file_client.py" '
        + 'get "' + remote_file_name + '" "' + local_file_name + '"';
    result = OS.system(cmd);
    if (result != 0) {
       test.log("An error occurred");
    }

    var local_file_name = "C:\\Users\\MyUser\\Desktop\\test.txt";
    var remote_file_name = "C:\\Users\\AnotherUser\\test.txt";
    var cmd = 'python "' + squishinfo.testCase + '/../py_remote_file_client.py" '
        + 'get "' + remote_file_name + '" "' + local_file_name + '"';
    result = OS.system(cmd);
    if (result != 0) {
       test.log("An error occurred");
    }
}

Example 02 –

Using py_remote_file_client.py without Squish

Prerequisites:

Script py_remote_file_server.py must have been started on the remote computer
Executed in cmd.exe:

C:\Users\MyUser\Desktop> python py_remote_file_client.py get C:\ThatFileOverThere.txt .\ThatFile-from_remote_computer.txt

Summary :

In this article we saw How to read a file from remote server using python so about this article you have any query then free to ask me.

Categories
python trending

how to make your own MP3 music player in python using Tkinter

The media player is in dark theme with all the functionalities of a modern media player we can adjust the volume from the player switch back and front to previous and next songs. We can shuffle our playlist and also can move the song to any position as we want using the song slider.

Which Packages Used for create own Mp3 music player using python

from tkinter import *
import tkinter.ttk as ttk
import pygame
import os
from PIL import ImageTk,Image
import random
from tkinter import filedialog
import time
from mutagen.mp3 import MP3

The Above packages are used to make the make the Media Player

i. tkinter for using Gui in python
ii. tkinter.ttk for using Slider for volume and song track
iii. pygame used for sound libraries
iv. os module for importing songs from file
v. PIL module used for images
vi. Random module used for shuffling playlist
vii. Filedialog used for adding more songs in the player directly
viii. Time module used for tracking song sound
ix. Mutagen used to get the song length

Tk() function is used to initialize the root window. The root window is a main application window in our programs.

Initial after calling all the packages a class My_music_player() is created and in the class a class constructor is created to initialise:

The use of the constructor is given below

i. Initializing Root window
ii. Title of the player
iii. Icon (bitmap)
iv. Dimension(geometry) of the player
v. Initialised pygame and pygame mixer
vi. Variables declared for track and status
vii. Root.root.resizable(0, 0) function is called to prevent resizing of window
viii. Global variables are declared to use in the player
ix. Initializing variables to use it further as accordingly

Media player title and Icon

Play Frame is created to group the control keys of the player.
All the control keys in the player comes under this frame. Control keys include Stop Button, Previous Button, Play and Pause Button,Shuffle Button and Button for hiding the Playlist.

Control Keys for MP3 player in python

All the Buttons are Assigned their respective functions using command attribute. The functionalities are stop button for stopping the music, Previous and Next Button for Previous and next songs, Play and Pause Button for playing and pausing the musing, shuffle button is also included to shuffle the play list.
The button keys are made using icon and Font Awesome 5 font.
The play pause button chances according to the playing and pausing of music

Change in Play Pause Button in python

Buttons and Lables of Tkinter module is used to create the control key in the play frame.

Playerarea Frame is created to show the player area where Image is show for better looks.
Song slider and volume controls are given in this frame.
Song Description and status of the song is also included in this frame.
The duration of the song and time elapsed is also shown in this frame.

Volume control functions in MP3 player in python
The symbol of the volume icon changes on increasing and decreasing of the volume and mute and unmute the volume.
Volume can be adjusted using the slider scrolling up and down
Ttk.scale() is used to create the volume slider.

Functions and attributes of Pygame module are use to adjust and set the volume using the slider

We can move the song to any position as we want using the song slider.
The Description area shows the Name of the song currently Playing and also the status of the song i.e. Playing, Paused or Stopped.

Add Button in MP3 player in python

Add Button is also included to add song to the player directly form the computer we can select multiple files also at once. The songs are added at the end of the playlist.

The Player Frame with above mentioned fuctionalities

how to make your own MP3 music player in python using Tkinter

The third Frame used in this media player is song_list Frame.
This frame is used for the playlist of the media player.
Listbox of tkinter is used for the playlist.
Scrolling option on the right side of the playlist is enabled for scrolling along y axis to access songs in the playlist.

Double click functionality is enables on the listbox to play the selected song.
Song can also be played using tha play button after selecting the song by clicking once.
Bind() is use to bind the mouse click for playing songs.

Functions of OS modules are used to fetch the song from the song folder.
Song can also be added using the add button.

Many function are created to do task according to the button press from the control area. The functions include function to add song, function to manage double click and playing the song, function to adjust volume, Functions for play and pause music and start and stop music, function to hide playlist, function to shuffle the playlist, functions to mute and unmute.
Functionalities for previous and next songs.and slider functions.

The whole media player looks like this

how to make your own MP3 music player in python using Tkinter

Source Coding For Create Mp3 music player in python :

We need to First import all necessary Library

from tkinter import *
from tkinter import filedialog
from pygame import mixer

Create class & Buttons for our application

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False

Adding Load Method to our MusicPlayer class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()

Adding Play Method to our class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
After adding Play Method to our class we need a Method to pause and unpause & also to stop the Music

Finally Let’s add pause and stop method to our class
Python
class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state=True
        else:
            mixer.music.unpause()
            self.playing_state = False
    def stop(self):
        mixer.music.stop()
​

look at our Final will app (app.py)

from tkinter import *
from tkinter import filedialog
from pygame import mixer
​
class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) 
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state=True
        else:
            mixer.music.unpause()
            self.playing_state = False
    def stop(self):
        mixer.music.stop()
root = Tk()
app= MusicPlayer(root)
root.mainloop()
credit goes to kalebujordan

Summary :

In this article we saw how to make your own MP3 music player in python using Tkinter so about this article you have any query then free to ask me

Categories
python trending

How to download Pandas Dataframe as CSV in Django

There can be three ways in which either we can download pandas dataframe or output the pandas dataframe as Excel or CSV in django. The ways are discussed below:-

How to download Panda Dataframe as CSV in Django

Step 1 : download pandas dataframe by mounting our drive in Django

Follow following steps one by one

• Import drive and pandas library modules
• Mount your drive
• Paste the path of your file
• Get the id of the file
• Now create the file with the same id in your drive
• Now get the data of the file
• Read the data in csv format

from google.colab import drive
import pandas as pd
drive.mount(“content/drive”)
link = “link of the file to download”
id = link.split(“/”)[-2]
downloaded = drive.CreateFile({‘id’:id})
downloaded.GetContentFile(‘data.csv’)
df = pd.read_csv(“path where the file is downloaded in the drive”)

Step 2 : directly return response csv format in Django

• Import HttpResponse and pandas library
• Define a function which will return the response in the csv format
• Now initiate a dataframe object
• State the response type as text/csv
• Now attach the file name which you want to be printed
• Now read the file as you want using to_csv function

import pandas as pd
def fun():
results = pd.Dataframe()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=filename.csv'
results.to_csv(path_or_buf=response,sep=';',float_format='%.2f',index=False,decimal=",")

Step 3 : We can directly read the csv file using the url

With the help of below code line we directly read the csv file using the url

Import pandas as pd
url = “raw github link”
df1 = pd.read_csv(url)
print(df1.to_string())

Summary :

In this article we saw Three Steps for download Panda Dataframe as CSV in Django so about this article you have any query then free to ask me

BEST OF LUCK!!!

Categories
python trending

different modules in python 3.10

Consider module to be the same as code library. A file containing a set of functions you want to include in your application. There are different types of modules in python.

  1. Import 
  2. From………  Import
  3. Renaming 
different modules in python 3.10

Import Module in python 3.10

The import statement is use to import all the functionality of one module into another. We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file. Create the module named as file.py

Import module1,module2,…….. module n 

Examples:

1.	import platform

x = platform.system()

print(x)

2.	import datetime

x = datetime.datetime.now()

print(x)

From… import Module in python 3.10

Instead of importing the whole module into the namespace, python provides the flexibility tom import only the specific attributes of a module. This can be done by using from? Import statement.

From < module-name> import <name 1>, <name 2>..,<name n>  

Examples:

1.	from sklearn.preprocessing import LabelEncoder

2.	from sklearn.model_selection import train_test_split

3.	from sklearn.preprocessing import StandardScaler

4.	from sklearn.preprocessing import StandardScale

5.	from sklearn.linear_model import LinearRegression

6.	from sklearn.linear_model import Ridge, Lasso

7.	from sklearn.metrics import mean_squared_error

Renaming modules in python 3.10

Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.

Import <module-name> as <specific-name> 

Examples:

1.	import numpy as np

2.	import pandas as pd

3.	import matplotlib.pyplot as plt

4.	import seaborn as sns

5.	import warnings

6.	%matplotlib inline

7.	warnings.filterwarnings('ignore')

Summary :

In this article we saw different modules in python 3.10 so about this section you have any query then free to ask me

Also see:

class and object in python

String Function in python

Categories
python trending

Relation between class and object in python 3.9.1

class and object in python 3.9.1

  • A class is a blueprint from which you can
    create the instance (object).
  • object is simply a collection of data (variables)
    and methods (functions) that act on those data.
  • classes have logical existence. – classes have physical existence.
  • A class doesn’t any memory space when
    created. (Also read Enumerate in python)
  • An object takes up the memory when it is
    created by the programmer.
class and object in python 3.9.1
Example:
- Creating a class name person.
Class person:
Def__init__(self, name, age, gender):
Self.name = name
Self.age = age
Self.gender = gender
P1 = person(‘Sachin’, 22, ‘male’)
Print(p1.name)
Print(p1.age)
Print(p1.gender)

Output:
Sachin
22
male
- creating an object in class name person.
Class person:
Def__init__(self, name, age, gender):
Self.name = name

Self.age = age
Self.gender = gender
Def myfunc(self):
Print(‘my name is’ + self.name)
Print(p1.name)
Print(p1.age)
Print(p1.gender)
P1.myfunc()

Output:
My name is Sachin.

Summary :

In this article we saw Relation between class and object in python 3.9.1 so about this article you have any query then free to ask me

Also see :

String Function in python

Break, Pass in python

Categories
python trending

Attributes in python 3.9 : Private,Protected and Global

These three attributes are the access modifiers which limit the access of the variables and functions of a class.

Attributes in python 3.9

In the object-oriented languages access modifiers are used to limit the access to the variables and functions of a class. Most of the languages including python have three types of access modifiers, they are – global, private and protected.

Just like any other object-oriented programming language, access to variables or functions can also be limited in python using the access modifiers. Python makes the use of underscores to specify the access modifier for a specific data member and member function in a class.

Access modifiers play an important role to protect the data from unauthorized access as well as protecting it from getting manipulated. When inheritance is implemented there is a huge risk for the data to get destroyed or manipulated due to transfer of unwanted data from the parent class to the child class. Therefore, it is very important to provide the right access modifiers for different data members and member functions depending upon the requirements.

Protected Attributes in python 3.9.1

Protected members of a class can be accessed by other members

within the class and are also available to their subclasses.

No other entity can access these members. In order to do so, they can inherit the parent

class. Python has a unique convention to make a member Protected: Add a prefix _(single

underscore). This prevents its usage by outside entities unless it is a subclass.

For example:  In the last example if we want make the ‘horn’ attribute protected then we

have to just prefix it with single underscore: self._horn

Global Attributes in python 3.9.1

Global members of a class are available to everyone. So, they can be

accessed from outside the class and also by other classes too. All members of a class are by

default global in Python. These members can be accessed outside of the class, and their

values can be modified too.

For example:  if we define the horn attribute as self.horn. it will become a global attribute

and can be simply accessed.

Summary :

In this article we saw Attributes in python 3.9 : Private,Protected and Global so about this section you have any query then free to ask me

Name of Intern who share this Task :

rekha lodhi github link: https://github.com/Rekha5649

Categories
python trending

common built in data types in python with sequence example

Different common built in data types in python with sequence example :

Different common built in data types in python with sequence example

• Text Type:- Str(String)
1)String is a python sequence of character.
2)It is a derived data type.

Also read : comprehension in python

• Numeric Types:- int, float, complex
1)Int is a integer. It is used to convert a specified value into an integer number.
2)Float is a data type used to return a floating point number from a number or string.
3)Complex is used to convert number or string into complex number.

• Sequence Types:-List,Tuple,Range
1)List is a collection of object. List are ordered in type. It contain arbitrary objects. Elements of a list can accessed by an index. List contain other list as sublists. Lists are in variable in size. Lists are mutable that’s why list can be changed.
2)Tuple is an immutable list. Once a tuple is created it cannot be changed. Tuple is analogously to lists. Tuples are faster as compare to list.to protect data from accidental changes use tuples instead of using list. Tuples can be used as keys in dictionaries while list can’t be used in dictionaries.
3)In Range function elements can be accessed using index values.

Also see : Generator in python
• Mapping Types:-Dict
1)Dict is a Dictionary . It is mutable.keys of dict are arbitrary.
• Set Types:-Set,Frozenset
1)Set is a mutable.add(),remove() like these operations performs on set but it is not possible to do these operations on frozenset. Set do not record element position. Set do not support indexing,slicing, or any other sequence related operations.
2)Frozenset is a immutable
• Boolean Type:-bool
Bool is used to represent the truth value of an expression.
In boolean type there are only two possible values True or False.
• Binary Types:-Bytes,bytearray,memoryview
1)Byte and Byte arrays are used to manipulate binary data in python.These are supported by protocol named memoryview.
2)Memoryview can access the memory of other binary object without copying actual data.

Also see : prime factor in python

Summary :

In this article we saw common built in data types in python with sequence example so about this section you have any query then free to ask me

Name of Intern Who share this Task :

Categories
python trending

what is dict and list comprehensions in python and how to use them

Key point about Dict comprehension

Key point about Dict comprehension :

1) Dict is a Dictionary which is used in python.

 2)Dictionary is used to store elements.

 3)Dict is an unordered and mutable python container,which stores mapping of unique keys to values.

 4)Dictionaries are written with curly brackets({}). Key value pairs are separated by comma(,) , a colon(:). It separates each key value from its value.

 5)Dict is a kind of Hash Table.

6)Number and strings are used in dict.

7)In dict duplicate values are not allowed.

8)Dictionary comprehension used to convert one dictionary to another dictionary.

9)Dict is a powerful concept and used for lambda and loops functions.

Also see : Database in python

Example on Dict comprehension :

my_dict={‘name’ : ‘om’, ‘age’ : 17} 
print(my_dict[‘name’])
print(my_dict.get(‘age’))
print(my_dict[‘address’])
Output:-
      Om
      17

Key point about List Comprehension :

  1. List is used for creating new list from other iterables.
  2. List comprehension returns list, it consist brackets which contains expressions. This expressions executed for element along with for loop to iterate over each element.
  3. Basic Syntax Of List- new_list =[expression
    for_loop_one_or_more conditions]
  4. It offers a short syntax when to create a new list which depends upon the values of an existing lists.
  5. It is more compact and faster than the normal functions and loops for creating list.
  6. There are three elements in every list comprehensions
    a)Expression- It is the member of itself.
    b)Member-It is the object or value in the list or iterable
    c)Iterable- It is a list,set,sequence,generator,or any other object that can returns its elements one at a time.

Also see : Decorator in python

Summary :

In this article we saw what is dict and list comprehensions in python and how to use them. so about this section you have any query then free to ask me

Name of Intern who share this Task :

Prafulla Rajendra Aher