Featured

Learn Python – Quick notes

September 17, 2014 by Sarath DR in Featured, Internet, Web Development with 0 Comments

The following article will be helpful for all beginners of python language. This also a quick reference note for all keywords, lists, data types and classes. Learn Python quickly icon wink Learn Python   Quick notes

1. Print something

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
print "Hello World"
 
x = 7 
print x 
 
str  = "Technology World"
print str
 
# Print float value - adjust for 2 decimal places
print("%.2f" % sum )
 
fruit = "Apple"
print "A for  %s." % (fruit)

2. Console Input

1
2
3
 
name = raw_input("What is your name?")
print name

3. Boolean variables

1
2
x = True
y = False

4. Comment Code

 
# Single line
 
""" 
Multiple lines 
comments in Python.
 
Use triple quotes
 
"""

5. Operands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
# Add
c = a + b
 
# Subtract
c = a  - b
 
# Multiply
c = a * b
 
# Divide 
c = a / b
 
# Mod 
c = a % b 
 
# Exponent - a to the power b
c  = a ** b

6. Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
# Prints 3rd letter of a string 
print "TECH"[2]
 
# Length of a string  - Prints 4
print len("TECH")
 
#  To Lower - Prints tech
print "TECH".lower()
 
#  To Upper - Prints TECH
print "tech".upper()
 
# To get string value
val = 5.33 
# prints "5.33"
print str(val)
 
# Concatenate two strings 
print "Technology " + "and" + " Digital media"
 
print "Total value = " + str(33.33)
 
temp_string = "digital"
 
# The first three characters of temp_string
temp_string[:3]

7. Lists

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
 
# List of numbers 
numbers = [11, 10, 1, 2, 3, 4 ]
 
# Printing second element 
print numbers[1]
 
# Sort list
numbers.sort()
 
# Sum of numbers 
print sum(numbers)
 
# List of strings 
fruits = ["orange", "apple", "mango", "plum", "peach" ]
 
# To get the length of the list 
print len(fruits)
 
# Printing second element 
print fruits[1]
 
# Adding another element to the list 
fruits.append("banana")
 
# Slice list 
# [start:end:stride]
 
# Prints [1, 3]
print numbers[2:6:2]
 
# Reverse list 
print numbers[::-1]
 
# The first and second elements
fruits[0:2]  
 
# Third and fourth elements
fruits[2:4]              
 
# The last two items 
fruits[4:6]              
 
# Get list index
print fruits.index("mango")
 
# Replace an element in an index 
fruits.insert(3, "strawberry" )
 
# Remove an item 
fruits.remove('mango')
 
# Join two lists 
list1 = [1,2,4,5]
list2 = [6,7,8,9]
 
new_list = list1+list2
 
# join string array as string 
print  " " . join(fruits)
 
# Build list 
even_numbers = [i for i in range(100) if i % 2 == 0]

8. Dictionary

1
2
3
4
5
6
7
8
9
10
 
fruits_count = {'apple': 34, 'orange': 55, 'mango': 6}
print fruits_count['apple']
 
temp = { "tech": "Technology and Digital media"}
 
# Dump dictionary 
fruits_count.items()
fruits_count.keys()
fruits_count.values()

9. Loops

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 
# For loop 
for num in numbers:
    print num
 
for fruit in fruits:
    print fruit
 
# Looping through a string
sentence = "I love technology and digital media"
 
# Print the letter in a string if it is equal to "t"
for l in sentence:
    if l == "t":
        print l
 
# With dictionaries 
fruits_count = {'apple': 34, 'orange': 55, 'mango': 6}
for key in fruits_count:
    print key + " " + fruits_count[key]
 
# For loop to iterate with index and element 
for index, element in enumerate(fruits_count):
    print index+1, element
 
# For loop for multiple arrays
list_x = [1,2,4,5,9]
list_y = [6,7,8,9]
 
for x, y in zip(list_x, list_y):
     if  x == y :
         print x
     else:
        print y
else: 
  print "End of loop"
 
 
 
# While loop
i = 0  
while i <= 9:
    print i
    i += 1
# With break 
while i <= 9:
    print i
    if i == 6 
       break
    i += 1
 
# With else  
while i <= 9:
    print i
    if i == 6 
       break
    i += 1
else:
  print "Exit loop"

10. Comparators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
# Equal to (==)
if a == b:
   print True
 
# Not equal to (!=)
if a != b:
   print True
 
# Less than (<)
if a < b:
   print True
 
# Less than or equal to (<=)
if a <= b:
   print True
 
# Greater than (>)
if a > b:
   print True
 
# Greater than or equal to (>=)
if a >= b:
   print True

11. Control flows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
# if else syntax 
 
if myVar == "tech" or myVar == "techno":
   print "Technology"
elif myVar == "And" and pre == "A":
   print "and"
else:
   print "Digital"
 
if not a > b:
   print "a is not greater than b "
 
if a > b and not b == 0:
   print "a is not greater than b and b is not zero"

12. Functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
def add(a,b):   
    return a+b
 
print add(5,4)
 
# Pass a list of arguments 
def get_max(*args):
    return max(args)
 
# Pass a list of arguments 
get_max(0, -2 , -4, 5 , 7 )
 
# Function to return the absolute value 
def get_abs(val):
    return abs(val)

13. Inbuilt functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
# Returns data  type  
type(var) 
 
# Prints int 
print type(5)
 
# Prints str
print type("Tech")
 
# Returns max from arguments  
max()
print max(2,3,5,6)
# Returns min from arguments  
min()
print min(2,3,5,6)
 
# Return absolute value 
abs()
 
# Array of numbers from 0 to 9 
range(0,10) 
 
# Generates a random integer between 0 and 999  
randint(0, 999)
 
# Round for two decimal numbers 
round(12.5489, 2)

14. Anonymous Functions

1
2
3
4
5
6
 
numbers = [11, 10, 1, 2, 3, 4 ]
# Filers all the numbers divisible by 2 
print filter(lambda x: x % 2 == 0, numbers )
 
# lambda - Writes functions that does not bound a  name.

15. Import Library Time

1
2
3
4
5
6
7
8
9
 
from datetime import datetime
from module import *
 
import math 
 
# List everything in a module 
all = dir(math)
print  all

16. Date time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
from datetime import datetime
 
# Current date 
current_date = datetime.now() 
print current_date
 
# Day 
current_date.day()
 
# Month 
current_date.month()
 
# Year 
current_date.year()
 
 
# Hour
current_date.hour()
 
 
# Minute
current_date.minute()
 
 
# Seconds
current_date.second()

17. Bitwise Operators

 
# Shift Right
print 5 >> 3 
 
# Shift Left
print 4 << 2
 
# AND  
print 3 & 2 
 
# OR
print 7 | 3  
 
# XOR
print 23 ^ 12 
 
# NOT
print ~45     
 
# Convert to binary - 0b11
print bin(3)

18. Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
class Student(object):
    # Initialize 
    def __init__(self, name, age, sex ):
        self.name = name
        self.age  = age
        self.sex  = sex
    # Short representation of the class object 
    def __repr__(self):
        return "(%d, %d, %d)" % (self.name, self.age, self.sex )
 
    def get_age(self):
        return self.age
 
    def is_male(self):
       if sex == "m"
          return True
       else 
          return False
 
stud = Student("Sarath", 30 , "London")
 
print stud 
print stud.get_age()
 
 
# Inheritance 
class University(object):   
  def __init__(self, student_id):
      self.student_id = student_id
  def get_class(self):
      return "A" 
 
  def calculate_grade(self):
      return "Super Class"
 
class Students_details(University):
  def get_grade(self):
      return "Grades not available"  
 
  # Overrides function
  def calculate_grade(self):
      return "Child Class"
 
 
obj = Students_details("STUD_123")
 
obj.get_class()
obj.get_grade()
obj.calculate_grade()

Tagged ,

Share this to

Leave a reply

Your email address will not be published. Required fields are marked *

*

About
View Sarath D R's profile on LinkedIn

I am a technology consultant and an entrepreneur focused on the following technologies Java,Spring, Android, Angular, Asterisk, Symfony, Cake , Code-Igniter, Jquery , XAMPP, XHTML, AJAX, MySql, Seo, Web Design, Wordpress, iPhone development.

Today’s Tips
  • Generate Codova.jar file from Phonegap project using ant
  • Google map javascript client  to find the geographic co-ordinates  from  Address or post code
  • Update Android main UI from Webview – Phonegap Plugin
  • Jplayer is not working  with HTC One Android 4.3 version browser
  • Regular expression to validate mobile phone numbers starting with + ( plus ) – php
  • Simple pagination script for PHP
  • Useful adb ( Android Debug Bridge ) commands
  • Change the javascript files url to absolute url – Symfony 1.4
  • Set Http authentication header from Client – PHP / CURL

This site uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information about your use of this site is shared with Google. By using this site, you agree to its use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.This site also uses cookies from Google to deliver its services, to personalise ads and to analyse traffic. Information about your use of this site is shared with Google. By using this site, you agree to its use of cookies.

Close