Basic Python

data types-

  • Integer(int) – Whole numbers 2, 200, 350
  • Floating Point(float) – Numbers with decimals 3.5, 5.6, 200.0
  • Strings(str) – Ordered sequence of characters “hello” ‘hi’ “240”
  • Lists(list) – Ordered sequence of objects [“hi”,123,4.0]
  • Dictionaries(dict) – Unordered key value pairs {“key1″:”value1”, “key2″:”value2”}
  • Tuples(tup) – Ordered immutable sequence of objects (“hi”,123,4.0)
  • Sets(set) – Unordered collection of unique objects : {“a”,”b”}
  • Booleans(bool) – Logical value indicating true or false.

Python is dynamically typed, so you do not need to mention the data type while doing variable assignment.

strings –

>mystring = "Hello World"
>mystring[0]
'H'
>mystring[8]
'r'
>mystring[-2]
'l'
#Slicing
>mystring = "abcdefghijk"
>mystring
'abcdefghijk'
>mystring[:3]
'abc'
>mystring[3:6]
'def'
>mystring[::2]
'acegik'
>mystring[2:7:2]
'ceg'
>mystring[::-1]
'kjihgfedcba'

#String Concatenation
>a="Hello"
>b="World"
>a+" "+b
Hello World

#String Formatting
>print('The {} {} in the {}'.format('Sun','rises','East.'))
The Sun rises in the East.

>name = "Sam"
>age = 30
>print(f'{name} is {age} years old.')

lists –

>mylist = [1, 2, 3]
>mylist[0]
1
>mylist[1:]
[2,3]
>mylist2 = [4,5]
>mylist + mylist2
[1,2,3,4,5]
#mutable
mylist[0]=100
>mylist
[100,2,3]
>mylist.append(200)
[100,2,3,200]
>mylist.pop()
200
>mylist
[100,2,3]
>mylist.pop(0)
100
>mylist
[2,3]

#Sorting
>list1 = ['d','b','c','a']
>list1.sort()
>list1
>['a','b','c','d']

dictionaries –

#Unordered Key value pairs
>prices = {'apples':2.99,'milk':5.00}
>prices['apple']
2.99
>d = {'k1':123,'k2':[0,1,2],'k3':100}
>d['k2']
[0,1,2]
>d.keys()
dict_keys(['k1','k2','k3'])

tuples-

Tuples are similar to lists except that they are immutable and once created cannot be changed.

>t = (1,2,3)
>type(t)
tuple
>t1 = ('one', 2)
>t1[0]
'one'
>t1[-1]
2
>t2 = ('a','a','b')
>t2.count('a')
2
>t2.index('a')
0 

sets –

#Sets are unordered collections of unique elements.
>myset = set()
>myset.add(1)
>myset
{1}
>myset.add(2)
{1, 2}
>mylist = [1,1,1,1,2,2,2,3,3,3]
>set(mylist)
{1, 2, 3}

booleans –

#To convey true or false
>True
True
>False
False
>type(False)
bool
>1 > 2 
False
>1==1
True

File I/O

>myfile = open('myfile.txt')
>myfile.read()
'Hello World'
>myfile.read()
''
>myfile.seek(0)
0
>myfile2.readlines()
['line1','line2']
>myfile2.close()
>with open('myfile.txt') as new_txt_file:
     contents = new_text_file.read()
#no need to close the file now

comparison operators –

==(Checks if two operands are equal)
!=(Checks if two operands are not equal)
> (Checks if one operand is greater than the second operand)
< (Checks if one operand is smaller than the second operand)
>=(Checks if one operand is greater than or equal to the second operand)
<=(Checks if one operand is smaller than or equal to the second operand)

PYTHON STATEMENTS –

if elif and else statements –

if condition: 
   <statement>
elif condition:
   <statement>
else condition:
   <statement>

for loop –

my_iterable = [1, 2, 3]
for item in my_iterable:
   print(item)
>1
>2
>3
for x in 'Hello'
   print(x)
>H
>e
>l
>l
>o

my_list1 = [(1,2,3),(4,5,6),(7,8,9)]
for a,b,c in my_list1
    print(b)
>2
>5
>8

d = {'a':1,'b':2,'c':3}
for value in d.values():
   print(value)
>1
>2
>3

Useful operators –

list1 = [1,2,3]
list2 = ['a','b','c']
for item in zip(list1,list2)
    print(item)
>(1,'a')
>(2,'b')
>(3,'c')

'a' in 'a world'
>True

result = input('What is your age ?')

*args and **kwargs –

#you can provide any number of arguments and it will create a tuple from the arguments and process it.
def myfunc1(*args):
   print(args)
>myfunc1(4,10,15,20)
(4,10,15,20)

#you can provide a dictionary and use that to process in the function, you do not need to specify anything about that dictionary while creating function.
def myfunc2(**kwargs):
    print(kwargs)
>myfunc2(key1='value1', key2 = 'value2')
{'key1':'value1', 'key2':'value2'}

#You can also use the tuple and dictionary together.
def myfunc3(*args, **kwargs):
    print(args)
    print(kwargs)
>myfunc3(2,3,4,key1='value1',key2='value2')
(2,3,4)
{'key1':'value1','key2':'value2'}