Python Basics

Python Basics

Text

  • Multi line print statement
print("""
Hello World this is amazing
""")
  • Escape Sequences
>>> print('hello\'world')
>>> print('hello\nworld') 
  • Strings Strings are indexed,just like array indexing,here string’s characters can be accessed over index
>>> name="vinay"
>>> name[0] #get the character at 0
'v'
>>> name[0:4] # get characters from 0th index to 4th index of the string
'vina'
>>> name[0:8] # total number of characers is 5 it prints every character
'vinay'
>>> name[-1] # python gives the flexibility to access string characters in reverse indexing way.
'y'
>>> name[-1:0]
''
>>> name[:-1] # can specify a range [:-1] in this range, it prints till the last element,but not the last element
'vina'
>>> name[:]
'vinay'
>>> name[-6:] 
'vinay'

Python strings are immutable and therefore cannot change the characters neither can assign new value to particular index.

>>> name[3]='v'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

len() returns the total length of the string.

Variables and Types

myint=7
print(myint)

myfloat=7.0
myfloat2=float(myint)
print(myfloat,myfloat2)

#strings
name="Vinay Keshava"
name1='kevin'
print(name,name1)

# Regarding strings it is that double quotes makes it easy to add apostrophe in given strings.

#Assignments can be done on more than one variable "simultaneously" on the same line like this
#variable assignment,below is the example for swapping of two variables.
a,b=20,30
print(a,b)
b,a = a,b
print(a,b)

Lists

Lists is a compound data types,where values are separted by commas,here values can be of different types. Unlike strings which are immutable,lists are mutable type,where it is possible to change value of a particular location.

>>> marks = [90,92,100,4,87]
>>> marks
[90, 92, 100, 4, 87]
>>> marks [0]
90
>>> marks [-1]
87
>>> marks [:}
  File "<stdin>", line 1
    marks [:}
            ^
SyntaxError: closing parenthesis '}' does not match opening parenthesis '['
>>> marks [:]
[90, 92, 100, 4, 87]
>>> marks[-1:]
[87]
>>> marks + [10,20,30] #concatenation
[90, 92, 100, 4, 87, 10, 20, 30]
>>> marks
[90, 92, 100, 4, 87]
>>> marks[3]= 76
>>> marks
[90, 92, 100, 76, 87]
>>> marks.append(40) 
>>> marks
[90, 92, 100, 76, 87, 40]

–slicing–

>>> letters = ['a','b','c','d','e','f']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f']
>>> #replace some values
>>> letters[1:4]=['B','C','D']
>>> letters
['a', 'B', 'C', 'D', 'e', 'f']
>>> #can also remove the same values during slicing
>>> letters[1:4]=[]
>>> letters
['a', 'e', 'f']
>>> len(letters)
3
>>> #it is possible to nest lists
>>> letters
['a', 'e', 'f']
>>> marks
[90, 92, 100, 76, 87, 40]
>>> letters = [letters,marks]
>>> letters
[['a', 'e', 'f'], [90, 92, 100, 76, 87, 40]]
>>> letters[0][2]
'f'
>>>