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

Monday, 19 September 2016

Datetime module in python: Example with Explanation

Datetime module is python has the classes and functions for manipulating date and time.


To manipulate date and time operations in python you have to import datetime module.


"import datetime" 


if you want to know the current date and time the code would be


"get = datetime.datetime.now()"





And the output is:



If you want to extract the information from date and time, then you can do it like


current_year = get.year
current_month = get.month


Example program;
Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.




The output is:




The github reference:


GitHub Code


https://gist.github.com/pinkpretty/577f188fa8bff563ed4d4802efebc5d6/edit





















 
 




 



Friday, 16 September 2016

If__name__ = '__main__' main method


When I started python as a beginner, the first thing which was confusing me is If__name__ = “__main__”.  It is mainly used to check whether the module is imported or not.

Usually the code inside ‘If’ block will be executed only, if it ran directly.

Let’s take a closer look at this.









If python interpreter is running the module (m1 )as a main program it sets the __name__ variable to the value __main__. So thus printing the __name__ variable will produce output “__main__”.

Let’s consider we import the module m1 to another module m2.
#m2.py
Import m1

Print m1.__name__
Now if we are printing the __name__ variable which will provide module name ‘m1’ as output.

By giving if __name __ == “__main__” statement, you can check whether your program is being run directly or imported by someone else.