Python

Python is a high-level general-purpose programming language, which is Interpreted, Interactive and Object-Oriented. The term object – oriented means it supports object oriented programming approach to develop applications.

Python file is saved as a .py extension.

Python’s initial development was led by Guido van Rossum in the late 1980s.

Currently, it is the 3rd version which is released in 2008, although the 2nd version originally released in 2000 is still in common usage.

 

Print Command in Python


print "Hello World" # is acceptable in Python 2

print ("Hello World") #  In Python 3, print must be followed by ()

 

The print() function inserts a new line at the end, by default. In Python 2, it can be suppressed by putting ‘,’ at the end. In Python 3, “end =’ ‘” append space instead of newline.

 

print x,        # Trailing comma suppresses newline in Python 2

print(x, end=" ")        # Appends a space instead of a newline in Python 3

 

Reading Input in Python

In Python 2, there are two versions of input functions, raw_input() and input(). The input() function accepts the received data as string if it is included in quotes “” or “, else the data is taken as number.

But for Python 3, raw_input() function is deprecated. Now, the received data is always treated as string.

 

In Python 3:

x = input("something:")

print ('x =', x)

Output

something:10

x = 10



x = input("something:") #entered data treated as string with or without '' or ‘

Output

something:'test code'

x = 'test code'



x =int(input("something:")) #to input an integer number

x=x+1

print ('x =', x)

Output

something:4

x = 5



d=float(input('Float Number:'))

print(‘d=',d)

Output

Float Number:74.76

d= 74.76

 

Waiting for the User

The following code displays the prompt as “Press enter key to end”, and waits for the user for an action:

input("\n\nPress enter key to end.")

In this case, “\n\n” is used to create 2 new lines before displaying the original line. Once the key is pressed, the execution of the program ends.

 

Multiple Assignment

Python allows us to assign a single value to several variables:

a = b = c = 1

print('a=',a,', b=',b,', c=',c)

Output

a= 1 , b= 1 , c= 1

 

In this case, an integer object is created with the value 1, and all three variables are allocated to the same memory location. Also you can assign multiple objects to multiple variables as follows:

a,b,c = 1,2,"test"

print('a=',a+1,', b=',b,', c=',c)

Output

a= 2 , b= 2 , c= test

 

Standard Data Types

Data stored in memory can be of different types. For eg, an amount for a product is stored as a numeric value and the product name is stored as alphanumeric characters.

Python has different standard data types which are used to explain the operations possible on them and the storage method for each one of them.

5 standard data types in Python are Numbers, String, List, Tuple & Dictionary.

Also, you can delete the reference to a number object by using the del command. The syntax is as follows:

del var, var2

 

Python supports four different numerical types:

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

 

Multi-Line Statements

In Python, the statements end with a new line by default. But Python allows the use of the line continuation character (\) to denote that the line should continue.

paragraph = 'This is a paragraph. It is \

made up of multiple lines and sentences.'

print (paragraph)

Output

This is a paragraph. It is made up of multiple lines and sentences.

 

The statements contained within the (), [] or {} brackets do not need to use the line continuation character (\).

 

Multiple Statements on a Single Line

Semicolon ( ; ) allows us to add multiple statements on a single line given that neither statement starts a new code block.

 

test='testline';print (test);input("Press the enter key to exit.")

Output

testline

Press the enter key to exit.

 

Comments in Python

— Single-line comments are created simply by beginning a line with the hash (#) character, and they are terminated by the end of that line.

— Comments that span multiple lines which is used to explain things in detail are created by adding a delimiter (“””) on each end of the comment.

 

“”” This is for testing

Please ignore these comments

Sorry for the inconvenience caused.

“””

Using Blank Lines

A line containing only whitespace, possibly with a comment, is known as a blank line and Python will totally ignore it during the execution of code.

In an interactive interpreter session, we must enter an empty physical line to end a multiline statement during execution time.

 

Integer Division

For Python 2, the result of division of two integers is rounded to the nearest integer value. As a result, 7/2 will show 3. If we want to obtain a floating-point division, numerator or denominator must be explicitly used as float. Hence, either 7.0/2 or 7/2.0 or 7.0/2.0 will result in 3.5

But for Python 3, it evaluates 7 / 2 as 3.5 by default, which is more easy for new programmers.

 

Python Strings

The strings in Python are identified as a contiguous set of characters shown in the quotation marks which either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the starting of the string and working their way from -1 at the end of the string.

The Asterisk (*) is the repetition operator and Plus (+) sign is the string concatenation operator.

 

str = 'Hello World!'

print (str)      # Prints complete string

print (str[0] )  # Prints first character of the string

print (str[2:5]) # Prints characters starting from 3rd to 5th

print (str[2:]) # Prints string starting from 3rd character

print (str*2)   # Prints string two times

print (str+"TEST") # Prints concatenated string
print ("Updated String :- ", str[:6] + 'Python')

Output

Hello World!

H

llo

llo World!

Hello World!Hello World!

Hello World!TEST

Updated String :-  Hello Python

 

Quotation in Python

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote begins and terminates the string.

The triple quotes allow us to extend the string across multiple lines. For eg, all the following are legal:

word = 'word'

sentence = "This is a sentence."

paragraph = """This is a paragraph. It is

made up of multiple lines and sentences."""

 

para_str = """this is a long string that is made up of

several lines and non-printable characters such as

TAB ( \t ) and they will show up that way when displayed.

NEWLINEs within the string, whether explicitly given like

this within the brackets [ \n ], or just a NEWLINE within

the variable assignment will also show up.

"""

print (para_str)

Output

this is a long string that is made up of

several lines and non-printable characters such as

TAB ( ) and they will show up that way when displayed.

NEWLINEs within the string, whether explicitly given like

this within the brackets [

 ], or just a NEWLINE within

the variable assignment will also show up.

 

Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −

print ('D:\\hello)

Output

D:\hello

 

If we put expression in r’expression’, then:

 

print r'H:\\hello

Output

H:\\hello

 

Python Lists

A list is a collection which is ordered and changeable. In Python, lists are written with square brackets which allows duplicate members. To some extent, lists are similar to arrays in C. The main one difference between them is that all the items linked to a list is not necessarily of the same data type.

Values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']

print (list)       # Prints complete list

print (list[0])    # Prints first element of the list

print (list[1:3])  # Prints elements starting from 2nd till 3rd

print (list[2:])   # Prints elements starting from 3rd element

print (tinylist * 2)  # Prints list two times

print (list + tinylist) # Prints concatenated lists

Output

['abcd', 786, 2.23, 'john', 70.2]

abcd

[786, 2.23]

[2.23, 'john', 70.2]

[123, 'john', 123, 'john']

['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

 

Python Tuples

Tuple is a particular order consisting of related things of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples can’t be changed unlike lists and tuples use parentheses ( ( ) ), whereas lists use square brackets ( [ ] ). Tuples can be considered as a read-only list.

 

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )

tinytuple = (123, 'john')

print tuple        # Prints complete list

print tuple[0]     # Prints first element of the list

print tuple[1:3]   # Prints elements starting from 2nd till 3rd

print tuple[2:]    # Prints elements starting from 3rd element

print tinytuple * 2   # Prints list two times

print tuple + tinytuple # Prints concatenated lists

Output

('abcd', 786, 2.23, 'john', 70.2)

abcd

(786, 2.23)

(2.23, 'john', 70.2)

(123, 'john', 123, 'john')

('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

 

Python Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets ({ }), and they have keys and values. A dictionary key can be almost any Python type, but are usually numbers or strings. Values can be any arbitrary Python object. Values can be assigned and accessed using square braces ( [ ] ). The Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “not in the correct sequence”; they are simply unordered.

 

dict = {}

dict['one'] = "This is one"

dict[2]  = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one'])    # Prints value for 'one' key

print (dict[2])        # Prints value for 2 key

print (tinydict)       # Prints complete dictionary

print (tinydict.keys())   # Prints all the keys

print (tinydict.values()) # Prints all the values

print (dict)

Output

This is one

This is two

{'name': 'john', 'code': 6734, 'dept': 'sales'}

dict_keys(['name', 'code', 'dept'])

dict_values(['john', 6734, 'sales'])

{'one': 'This is one', 2: 'This is two'}

Leave a Reply