print "Hello, CSE!"
a = 10
b = 5
print a, b
a, b = b, a
print a, b
No need to specify data types. Automatically recognises them
n = 10
s = "Department of CSE"
marks = [
90, 82, 99, 97
]
marksTuple = (
90, 82
)
regNos = {
95: "Siva",
116: "Vignesh",
85: "Sagar"
}
print type(n)
print type(s)
print type(marks)
print type(regNos)
testNo1 = raw_input()
testNo2 = raw_input()
print testNo1 + testNo2
raw_input
takes str arguments by default. Cast it to int when necessary.
testNo1 = int(raw_input())
testNo2 = int(raw_input())
print testNo1 + testNo2
#Subtraction, Multiplication -> One line comment
"""
Division, Modulo have the same -> Multiline comment
operators as that of other
languages like C
"""
testNo1 ** testNo2
There is also a complex data type.
c1 = 3 + 5j
c2 = 5 - 8j
print type(c1)
print c1 + c2
print c1 - c2
print c1 * c2
print c1 / c2
print c1 ** c2
Can you figure out how to do 10/3 in floating point?
s1 = "Hello"
s2 = "World" #can also be written as 'World'
print s1 + ", " + s2 + "!"
print len(s1)
print s1*3
Write a Python code to take in your name and CGPA as inputs and print "Welcome to Python, nameHere. Your CGPA is CGPAHere"
Welcome to Python, Siva. Your CGPA is 8.
Collection of elements. The elements can be of different data types.
l = [1, 2, 3]
To access list elements, use
print l[0]
Python strings are like a list of characters. So,
print s1[0] #Will give the first element
To add an element,
l.append(4)
print l
Slicing a list - the cool part
dept = "Department of CSE"
#Usage: list[startingIndex:endingIndex:increment]
print dept[4:8]
print dept[4:8:2]
#Tricks
print dept[5:len(dept)-1] #will print from 5th element to the end
print dept[:8] #print from the starting element to the 8th element
print dept[::-1] #print the list in the reverse order
#Finding an element
pos = dept.index("CSE")
print "The word CSE is present at " + str(pos) + "th position"
#Joining the elements of a list
joinExample = [
'1', '2', '3' #Be careful to use a list with str elements for join
]
print ",".join(joinExample)
sentence = "My name is Siva"
words = sentence.split() #or sentence.split(" ")
print words
Can you produce the following output using the list words
?
Siva is name My
Clue: Use join.
dictionary = {
1: "one",
2: "two",
3: "three"
}
print dictionary[1]
print dictionary.values()
print dictionary.keys()
Write a program that would get a number from a user between 20 and 30 and print it in words.
Example,
input -> 25
output -> twenty five
Clues:
words = {
1: "one"
4: "four"
}
n = 24 #example
print "twenty " + words[int(str(n)[1])]
The above solution is too dirty. Python is all about code beauty. Try and make it beautiful.
Python has no braces. Indentation is used instead.
Also, there is no switch.
if(True):
print "Hello"
else:
print "No"
a = 10
if(a == 1):
print "one"
elif(a == 2):
print "two"
else:
print "oops"
i = 10
while(i > 0):
print i
i -=1
#usage: range(start, end, increment)
for x in range(10):
print x
a = ["one", "two", "three"]
for x in a:
print x
#what's the difference?
for x in xrange(10):
print x
nos = [x for x in range(20)]
nos
even = [x for x in range(20) if x%2 == 0]
even
strange_odd = [x+1 for x in range(20) if x%2 == 0]
strange_odd
def area(side):
return side*side
def foo(side, length=2):
return (side*length)
print area(10)
trial2 = foo(2)
print trial2
#note the %i and %f
def tax(bill):
"""Adds 8% tax to a restaurant bill."""
bill *= 1.08
print "With tax: %f" % bill
return bill
def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print "With tip: %i" % bill
return bill
meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)
Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda".
They do not have return statements.
Python supports functional programming. Lambdas play a role here.
Especially useful when you want to pass a function as a variable.
def foo(x):
return x**x
f = foo(4)
print f
g = lambda l: l**l
print g(4)
def increment (n): return lambda x: x + n
sample = increment(2)
print sample(5)
print increment(2)(5)
nos = [1, 2, 3, 4, 5, 6]
print filter(lambda x: x%2 == 0, nos)
squares=[x**2 for x in range(1,11)]
print filter(lambda x: (x>=30)and(x<=70),squares)
Can you write a list-comprehension only equivalent of the above lambda?
#all class methods will have a self parameter. this is different from c++
class Fruit(object):
"""A class that makes various tasty fruits."""
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)
def is_edible(self):
if not self.poisonous:
print "Yep! I'm edible."
else:
print "Don't eat me! I am super poisonous."
lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()
class Triangle(object):
number_of_sides=3
def __init__(self,angle1,angle2,angle3):
self.angle1=angle1
self.angle2=angle2
self.__angle3=angle3
def check_angles(self):
sum=self.angle1+self.angle2+self.__angle3
if sum==180:
return True
else:
return False
class Equilateral(Triangle):
angle = 60
def __init__(self):
self.angle1 = self.angle
self.angle2 = self.angle
self.angle3 = self.angle
my_triangle=Triangle(45,60,60)
my_triangle=Equilateral()
print my_triangle.angle
print my_triangle.number_of_sides
print my_triangle.check_angles()
my_triangle=Triangle(45,60,75)
print my_triangle.check_angles()
print my_triangle.angle2
#Use double-underscore for private variable in the class definition
print my_triangle.__angle3
1
print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT
for i in range(2,6):
print bin(i)
print bin(i)[2:]
print int("111",2)
print int("0b111",2)