Monday, June 6, 2016

A quick try except in python


Please use try/except for cross service or real time user input validation, its safer to throw exception rather failing the whole program

# Program to convert all given values into int

# Ex. of try except

for v in 1,2,10,'a',4,5,10,'v',"abc",1:
        try:
                print "Vint:",int(v)
        except ValueError as ex:

                print "{} cannot be converted to int: {}".format(v,ex)


Counting the vowels

There are many ways to count the vowels in python, here is one


# Program to count vowels in given sentence

count=0
vowels={'a':0,'e':0,'i':0,'o':0,'u':0}

print "Program to count vowels in given sentence"

sentence=raw_input('Enter sentence? ')

for i in sentence:
if i.lower() in vowels.keys():
count+=1
vowels[i.lower()]+=1

print "Vowel count:", count
print "Each vowel count"
for k,v in vowels.items():

print '\t',k,':',v