Fun with Python
2010-08-31Hey there fellow developers 😀 I have been working with Python lately(specifically Python3) and wanted to share some things I thought were pretty cool from an outsider’s(learning the language) perspective. I hope the following helps with getting to know this great language.. Enjoy
#construct a tuple using()
t=(1,2,3)
#contruct a list using []
lst= [1,2,4]
#iterate a string and print each character
for i in "This is a String":
print(i)
#getting the length of a string
print ("length is",len("12345"))
#test x is in a range
x=6
if(3< x <10 ):
print( "I am true")
else:
print( "I am false")
#test membership
if "2" in "1234":
print("I am in the string")
if int("2") in [1,2,3,4]:
print( "I am in the list")
#replication
print( "hithreetimes, "*3)
#using math class
import math
print(math.sqrt(4))
#print all methods
print(dir(math))
#named Tuples
import collections
Movie = collections.namedtuple("Movie","title rating")
collection =[Movie("Jaws", 4.0)]
collection.append(Movie("Toy Story", 5.0))
for movie in collection:
print("I watched {0} and gave it {1} stars".format(movie.title,movie.rating))
#sequence unpacking
head, *rest = [1,2,3,4,5]
print("head is {0} and rest is {1}".format(head,rest))
#passing and unpacking parameters
def fullname(f,m,l):
print("First Name ="+f)
print("Middle Name ="+m)
print("Last Name ="l)
fakenamelist =["Homer","J","Simpson"]
fullname(*fakenamelist)
#list comprehensions (print all odd numbers from 0 to 99)
print( [item for item in range(0,100) if item % 2])
#named parameters
def count_animals(number,*, animal="ducks"):
return "{0} {1}".format(number,animal)
print( count_animals(3,animal="cows"))
print( count_animals(3))
print(sorted([-1,2,-3],key=abs)) #same order
line = input("enter something.. ")
print("your line was " ,line)
I have been using python for web requests and recommend using the httplib2 library. It has a lot of really nice features.