x = 5
print(x)
print(type(x))
y = 2.6
print(type(y))
a = 1.5 + 0.5j
print(a.real, a.imag)
print(type(a))
print(x+1)
print(a+1)
print(x*2)
print(a*2)
print(x/2)
print(x**2)
x+=1
print(x)
x *= 2
print(x)
print(x/5)
remainder = 11 % 3
print(remainder)
print(y, y+1, y-2, y*2, y**2, y/5)
b = complex(2.5,1.5)
print(a, b, a+b, a-b, a/b)
print(a, a.conjugate(), abs(a), pow(a,2))
userInput = raw_input('Enter an integer - ')
print(userInput)
print(type(userInput))
t = True
f = False
print(type(t),type(f))
print(t and f)
print(t and t)
print(t or f)
print(f or f)
print(not f)
print(t != f)
print(t != t)
x, y = 4, 8
print(x == 4 and y == 8)
print(x == 2)
print(x < 4)
print(y > 4)
print(x!=4)
hello = 'hello'
world = 'world'
print(hello, world)
print(len(hello), len(world))
hw = hello + ' ' + world
print(hw)
hw12 = '%s %s %d' % (hello, world, 12)
print(hw12)
h = 'hello world!'
print(h.capitalize())
h = h.upper()
print(h)
h = h.lower()
print(h)
str1 = h
print(str1)
print(str1.count('h'))
print(str1[::-1])
print(str1.endswith('!'))
print(str1[1:len(str1)])
print(str1.index('l'))
print(h.rjust(7))
print(h.ljust(7))
print(h[:3])
print(h[:-1])
print(h[3:])
print(h[-1:])
print(h.center(7))
print(h.replace('l','imb'))
print(' world is good'.strip()) # Strip leading and trailing whitespace
print(' world is good'.split())
print(' world is good'.split("i"))
sS = ' world is good '
print(len(sS))
newS = sS.strip()
print(newS, len(newS))
spS = newS.split()
print(spS, spS[0])
print(type(spS))
name = 'Bikash'
age = 32
print(('%s is %d year\'s old') % (name, age))
if x is not 3:
print('not 3')
if x is 4:
print('Hmm')
name = 'Bikash'
age = 32
if name == 'Bikash' and age == 32:
print('%s is %d year\'s old' % (name, age))
else:
print('Shit!')
if name in ['Bikash', 'Akash']:
print('%s' % name)
if name == 'Bikash' and age == 31:
print('Good')
elif age == 33:
print('Average')
else:
print('Bad')
mystring = 'Bikash'
myfloat = 10.00
myint = 20
# testing code
if mystring != "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)
primes = [2,3,5,7];
for prime in primes:
print(prime)
for x in range(5):
print(x)
for x in range(3,4):
print(x)
for x in range(3,12,2):
print(x)
for i in range(10,0,-1): #decreasing loop
print(i)
count = 0
while count < 5:
print(count)
count += 1
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
else:
continue
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
# Prints out 1,2,3,4
for i in range(1, 10):
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition")
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
numbers = [
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470,
743, 527
]
print(len(numbers))
for x in numbers:
print(x)
if x%2 == 0:
print(x)
elif x == 237:
break
else:
continue
else:
print("It is done")
list1 = [1,2,3,4]
print(list1)
print(list1[0], list1[1], list1[2], list1[3])
print(type(list1))
print(list1[-1])
print(list1[-4])
print(list1[-2])
list1[3] = 'bikash'
print(list1)
list1[4] = 'santra'
list1.append('santra')
print(list1)
print(list1[2:4])
last = list1.pop()
print(last, list1)
nums = list(range(0,10)) # last exclusive
print(nums)
print(nums[2:6]) # last exclusive
print(nums[3:])
print(nums[:3])
print(nums[:])
print(nums[-1])
print(nums[:-1]) # last exclusive
print(nums[:-2])
nums[2:4] = [11,12]
print(nums[2:8:2])
print(nums)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7]
allNum = even + odd
print(allNum, type(allNum))
print(even*3)
mlist = [1, 2, 3]
print('A list is %s %s' % (mlist,mlist))
for i in range(100):
print(2**i)
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
for animal in enumerate(animals):
print(animal)
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx+1, animal))
nums = list(range(5))
print(nums)
squares = []
for x in nums:
squares.append(x**2)
print(squares)
print(len(squares))
squares = [x**2 for x in nums] # Easy Approach
print(squares)
even_squares = [x**2 for x in nums if x % 2 == 0]
print(even_squares)
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
proper_nouns = ['Bikash', 'Santra']
# write your code here
for i in range(2,10):
numbers.append(i)
strings.append(raw_input('Enter a string - '))
# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s %s" % (proper_nouns[0], proper_nouns[1]))
d = {'cat': 'cute', 'rat': 'bustard', 'frog': 'messy'}
print(d['cat'])
print(d)
for ind, key in enumerate(d):
print('#%d: %s' % (ind,key))
for key in d:
print(d[key])
print('cat' in d)
d['fish'] = 'wet'
print(d['fish'])
print(d.get('monkey'))
print(d.get('monkey', 'N/A')) # Default if not found
print(d.get('fish'))
print(d.get('fish', 'N/A')) # Default if not found
d['rat'] = 'funny'
del d[('fish')]
print(d.get('fish','N/A'))
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print(phonebook)
del phonebook["John"]
print(phonebook)
phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
print(type(phonebook))
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal, legs))
nums = list(range(0, 10))
print(nums)
even_num_to_square = {x: x**2 for x in nums if x % 2 == 0}
print(even_num_to_square) # Search how it works, sequence is not maintained
animals = {'cats', 'dogs'}
print(animals)
animals = set(['cats', 'dogs']) # Alternate declairation
print(animals)
print('cats' in animals)
print('rats' in animals)
animals.add('rats')
print('rats' in animals)
print(len(animals))
animals.remove('rats')
print(len(animals))
animals = {'cat','dog','rat'}
for idx, animal in enumerate(animals):
print('#%d: %s' % (idx+1, animal))
import math
nums = {int(math.sqrt(x)) for x in range(30)}
print(nums)
d = {(x, x+1): x for x in range(10)}
t = (2,3)
print (type(d))
print(type(t))
print(d)
print(list(t))
d[t] = 1000
print(d)
for ind1,data in enumerate(d):
print('#%d: %s' % (ind1,data))
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print(sign(x))
def hello(name, loud=False):
if loud:
print('HELLO, %s!' % name.upper())
else:
print('Hello, %s' % name)
hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True) # Prints "HELLO, FRED!"
# Iterative version
def factorial(x):
fact = 1
for i in range(1,x+1):
fact *= i
return fact
print(factorial(3))
# Recursive Function
def fact(n):
if n==0:
return(1)
else:
return(n*fact(n-1))
print(fact(5))
# Modify this function to return a list of strings as defined above
def list_benefits():
return ['More','More-More', 'Greater']
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
return benefit + ' effort is required.'
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
name_the_benefits_of_functions()
class Greeter(object):
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=False):
if loud:
print('HELLO, %s!' % self.name.upper())
else:
print('Hello, %s' % self.name)
g = Greeter('Fred') # Construct an instance of the Greeter class
g.greet() # Call an instance method; prints "Hello, Fred"
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
class school(object):
def __init__(self,name):
self.name = name
def candidate(self, x):
if x==5000:
print('%s is paid %d rupees' % (self.name,x))
else:
print('%s is paid %d rupees' % (self.name,x))
stu = school('Bikash')
stu.candidate(5000)
class school():
def candidate(self):
print('is paid rupees')
stu = school()
stu.candidate()
# define the Vehicle class
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
return desc_str
# your code goes here
car1 = Vehicle()
car2 = Vehicle()
car1.name = 'Benz'
car1.color = 'Red'
car2.name = 'BMW'
car2.color = 'Silver'
# test code
print(car1.description())
print(car2.description())
%whos
a) https://docs.python.org/2.7/tutorial/index.html
b) https://www.scipy-lectures.org/intro/language/python_language.html
c) https://github.com/kuleshov/cs228-material/blob/master/tutorials/python/cs228-python-tutorial.ipynb
d) https://www.learnpython.org/
Click here to download the source code of this tutorial.