Getting started with Python programming through simple example code snippets. There are plenty of resources on Python. I have referred the following:
- Guido van Rossum and the Python development team (2018). Python Tutorial. Release 3.7.0. Python Software Foundation.
# This is a comment
print("17/3 = ",17/3) # 5.666666666666667; Division
print("17//3 = ",17//3) # 5; Floor
print("17%3 = ",17%3) # 2; Remainder
print("5**2 = ",5**2) # 25; Power of
a = 5
b = 6
c = a*b #30
print(a,b,c) #30
# Multiple assignment
a,b = 10, 20
print(a,b) # 10 20
# Operations
print(22/7) # 3.142857142857143
print(round(22/7,3)) # 3.143; Round
print(round(22/7,2)) # 3.14; Round
print('A belongs to B') # Single quote text
print('A doesn\'t belong to B') # Single quote text with escape character \
print('First line\nSecond Line') # New line
print(r'First line\nSecond Line') # First line\nSecond Line; r - raw strings; Ignores treating characters prefaced with \
print("""\
This is first line
This is second line
This is third line
""")
print('Tiger! '+3*'Run ') # Output: Tiger! Run Run Run
print('Py''thon') # Concatenation of string literals
text = ('This is first sentence. '
'This is second sentence.') # This is first sentence. This is second sentence.
print(text)
# String and characters
word = 'Python'
print(word[0],word[1],word[2],word[3],word[4],word[5]) # P y t h o n
print(word[-1],word[-2],word[-3],word[-4],word[-5],word[-6]) # n o h t y P
print(word[0:2]) #[0:2] - elements 0, 1; ie 'Py'
print(word[2:5]) #[2:5] - elements 2, 3, 4 ie 'tho'
print(word[:2]) # elements 0 & 1; ie 'Py'
print(word[2:]) # elements 2, 3, 4, 5; ie 'thon'
print(word[-2:]) # elements -2, -1 ie 'on'
# Out of range cases
print(word[2:50]) # 'thon' ie elements 2, 3, 4, 5 ie till last element
print(word[50:]) # ''
print(len(word)) # len: length of the string ie 6
print(word.format())
# Lists
numbers = [10,20,30,40,50]
print(numbers[1:], numbers[:3], numbers[2:4], numbers[-2:]) # [20, 30, 40, 50] [10, 20, 30] [30, 40] [40, 50]
# Append elements to a list
numbers = numbers + [60,70]
print(numbers) # [10,20,30,40,50,60,70]
numbers.append(80)
print(numbers) # [10, 20, 30, 40, 50, 60, 70, 80]
# Replace some entries
numbers[2:5] = [35,45,55]
print(numbers) # [10, 20, 35, 45, 55, 60, 70, 80]
# Length of list
print(len(numbers)) # 8
# Clear some entries
numbers[2:4] = []
print(numbers) # [10, 20, 55, 60, 70, 80]
# Clear entire list
numbers[:] = []
print(numbers) # []
# Nested lists
a = [1,2,3,4]
b = ['x','y','z']
c = [a,b]
print(a) # [1,2,3,4]
print(b) # ['x','y','z']
print(c) # [[1,2,3,4],['x','y','z']]
print(c[0]) # [1,2,3,4]
print(c[0][1]) # 1