Showing posts with label python programming. Show all posts
Showing posts with label python programming. Show all posts

Tuesday, November 3, 2015

Showing a List as String in Python

In my previous example and in my website, I have shown you how to split a string and make a list out of it. We simply used the split() function of the string to do so. e.g.

>>> a="The tiny runner running through the narrow edges"
>>> a.split()
['The', 'tiny', 'runner', 'running', 'through', 'the', 'narrow', 'edges']


As you can see the split operation which can split the string and make a list from it. But what if we need to join it again to get the actual string again? Python has a join keyword for this purpose -

>>> ''.join(a)
'The tiny runner running through the narrow edges'


Now, what if we have a list which has integer variables in it. We can not simply right the above function , we need to have a lambda function. Let's have a list of integers - 

>>> a=[1,2,3,4,4,5,5] 
>>> ''.join(a)

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    ''.join(a)
TypeError: sequence item 0: expected string, int found


We can solve the problem using the lambda function, as shown below -


>>> ''.join(map(lambda a:str(a),a))
'123456'


See, the easy way to get the string back!  

Tuesday, August 18, 2015

Sending and Reading Mail with Python


Sending mail and receiving mail by python can be done by using the module smtplib and imaplib. If you have a mail server configured in your server then you can use localhost and generally the port number 25 to send mail but if you don't have mail server then you can use the mail server you are currently using e.g. gmail or other.
In the below program I have used myoffice mail server which is provided by my office and send mail through it. Lets have a look at the program -

import smtplib #importing the smtplib module
toaddress="toaddress@gmail.com" # the address  where I want to send the email.
fromaddress="someusername@someserver.co.in" #the address from where we want to send mail
msg="Hello Just testing if it is working or not"# The message we want to send
username="someusername"#Giving the username and password of your account
password="********"
server=smtplib.SMTP("mail.wbpdcl.co.in:25")#Now connecting to the server
server.ehlo()# establishing the connection
server.starttls() #start the communication in an encrypted mode
server.login(username,password) #Finally login to the server using the credentials
try:
    server.sendmail(fromaddress,toaddress,msg) #try to send msg by sendmail function
    print "Successfully sent"
except: #if can't be sent display the message below
    print "Not send "
server.quit() #Quit the server
 You can see there are some small steps, that are getting the credentials, knowing the server name and port and the connecting to it with smtplib.SMTP . The next important procedure is to server.login() and server.sendmail(). That's all we need to send mail.


 Receiving mail can be possible with imaplib module. As the server nowadays deny a not secured connections we have to use ssl connection. Here we are connected to our gmail account and see the latest mail there. Lets see the program in detail- 

import imaplib #importing the needed imaplib module
mailserver = imaplib.IMAP4_SSL('imap.gmail.com', 993) #Now connecting to gmail imap server  
username = 'someusername' #giving the needed credentials
password = '********H'
mailserver.login(username, password) #login to the server

status, count = mailserver.select('Inbox') # selecting the inbox from the mailserver

status, data = mailserver.fetch(count[0], '(UID BODY[TEXT])') #now fetching the data as text

print data [0][:]#printing the mail in console
mailserver.close()
mailserver.logout()


 Though the sending and receiving are done but they are not as fanciful as we have thought, the text display of mesage is not as good as expected. May be we can use formatter and display it in a proper way, also we can build a GUI based program with the help of Tkinter, but those are kept for future project.
Now we will send mail in a fanciful way with the help of MIMEMultipart and MIMEText. The below program used it and for that sending of mail looks somehow proper - lets check it out

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
toaddress="someuser@gmail.com"
fromaddress="someuser@somesite.co.in"
text="Subject :Hello \n\t Just testing if it is working or not"
username="someuser"
password="*****"
msg=MIMEMultipart()
msg['From']=fromaddress
msg['To']=toaddress
msg['Subject']='How are you'
msg.attach(MIMEText(text)) #attaching the text to the message
server=smtplib.SMTP("mail.somesite.co.in:25")
server.ehlo()#establishes and comminicates with email server
server.starttls() #encryption technique

server.login(username,password)
try:
    server.sendmail(fromaddress,toaddress,msg.as_string())
    print "Successfully sent"
except:
    print "Not send "
server.quit()




Check out again for the graphical program for receiving and sending mail.  Also visit my site www.pythonbeginner.in for more information and materials.
       

Saturday, July 4, 2015

Python loops and conditionals

Like many other programming language Python also has loop controlling and conditional operators, they are not renamed to something else. We can iterate through any list or anything which are close relative list.
For loop for tuple or list:
Suppose we have a list a=[1,3,5,7,6], we want to iterate through the list and do some operation, we can do it by -
for i in a:
   i=i+1
   print i

The above snippet will iterate through the list and add one to each element, then print it. See the use of for loop in the program. The temporary variable i  iterate through the list a. So we don't have to know the number of element  in the list. We can use the same method for tuple. Or not? See it yourself as the tuples are not modifiable.
The same can be done in while loop.
i=0
While i<len(a):
   print i
   i=i +1

for and while loop works in a same way, i.e. iterate through a range or until some conditions are met. while loop is particularly useful when you need to write an infinite loop. Just write -
 while 1:
     print "looping continuously"
you can also write while True, too. Python has a boolean True and False keyword, so True is a viable option.

See the video for a better understanding.

The other important thing in python is conditional operator. if-elif-else can be used to see if certain condition or met and execute some statement if the condition is true.
It works like this  - 
if somecondition==true:
   execute something
elif seeothercondition==true:
   execute other statement
else :
   do this statement
You can see here how if else works in python.Let's see it by an example -

    value=raw_input("Enter a value") #To have user input through console
    value=int(value) #converting the value to an integer
    if value<5:
       print "You entered less than five"
    elif value>=5 and  value<10:
       print "You enter between 5 to 10"
    else:
       print "You entered beyond 10"

     

In the program we are checking the value of variable value and executing print statement. see the use of <,>,and,= statement in the program. The raw_input is used for prompt user to enter a value.You can use while 1: to loop forever through the program.



Thursday, June 25, 2015

Hello World with Python

Creating programs to print 'hello world' is a general concept, so I will start with that. Unlike any language where you have to call library to print the statement, Python has nothing Luke that.
So, for 'hello world' program -
If you are in Linux -
1. Open terminal and type Python.
         $python
2. Then just write print "hello world"
        >>print "hello world "
3. It will show the output "hello world"
For windows it is even more simpler,
Open the Python idle and type the above said statement. The out put will be the same.
But we need something more than "hello world" !
Open the terminal and write Python again. Write:  >>5+4
>>9
You can multiply,divide and do all the basic operations on the Python console.
You can also have variables.
>>a=5
>>b=4
>>c=a+b
>>9
You can see the output of c. The program is simply assign values to a and b variables and their addition in variable c. Python is smart enough to guess the  types of variables by itself.

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...