Some Very Basic Python

Hello readers,

Rather than trying to wow you with some mega complicated code snippets; which you might not understand, and I probably couldn’t really explain, I figured maybe on occasion I’d throw out some very basic programming to encourage some interest.

Python is a scripting language, and with a simple interpreter it can do some really useful stuff.

To grab an interpreter and install python you should visit python.org or if you are on Linux you can check to see which version of python you have installed via command line by typing: python –version .

For the purpose of this tutorial I was using Geany on Linux Mint 18 and python 2.7 as well as Ninja IDE (after I found it and discovered that I liked it.)

First things first, remember to save whatever python code you start scripting with the .py extension. All languages have specific extensions that denote which type of document they are and python is no exception.

Some Basics

i = 1000
while i >=1:
print(i)
i = i – 1
print (“counting”)

The above script counts forward to 1000 and says counting between each number. In this case we are telling the compiler that i should equal 1000, and that while i is less than or equal to 1, it should count forward while printing the value as well as the word counting. The syntax here is simple enough, an equals sign means equals by itself, a > means less than, while a < means greater than. The semicolon declares the while statement but could also declare an if statement, or an else statement.

That all seems confusing but you’ll get a better understanding of it as we go.

def countdown():
i=5
while i > 0:
yield i
i -= 1

for i in countdown():
print(i)

In this case we are counting down instead of up. We’ve removed the word counting from our code and now it’s only counting down from 5. The yield command is important here as without it the countdown would continue forever. (Unless we stop it by pressing control c.)

Indentation is important but the editor will chide you into correcting it.

The python standard libraries are available online, by version. There is a drop down box on this page that displays all of the different versions.

If you found this article compelling enough go check out sololearn.com and before you know it you’ll have dozen or even hundreds of example scripts to tinker with. This was just after a few days of playing with what they teach.

Screenshot from 2016-09-06 19-37-56

 

I not only am not stopping anytime soon, I’m just getting started. Maybe you are too?

*Collected from around internet a neat code snippet (I didn’t write it but it worked in python 2.7)

Port Scanner

#!/usr/bin/env python
import socket
import subprocess
import sys
from datetime import datetime

# Clear the screen
subprocess.call(‘clear’, shell=True)

# Ask for input
remoteServer    = raw_input(“Enter a remote host to scan: “)
remoteServerIP  = socket.gethostbyname(remoteServer)

# Print a nice banner with information on which host we are about to scan
print “-” * 60
print “Please wait, scanning remote host”, remoteServerIP
print “-” * 60

# Check what time the scan started
t1 = datetime.now()

# Using the range function to specify ports (here it will scans all ports between 1 and 1024)

# We also put in some error handling for catching errors

try:
for port in range(1,1025):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print “Port {}:      Open”.format(port)
sock.close()

except KeyboardInterrupt:
print “You pressed Ctrl+C”
sys.exit()

except socket.gaierror:
print ‘Hostname could not be resolved. Exiting’
sys.exit()

except socket.error:
print “Couldn’t connect to server”
sys.exit()

# Checking the time again
t2 = datetime.now()

# Calculates the difference of time, to see how long it took to run the script
total =  t2 – t1

# Printing the information to screen
print ‘Scanning Completed in: ‘, total


 

Spread the love

81 thoughts on “Some Very Basic Python”

  1. I like what you guys are up too. Such intelligent work and reporting! Keep up the excellent works guys I have incorporated you guys to my blogroll. I think it will improve the value of my website :)

  2. I was just seeking this info for a while. After six hours of continuous Googleing, finally I got it in your web site. I wonder what is the lack of Google strategy that don’t rank this kind of informative sites in top of the list. Usually the top sites are full of garbage.

  3. Hello there, I discovered your web site by the use of Google whilst looking for a comparable topic, your website came up, it appears to be like great. I’ve bookmarked it in my google bookmarks.

  4. Pretty section of content. I just stumbled upon your website and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently quickly.

  5. I’m extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it is rare to see a great blog like this one today..

  6. My spouse and i have been quite lucky that Ervin managed to conclude his reports from your precious recommendations he discovered from your web page. It’s not at all simplistic just to be giving out techniques many people have been making money from. We really do understand we’ve got the blog owner to appreciate for this. The specific explanations you’ve made, the straightforward website menu, the relationships your site aid to promote – it’s mostly incredible, and it is making our son and our family recognize that that idea is awesome, and that’s exceedingly serious. Many thanks for everything!

  7. Thanks , I’ve just been looking for info about this subject for a long time and yours is the best I have discovered so far. However, what concerning the conclusion? Are you certain concerning the supply?

  8. Hi my loved one! I wish to say that this post is amazing, great written and come with approximately all vital infos. I¡¦d like to see extra posts like this .

  9. you’re in point of fact a just right webmaster. The web site loading speed is incredible. It seems that you’re doing any unique trick. Moreover, The contents are masterwork. you have done a fantastic process in this subject!

  10. Great deliveryIncredible pointsTouche. GreatOutstandingSolidSound arguments. Keep up the amazinggoodgreat effortworkspirit.

    http://www.hqtext.com/top-10-best-baby-crib-mattresses-reviews/

  11. fantastic publish, very informative. I’m wondering why the opposite specialists of this sector do not understand this. You should proceed your writing. I am confident, you’ve a great readers’ base already!

  12. You actually make it seem really easy together with your presentation but I find this matter to be actually one thing which I believe I would by no means understand. It kind of feels too complicated and very huge for me. I am having a look forward to your subsequent publish, I¡¦ll try to get the dangle of it!

  13. “Great Blogpost! Way cool! Some extremely valid points! I _appreciate you writing this post and also the rest of the website is also very good.”

    https://structuringtechniques.wordpress.com/2017/02/14/for-our-dutch-readers-interview-with-a-colleague-from-europe-regarding-easy-structuring-techniques-article-in-dutch-language/

  14. “Great Blogpost! Hello Admin! Thanks for this article, very good information, I will be_ forwarding this to some friends, if you’re ok with that. Greetings from Germany!”

    https://structuringtechniques.wordpress.com/2017/02/14/for-our-dutch-readers-interview-with-a-colleague-from-europe-regarding-easy-structuring-techniques-article-in-dutch-language/

  15. I have recently started a web site, the info you provide on this website has helped me tremendously. Thank you for all of your time & work.

    http://felonspace.com/index.php?do=/blog/42870/modern-pest-control-absolute-pest-control/

  16. HeyHowdyWhats upHi thereHeyaHiHey thereHello this is kindasomewhatkind of of off topic but I was wonderingwanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding knowledgeskillsexperienceknow-howexpertise so I wanted to get adviceguidance from someone with experience. Any help would be greatlyenormously appreciated!

    http://www.flashdrive-direct.com/audio-item-creation-create-high-high-quality-audio-products-now/

  17. I like what you guys are up too. Such smart work and reporting! Keep up the excellent works guys I have incorporated you guys to my blogroll. I think it will improve the value of my web site :)

  18. you’re really a excellent webmaster. The website loading speed is incredible. It sort of feels that you are doing any unique trick. Moreover, The contents are masterpiece. you have done a fantastic activity in this subject!

  19. whoah this blog is fantastic i love reading your articles. Keep up the great work! You know, a lot of people are hunting around for this information, you can aid them greatly.

    http://fredholmes63.edublogs.org/2017/03/02/tips-on-how-to-consider-pool-services/

  20. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! By the way, how can we communicate?

    http://www.mymakeclub.com/blog/view/84996/wood-patio-covers-is-it-a-thing-anyone-must-know

  21. Simply wish to say your article is as surprising. The clearness in your post is just spectacular and i can assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.

    http://www.bucksportnext.net/vanilla/discussion/630619/wall-tiles-looking-for-high-quality-advice-about-it-read-this

  22. This information is magnificent. I understand and respect your clear-cut points. I am impressed with your writing style and how well you express your thoughts.

    http://www.blah.com

  23. First offFirst of all I want toI would like to say greatawesometerrificsuperbwonderfulfantasticexcellent blog! I had a quick question thatin whichwhich I’d like to ask if you don’tif you do not mind. I was curiousinterested to knowto find out how you center yourself and clear your mindyour thoughtsyour head beforeprior to writing. I haveI’ve had a hard timea tough timea difficult timetroubledifficulty clearing my mindthoughts in getting my thoughtsideas outout there. I doI truly do enjoytake pleasure in writing but ithowever it just seems like the first 10 to 15 minutes areare generallyare usuallytend to be wastedlost justsimply just trying to figure out how to begin. Any suggestionsideasrecommendations or tipshints? ThanksKudosAppreciate itCheersThank youMany thanks!

    http://5productreviews.com

  24. Hello There. I found your blog using msn. This is a really well written article. I’ll make sure to bookmark it and come back to read more of your useful info. Thanks for the post. I’ll definitely comeback.

  25. It¡¦s in point of fact a great and useful piece of info. I am happy that you simply shared this useful information with us. Please keep us informed like this. Thanks for sharing.

  26. wonderful publish, very informative. I ponder why the opposite specialists of this sector don’t notice this. You should proceed your writing. I’m confident, you’ve a huge readers’ base already!

    http://eaamongolia.org/vanilla/discussion/254250/acquire-greater-knowledge-of-transporation-batteries-an-especially-important-topic

  27. You could definitely see your enthusiasm within the work you write. The world hopes for even more passionate writers like you who are not afraid to mention how they believe. Always go after your heart.

  28. Great website. Plenty of useful info here. I am sending it to several friends ans also sharing in delicious. And certainly, thanks for your effort!

    http://123delights.com/blog/view/336375/biological-pest-control-revealed-on-this-page

  29. It’s actually a cool and useful piece of info. I am glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing.

    http://riley27a.blogcu.com/poster-printing-software/31866814

Leave a Reply

Your email address will not be published. Required fields are marked *