print('Hello!')
# This is a comment
'''
This is
a
multi-line
comment
'''
# 1. Strings:
print('This is a string')
print("This is a string too")
print('''This is a string three!''')
s = "\nThis is a str'ing"
print(s)
print(type(s))
# 2. Integers
i = 5
print(i)
print(type(i))
# 3. Floats
f = 4.3
print(f)
print(type(f))
# 4. Complex Numbers
c1 = 2 + 3j
c2 = complex(4,5)
print(c1)
print(c2)
print(type(c1), type(c2))
print('\n')
print(c1.real)
print(c1.imag)
# 5. Boolean
b = True
c = False
print(b)
print(c)
print(type(b))
print(type(c))
# raw_input() #Python2
ip = input('Enter an integer:')
print(type(ip))
print(int(ip), type(int(ip)))
print(float(ip), type(float(ip)))
ip2 = int(input('Enter an integer:'))
print(ip2, type(ip2))
ip3 = float(input('Enter a number:'))
print(ip3, type(ip3))
i = 10
print(i, type(i))
print(str(i), type(str(i)))
f = 0.5
print(f, type(f))
print(str(f), type(str(f)))
# Implicit type-conversions
b1 = True
b2 = False
print(b1 + b2 + b1 + b1)
print(bool(0))
print(bool(100))
print(bool(-100))
# Some ways to print
a = 5
b = 6
print('This',a,'is a',b)
print('This {} is a {}'.format(a , b))
print('This %d is a %d' %(a,b))
i = int(input('Enter an integer:'))
f = float(input('Enter a float:'))
s = i + f
print(s, type(s))
# 1. Arithmetic Operators
n1 = 10
n2 = 3
print('Add', n1 + n2)
print('Subtract',n1 - n2)
print('Multiply',n1 * n2)
print('Division',n1 / n2)
print('Remainder (Division)', n1 % n2)
print('Floor Division',n1 // n2)
print('\n')
print('Exponentiation',n1 ** 2)
print('Exponentiation',n1 ** 0.5)
print('Exponentiation',n1 ** -2)
# 2. Assignment Operators
n3 = 20
n4 = 6
n3, n4 = 20, 6
print(n3, n4)
n3 += n4 # Equivalent to n3 = n3 + n4
print(n3)
n3 -= n4 # Equivalent to n3 = n3 - n4
print(n3)
n3 *= n4 # Equivalent to n3 = n3 * n4
print(n3)
n3 /= n4 # Equivalent to n3 = n3 / n4
print(n3)
n3 %= n4 # Equivalent to n3 = n3 % n4
print(n3)
n3 = 20
n3 //= n4 # Equivalent to n3 = n3 // n4
print(n3)
n3 **= n4 # Equivalent to n3 = n3 ** n4
print(n3)
# 3. Relational Operators
n1 = 10
n2 = 5
print(n1 == n2)
print(n1 != n2)
print(n1 > n2)
print(n1 < n2)
print(n1 >= n2)
print(n1 <= n2)
# 4. Logical Operators
b1 = True
b2 = False
print(not b1)
print(b1 and b2)
print(b1 or b2)
print(0 and 1)
print(0 or 1)
# 5. Bitwise Operators
i1 = 15 # 1111
i2 = 6 # 0110
print(i1 & i2) # and
print(i1 | i2) # or
print(i1 ^ i2) # xor
print(~i1) # one's complement
print(i1 << 2) # left shift
print(i1 >> 2) # right shift
# 6. Membership Operators
print('str' in 'string')
print('ni' not in 'convenient')
# 7. Identity Operators
string1 = 'abcd'
string2 = 'efgh'
print(string1 is string2)
# General structure
# if condition1:
# statement(s)
# elif condition2:
# statement(s)
# elif condition3:
# statement(s)
# ...
# elif conditionN:
# statement(s)
# else:
# statement(s)
a1 = 5
a2 = 10
if a1 > a2:
print('a1 is greater')
elif a1 < a2:
print('a2 is greater')
elif False:
print('This statement will never be reached')
else:
print('a1 and a2 are equal')
x = int(input('Input an integer:'))
if x%2:
print(x,'is odd')
else:
print(x, 'is eve')
a1 = 10
a2 = 20
a3 = 30
if a1 == 10:
if a2 == 20:
if a3 == 30:
print('a1 == 10, a2 == 20, a3 == 30')
else:
print('a1 == 10, a2 == 20, a3 != 30')
else:
print('a1 == 10, a2 != 20, a3 != 30')
else:
print('a1 != 10, a2 != 20, a3 != 30')
# 1. for loops
# General Structure
# for variable in iterator:
# statement(s)
# range() with 1 argument:
# range(t) : goes from 0 to t-1
for i in range(6): # [0, 1, 2, 3, 4, 5]
print(i)
print('')
for i in 'abc':
print(i)
# range with 2 arguments:
# range(start, end)
for i in range(0,5+1):
print(i)
print('')
for i in range(5,10):
print(i)
# range with 3 arguments
# range(start, end, steps)
for i in range(0,20,2):
print(i)
# Loop in the opposite step direction
for i in range(10,0,-2):
print(i)
# Iterate over strings
str1 = 'abcdefg'
for i in str1:
print(i)
# Iterate explicitly over strings:
str1 = 'abcdefg'
for i in range(len(str1)):
print(i, str1[i])
# 2. while loops
# General Structure
# while condition:
# statement(s)
i = 0
while i < 10:
print(i)
i += 2
# break: break out of the inner-most loop (not the if-else block!)
i = 0
while 1:
i += 1
if i > 10:
break
print(i)
# continue: go to the start of the inner-most loop (not if-else blocks)
i = 0
while 1:
i += 1
if i > 10:
break
elif i <= 10:
continue
print('something')
print(i)
# General Structure
# def functionName(argument1, argument2, argumentN):
# statement(s)
# return return1, return2, returnN
# You can also return nothing.
# functions can accept arguments, and can return values
def even(n):
if n % 2 == 0:
is_even = True
else:
is_even = False
return is_even
n1 = 4
print(even(n1))
n2 = 7
print(even(n2))
def even(n):
return n % 2 == 0
n1 = 20
print(even(n1))
n2 = 13
print(even(n2))
# functions can return multiple values
def mad_calculator(n1, n2):
return n1+n2, n1-n2, n1*n2, n1/n2, n1%n2, n1//n2, n1**n2
a1 = 10
a2 = 5
print(mad_calculator(a1, a2))
a3 = 20
a4 = 4
ret1, ret2, ret3, ret4, ret5, ret6, ret7 = mad_calculator(a3, a4)
print(ret1, ret2, ret3, ret4, ret5, ret6, ret7)
# You can provide default values to the parameters of a function
def power(x, p=1):
return x**p
print(power(x=10))
print(power(p=10, x=3))
# Default values MUST be filled from the right
def power(x=1, p):
return x**p
print(power(10, 3))
# General Structure
# class className:
# def function1():
# statement(s)
# def function2():
# statement(s)
# def functionN():
# statement(s)
# className objectName
# objectName.function1()
# # public members
# def functionName():
# statement(s)
# # private members
# def __name__():
# statements(s)
# Constructor:
# def __init__():
# statements(s)
class rectangle:
def __init__(selfabc, length=0, width=0):
selfabc.length = length
selfabc.width = width
def area(self123):
return self123.length * self123.width
var_rect = rectangle(length=2, width=3)
print(var_rect.area())
var_rect = rectangle()
print(var_rect.area())
class cuboid(rectangle):
def __init__(self, length=0, width=0, height=0):
rectangle.__init__(self, length=length, width=width)
self.height = height
def volume(self):
return self.height*self.area()
var_cuboid = cuboid(length=2, width=3, height=4)
print(var_cuboid.volume())
var_cuboid2 = cuboid(length=5, width=6, height=7)
print(var_cuboid2.volume())
# lists store data of any type
l1 = [2, 3.5, 'apple', False]
print(l1)
print(l1[0])
print(l1[2])
# can create empty lists, can append elements to a list
l1 = []
print(l1)
l1.append('Five')
print(l1)
# '+' for lists defined as concatenation
l1 = ['abc', 'def']
l2 = ['abc2', 'def2']
print(l1 + l2)
l3 = [4,5]
l4 = [6,7]
print(l3 + l4)
# can append lists to lists
l1 = ['abc', 'def']
l2 = [l1, 'Six']
print(l2)
# remove the first occurance of an element
l1 = [2, 3.5, 'apple', False, 'apple']
l1.remove('apple')
print(l1)
# insert element in a specific position
l1 = [2, 3.5, False, 'apple']
l1.insert(2, 'apple')
print(l1)
# delete last element
l1 = [2, 3.5, 'apple', False, 'Five']
x = l1.pop()
print(x)
print(l1)
# all possible operations on a list
print(dir(l1))
l1 = [2, 3.5, 'apple', False, 'Five']
print(len(l1))
l1 = [2, 3.5, 'apple', False, 'Five']
print(l1.index('apple'))
l1 = [2, 3.5, 'apple', False, 'apple', 'Five', 'apple']
print(l1)
print(l1.count('apple'))
l3 = [20, 3.5, 14, 5, 1]
print(l3)
l3.sort()
print(l3)
l3.reverse()
print(l3)
l1 = [1, 2, 3, 4]
l2 = l1
l2.append(5)
print(l2)
print(l1)
print('\n')
l3 = list(l1)
l3.append(6)
print(l3)
print(l1)
t1 = (2, 3, 'banana')
print(t1)
# access a particular element
print(t1[0])
# create empty tuples
t2 = ()
print(t2)
# cannot modify tuples
t1[0] = 1
s1 = set({1, 2, 2, 3, 4})
print(s1)
s1 = set({1, 2, 2, 3, 'abc', 4.5, 2.0})
print(s1)
# Sets are useful in getting only the unique elements
l1 = [2, 5, 1, 9, 2, 4, 1, 5, 9, 2, 2, 2, 9, 1]
l2 = list(set(l1))
print(l2)
# key:value - maps key to value
roll = {'harry':1, 'ron':2, 'hermione':3, 'hermione':'top student'}
print(roll['harry'])
print(roll['ron'])
print(roll['hermione'])
# both kets and values can be of any data type
names = {1: 'harry', 2:'ron', 'hermione':3}
print(names[1])
print(names[2])
print(names['hermione'])
roll = {'harry':1, 'ron':2, 'hermione':3}
print(len(roll))
print(roll.keys())
k1, k2, k3 = roll.keys()
print(k1, k2, k3)
print(roll.values())
# Iterate over Lists
l1 = [1, 2, 3, 4, 5]
for x in l1:
print(x)
l1 = [1, 2, 3, 4, 5]
for x in range(len(l1)):
print(x, l1[x])
l1 = [1, 2, 3, 'cat', 5]
for x, y in enumerate(l1):
print(x, y)
# Tuples
t1 = ('a1', 'a2', 'a3', 'a4')
for x in t1:
print(x)
# Dictionaries
d1 = {'key1': 'val1', 'key2':'val2', 'key3': 'val3'}
print(d1.items())
for k, v in d1.items():
print(k, v)
# Similar way of iterating for lists
l1 = ['a1', 'a2', 'a3']
for idx, val in enumerate(l1):
print(idx, val)
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']
for q, a in zip(l1, l2):
print(q, a)
print('')
for i, (q, a) in enumerate(zip(l1, l2)):
print(i, q, a)
# List comprehensions
w_letters = []
for letter in 'aword':
w_letters.append(letter)
print(w_letters)
h_letters = [ letter for letter in 'aword' ]
print( h_letters)
# General structure
# [expression for item in list if condition]
h_letters = [ letter for letter in 'aword' if letter != 'o']
print(h_letters)
[2*i for i in range(10) if i != 5]
f1 = open('afile', 'w')
f1.write('Line 1\n')
f1.write('Line 2\n')
f1.close()
f1 = open('afile', 'r')
c1 = f1.readline()
print(c1)
f1.close()
f1 = open('afile', 'r')
c1 = f1.read()
print(c1)
f1.close()
f1 = open('afile', 'r')
for c1 in f1:
print(c1)
f1.close()
s1 = 'abcd'
s2 = 'defg'
print(s1)
print(s2)
print(s1+s2)
print(s1.upper())
print(len(s1))
s3 = ' this is a sentence '
print(s3)
print(s3.strip())
l1 = (s3.strip()).split() # other arguments for split
print(l1)
s4 = ' '.join(l1)
print(s4)
import re
s1 = 'this is a sentence'
print(re.findall('sentence', s1))
print(re.sub('a sentence', 'not a sentence??', s1))