Lab 2: Python Snippets

Lab 2: Python Snippets

""" MODULE Docstring: RSTFORUM DEVNET Python LAB SCRIPTS """
'==============================================================================='
# "print Welcome to RSTForum"
'==============================================================================='

print (“Welcome to RSTForum")

'==============================================================================='
# print (“Hello, World") and (“Welcome") one below the other
'==============================================================================='

print (“Hello, World"); print (“Welcome")

'==============================================================================='
# run a "test.py" script that was downloaded on computer by issuing following
# python -i test.py
'==============================================================================='

python –i test.py

'==============================================================================='
# Variables
'==============================================================================='

my_number = 5
my_number

'==============================================================================='
# function
'==============================================================================='

def my_function():
    print("Hello from a function")

my_function()

'==============================================================================='
# class
'==============================================================================='

class Myclass:
   x = 5
	
Myclass

'==============================================================================='
# object
'==============================================================================='

myobject = Myclass ()
myobject.x

'==============================================================================='
# Lines and indentation
'==============================================================================='

if True:
   print ("True“)
else:
    print ("False“)

'==============================================================================='
# quotation # comment strings
'==============================================================================='

'This is a comment'
" This is also a comment"
""" This is also a comment"""

'==============================================================================='
# comment strings
#example 1
'==============================================================================='

#This is a comment
'Welcome to RSTForum'

'==============================================================================='
#example 2
'==============================================================================='

print "Hello, Python!" #This is a comment

'==============================================================================='
#example 3
'==============================================================================='

"""
This is a comment
"""
print("Hello, RSTForum")

'==============================================================================='
# Waiting for user input
#example 1
'==============================================================================='

input ("\n\nPress the enter key to exit.")

'==============================================================================='
# run a "wait.py" script that was downloaded on computer by issuing following
# python -i wait.py
'==============================================================================='

python –i wait.py

'==============================================================================='
# multiple Statements on single line
'==============================================================================='

import sys; x='RST'; sys.stdout.write(x +'\n')

'==============================================================================='
#Python Variables examples
#example 1
'==============================================================================='

x = 1
print (x)

'==============================================================================='
#example 2
'==============================================================================='

name, weight = "aliya" , 42.8
print (name, weight)

'==============================================================================='
#example 3
'==============================================================================='

name = "ash"
weight = 48.5
name; weight

'==============================================================================='
#example 4
'==============================================================================='

a = b = c = 1
a, b, c

'==============================================================================='
#example 5
'==============================================================================='

a = b = c = 1
a; b; c

'==============================================================================='
# Python Output Variables Examples
#example 1
'==============================================================================='

x = "RSTForum"
print ("Welcome to " + x)

'==============================================================================='
#example 1
'==============================================================================='

x = 5
y = 10
print(x + y)

'==============================================================================='
#example 2
'==============================================================================='

x = "Python is "
y = "Great"
z =  x + y
print(z)

'==============================================================================='
#example 3 TypeError: unsupported operand type(s) for +: 'int' and 'str' 
'==============================================================================='

x = 5 ; y = “RST"
print(x+y)
#should return "error TypeError:unsupported operand type(s) for +: 'int' and 'str'

'==============================================================================='
#Python Global Variables
#example 1
'==============================================================================='

x = "RSTForum"
def myfunction():
    print ("Welcome to " + x)

myfunction()

'==============================================================================='
#example 2
'==============================================================================='

x = “Python“
	
def myfunction():
    x = “RSTForum"
    print(“Welcome to " + x)

myfunction()
print(“Welcome to " + x)

'==============================================================================='
#example 3
'==============================================================================='

Welcome to RSTForum
print("Welcome to " + x)

'==============================================================================='
#Python Global Variables inside a 
#example 1
'==============================================================================='

def myfunction():
    global x
    x = "RSTForum“

myfunction()
print ("Welcome to " + x)

'==============================================================================='
#example 2
'==============================================================================='

x = “RSTForum“
def myfunction():
    global x
    x = “Python“

myfunction()
print(“Welcome to " + x)

'==============================================================================='
#Python Data Type
#string
'==============================================================================='

x = "Hello RSTForum"
print(x) ; print(type(x)) 

'==============================================================================='
#integer
'==============================================================================='

x = 5
print(x) ; print(type(x)) 

'==============================================================================='
#float
'==============================================================================='

x = 5.8
print(x) ; print(type(x)) 

'==============================================================================='
#complex
'==============================================================================='

x = 5j
print(x) ; print(type(x))

'==============================================================================='
#list
'==============================================================================='

x = [“jay", “veeru", “gabbar"]
print(x) ; print(type(x)) 

'==============================================================================='
#Tuple
'==============================================================================='

x = (“jay", “veeru", “gabbar“)
print(x) ; print(type(x)) 

'==============================================================================='
#range
'==============================================================================='

x = range(5)
print(x) ; print(type(x)) 

'==============================================================================='
#dictionary
'==============================================================================='

x = {"name" : “Rohish", "age" : 31}
print(x) ; print(type(x)) 

'==============================================================================='
#set
'==============================================================================='

x = {“jay", “veeru", “gabbar"}
print(x) ; print(type(x)) 

'==============================================================================='
#frozenset
'==============================================================================='

x = frozenset({“jay", “veeru", “gabbar"})
print(x) ; print(type(x)) 

'==============================================================================='
#boolean
'==============================================================================='

x = True
print(x) ; print(type(x))

'==============================================================================='
#bytes
'==============================================================================='

x = b“RSTForum"
print(x) ; print(type(x))

'==============================================================================='
#bytearray
'==============================================================================='

x = bytearray(5)
print(x) ; print(type(x))

'==============================================================================='
#Memoryview
'==============================================================================='

x = memoryview(bytes(5))
print(x) ; print(type(x)) 

'==============================================================================='
#Python Numbers Type Conversion
#example 1
'==============================================================================='

x = 1    # int
y = 2.8  # float

a = float(x)
b = int(y)
c = complex(x)

print(a);print(b);print(c);print(type(a)); print(type(b));print(type(c))

'==============================================================================='
#Python Random Numbers
#example 1
'==============================================================================='

import random
print (random.randrange (1, 10))

'==============================================================================='
#Python playing around with Strings 
#example 2
#String: "Hello, World!"
#To get the character at position 4 
#(first character has the position 0)
'==============================================================================='

a = "Hello, World!"
print(a[4])

'==============================================================================='
#example 3
#To get the character from position 2 to position 5:
'==============================================================================='

a = "Hello, World!"
print(a[2:5])

'==============================================================================='
#example 4
#To Get the characters from position 4 to position 1, 
#starting the count from the end of the string
'==============================================================================='

a = "Hello, World!"
print(a[-4:-1])

'==============================================================================='
#example 5
#To Get the length of a string use the len() function
'==============================================================================='

a = "Hello, World!"
print(len(a))
13

'==============================================================================='
#example 6
#String: “   Hey RSTForum   "
#The strip() method removes any whitespace from the beginning or the end: 
'==============================================================================='

b = “     Hey RSTForum     "
print(b.strip())

'==============================================================================='
#example 7
# The lower() function returns the string in lower case:
'==============================================================================='

"WhO wRoTe THIs? " .lower() 

'==============================================================================='
#example 8
#The upper() function returns the string in upper case:
'==============================================================================='

b = "Hey RSTForum"
print(b.upper())

'==============================================================================='
#example 9
#The replace() replaces a string with another string:
'==============================================================================='

b = "Hey RSTForum"
print(b.replace(“e", “o"))

'==============================================================================='
#example 10
#The split() splits a string into 2 parts: if it finds ‘” , “
'==============================================================================='

a = "Hello, RSTForum!"
print(a.split(",")) 

'==============================================================================='
#example 11
#Merge variable x with variable y into variable z:
'==============================================================================='

x = “Welcome" ; y = “RSTForum“ ; z = x + y
print(z)

'==============================================================================='
#example 12
#To add a space between them, add a " “ :
'==============================================================================='

x = “Welcome" ; y = “RSTForum“ 
z = x +“ “+ y
print(z)

'==============================================================================='
#example 13
#To add strings
'==============================================================================='

“RST” + “Forum”

'==============================================================================='
#example 14
#display a string twice
'==============================================================================='

“RST” * 2

'==============================================================================='
#example 15
#The format() helps insert number into the string:
'==============================================================================='

age = 21 ; txt="My name is Lee, and I am {}"
print(txt.format(age))

'==============================================================================='
#example 16
#Insert multiple items in a string:
'==============================================================================='

name = “Lee” ; age = 21
txt="My name is {} , and I am {}"
print(txt.format(name, age))

'==============================================================================='
#example 17
#new way to Insert items in a string:
'==============================================================================='

“Welcome to {} “.format (“RSTForum“)

'==============================================================================='
#example 18
#The join() joins string separated by ‘” , “ into one string
'==============================================================================='

",".join(['a','b','c'])
'a,b,c'

'==============================================================================='
#Escape Characters
#Single Quote: \'
'==============================================================================='

txt = 'It\'s alright.' ; print(txt)

'==============================================================================='
#Escape Characters
#Slash: \\
'==============================================================================='

txt = 'Five \\ Two' ; print(txt)

'==============================================================================='
#Escape Characters
#New Line: \n
'==============================================================================='

txt = 'RST \n Forum' ; print(txt)

'==============================================================================='
#Escape Characters
#Tab: \t
'==============================================================================='

txt = 'RST\tForum.' ; print(txt)

'==============================================================================='
#Escape Characters
#Backspace: \b
'==============================================================================='

txt = 'RST \bForum.' ; print(txt)

'==============================================================================='
#Arithmetic Operators
#addition
'==============================================================================='

x=4 ; y=2 ; z=x+y ; print(z)

'==============================================================================='
#Arithmetic Operators
#substraction
'==============================================================================='

x=4 ; y=2 ; z=x-y ; print(z)

'==============================================================================='
#Arithmetic Operators
#Multiplication
'==============================================================================='

x=4 ; y=2 ; z=x*y ; print(z)

'==============================================================================='
#Arithmetic Operators
#Division
'==============================================================================='

x=4 ; y=2 ; z=x/y ; print(z)

'==============================================================================='
#Arithmetic Operators
#Modulus
'==============================================================================='

x=4 ; y=2 ; z=x%y ; print(z)

'==============================================================================='
#Arithmetic Operators
#exponential
'==============================================================================='

x=4 ; y=2 ; z=x**y ; print(z)

'==============================================================================='
#Arithmetic Operators
#floor division
'==============================================================================='

x=4 ; y=2 ; z=x//y ; print(z)

'==============================================================================='
#Comparison Operators
#Equal x==y
'==============================================================================='

x=4 ; y=2 ; print(x == y)	       

'==============================================================================='
#Comparison Operators
#Not Equal x!=y
'==============================================================================='

x=4 ; y=2 ; print(x!=y)

'==============================================================================='
#Comparison Operators
#Greater Than x>y
'==============================================================================='

x=4 ; y=2 ; print(x>y)      

'==============================================================================='
#Comparison Operators
#Greater Than x<y
'==============================================================================='

x=4 ; y=2 ; print(x<y)

'==============================================================================='
#Comparison Operators
#Less Than x<y
'==============================================================================='

x=4 ; y=2 ; print(x>=y)

'==============================================================================='
#Comparison Operators
# Greater Than Equal To x>=y
'==============================================================================='

x=4 ; y=2 ; print(x>=y)       

'==============================================================================='
#Comparison Operators
# Less Than Equal To x<=y
'==============================================================================='

x=4 ; y=2 ; print(x<=y)

'==============================================================================='
#Comparison Operators if if else loop
'==============================================================================='

x=4
if x<4:print(“x is less than four”)
elif x==4:print(“x is equal to four”)
else:print(“x is greater than four”)

'==============================================================================='
# Logical and Identity Operators
# and	x < 5 and  x < 10
'==============================================================================='

x=5 ; print (x<5 and x<10)

'==============================================================================='
# Logical and Identity Operators
# or	x < 5 or  x < 4
'==============================================================================='

x=5 ; print (x<5 or x<4)

'==============================================================================='
# Logical and Identity Operators
# and	not(x<5 and x<10))
'==============================================================================='

x=4 ; print(not(x<5 and x<10))

'==============================================================================='
# Logical and Identity Operators
# and	x is y; x==y
'==============================================================================='

x=["cat", "dog"] ; y=["cat", "dog"] ; z=x
print(x is z)
print(x is y)  #False, as x and y are 2 different objects
print(x == y)
print("dog" in x)
print("rat" not in x)

'==============================================================================='
# Functions
# example 1
'==============================================================================='

def my_function():print(“RSTForum")

my_function()

'==============================================================================='
# Functions
# example 2
'==============================================================================='

def function(name):
  print(name + ” “ + “RSTForum")

function(“H!")
function(“Hello")

'==============================================================================='
# Functions
# example 3
'==============================================================================='

def function(name1, name2):
  print(name1 + ” “ + name2)

function(“Hi“ , “Hello")

'==============================================================================='
# Functions with Arbitrary Arguments(*args): 
#if we don't know how many arguments will be passed in our function, add a * :
# example 4
'==============================================================================='

def function(*day):
  print("Today is " + day[2])

function(“Monday", "Tuesday", “Wednesday")

'==============================================================================='
# Functions with Arbitrary Arguments(*args):
# Passing a List as an Argument:
# example 5
'==============================================================================='

def my_function(items):
  for x in items:
    print(x)

comp = [“CPU", “RAM", “SSD"]
vehicle = [“Cycle", “Car", “Bus"]
my_function(comp) 
my_function(vehicle)

'==============================================================================='
# Functions
# example 6
'==============================================================================='

def add(num1, num2):
     result = num1 + num2
     return result

add(3, 5)

'==============================================================================='
# A list is a collection which is ordered and changeable. 
# lists are written with square brackets.
# example 1
'==============================================================================='

x = ['a', 5, 16.4]
x[2]

'==============================================================================='
# List
# example 2
'==============================================================================='

x = ['a', 5, 16.4]
x[2] =20.5
x

'==============================================================================='
# List
# example 3
'==============================================================================='

x = ['a', 5, 20.5]
x.append (“new”)
x

'==============================================================================='
# List
# example 4
'==============================================================================='

x = ['a', 5, 20.5]
x.insert (1, “new”)
x

'==============================================================================='
# List
# example 5
'==============================================================================='

x = ['a','new', 5, 20.5]
x.remove ('new')
x

'==============================================================================='
# List
# example 6
'==============================================================================='

x = ['a', 5, 20.5]
del x[0] 
x

'==============================================================================='
# List
# example 7
'==============================================================================='

x = ['a', 5, 20.5]
y=x.copy()
y

'==============================================================================='
# Tuples
# example 1
'==============================================================================='

x = ('a', 5, 16.4)
x[2]

'==============================================================================='
# Dictionary: Python dictionaries are written with curly brackets,
# They have keys and values.
# example 1
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“} 
mydict

'==============================================================================='
# Dictionary:
# example 2
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“} 
mydict[“since”]

'==============================================================================='
# Dictionary:
# example 3
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“}
x = mydict[“since"]
print(x)

'==============================================================================='
# Dictionary:
# example 4
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“}
x=mydict["since"] =2020
mydict

'==============================================================================='
# Dictionary:
# example 5
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “2020“}
y=mydict.get("name")
y

'==============================================================================='
# Dictionary:
# example 6
'==============================================================================='

if “since" in mydict:
   print("Yes, ‘since' is a keys in our dictionary")

'==============================================================================='
# Dictionary: You can loop through a dictionary by using a for loop:
# Print all key names in the dictionary, one by one:
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“} 
for x in mydict:  print(x)

'==============================================================================='
# Dictionary: You can loop through a dictionary by using a for loop:
# Print all values in the dictionary, one by one:
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“}
for x in mydict:  print(mydict[x])

'==============================================================================='
# Dictionary: You can loop through a dictionary by using a for loop:
# we can also use the value() method to return values of dict:
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“}
for x in mydict.values():  print(x)

'==============================================================================='
# Dictionary: You can loop through a dictionary by using a for loop:
# Print the number of items in the dictionary:
'==============================================================================='

mydict = {“name“: “RSTForum“, “since“: “1997“}
len(mydict)

'==============================================================================='
# While Loop: Statements keep executing till condition is true:
# example 1
'==============================================================================='

i = 1 
while i < 4: 
   print(i)
   i += 1

'==============================================================================='
# While Loop:
# example 2
'==============================================================================='

i = 1
while i < 6:
    print(i)
    if (i == 2):
       break
    i += 1

'==============================================================================='
# While Loop:
# example 3
'==============================================================================='

i = 1
while i < 3:
    print(i)
    i += 1
else:
     print("i is no longer less than 3")

'==============================================================================='
# While Loop:
# example 4
'==============================================================================='

from time import sleep
while True:
     try:
         print("Polling.")
         sleep(1)
     except KeyboardInterrupt:
         break

'==============================================================================='
# For Loop:
# example 1
'==============================================================================='

for i in range (3): 
    print (i)

'==============================================================================='
# For Loop:
# example 2
'==============================================================================='

names = [“RST”, “Forum”]
for x in names:
    print(x)

'==============================================================================='
# For Loop:
# example 3
'==============================================================================='

list = [ ( "apple", 2 ) ,  ( "banana“ , 3 ) ]
for fruit in list:
    print(fruit)

'==============================================================================='
# For Loop:
# example 4
'==============================================================================='

dict = { "apple“ : 2  ,  "banana“ : 3 }
for x,y in dict.items(): # using items functon
    print(x,y)

'==============================================================================='
# For Loop:
# example 5
'==============================================================================='

dict = { "apple“ : 2  ,  "banana“ : 3 }
for x, y in dict.items(): 
  print(y)

'==============================================================================='
# For Loop:
# example 6
'==============================================================================='

dict = { "apple“ : 2  ,  "banana“ : 3 }
for x in dict.values(): # using values functon
    print(x)

'==============================================================================='
''' Thank You From RSTForum '''
'==============================================================================='