Kagula
02-22-2023
Introduction
How to get python in ten minutes from C++ programmer view. Here introduces python by a few examples, letting you quickly dive into python’s world!
Environment
- Visual Studio Community 2022 17.5.0
- Python 3.11.2
Content
Install Environment
First step:
Open Visual Studio Installer and check Python development box to install, after everything is ok start visual studio community.
Last Step:
Install the last python from Python home page and use default settings. In my computer default install path is “c:\Users\jun li\AppData\Local\Programs\Python\Python311”.
You will notice pip, it is the packet manager for python.
Hello World
Choice “Python Application” from the project templates and create my first python program.
import sys
print("Hello, World!");
print ("Python Version {}".format(str(sys.version).replace('\n', '')))
If you install Python is ok, now you can press F5 to run the above snippet.
I can see "Python Version 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)]" in my Output window.
Basic data types
import sys
varBool = True
print(type(varBool))
varNum = 1
print(type(varNum))
#varNum = 0x123 is Hexadecimal as C++
varFloat = 3.14159 #you can use 'e' symbol to indicate scientific notation, exmaple varFloat = 314159e-5
#using str function to stringify
print("varFloat is " + str(varFloat) +", type is " + str(type(varFloat)))
print(sys.getsizeof(varFloat)) #For float default type is double.
#the result of sys.getsizeof(varFloat) is 24 bytes.
varComplex = 1+2j #Equivalent to varComplex = complex(1,2)
print("varComplex's value = " + str(varComplex) + ", type is " + str(type(varComplex)))
varString = "I need money."
print(varString);
#More detail reference to https://docs.python.org/3/library/string.html
#You can regard list in python is array in C++.
#first we familiarize with assert function
#assert expression[, assertion_message]
print("\n")
print("--varArray--")
varArray = [1,'2'] #Note: the second item is string type.
print(type(varArray)) #print out class type is list.
assert(varArray[0]==1)
varArray[0] = 100
assert(varArray[0]==100)
assert(len(varArray)==2)
varArray.append(3)
assert(len(varArray)==3)
#remove an item in varArray by index number.
varArray.pop(0) #base index is 0 which is as C++ language.
assert(len(varArray)==2)
assert(varArray[0]=='2')
#remove the item in array by value.
varArray.remove('2')
assert(varArray[0]==3)
print("\n")
print("--varDict--")
#Dictionary in Python like Map in C++
varDic = {10:"Red",
11:"Green"}
print(varDic)
#Get value by key
assert(varDic[11]=="Green")
assert(len(varDic)==2)
#Update
varDic[11] = "Blue"
assert(varDic[11]=="Blue")
#Add
varDic[12] = "Purple"
assert(len(varDic)==3)
#Remove
del(varDic[11]) #Remove the specified item.
assert(len(varDic)==2)
varDic.clear()
assert(len(varDic)==0)
#query
print(11 in varDic)
print(11 not in varDic)
#query if 11 is exist, if not exist, return the second argument -1
#symbol ':' at end indicates the end of if statement
#TheVarOfDictionary.get(<key>[, <default>])
if varDic.get(11,-1) == -1:
#same indent indicated snippet in the same sub routine.
print("key 11's value is not exist!")
#Merge Dictionaries
varDic2 = {10:"Scarlet",
11:"jade"}
varDic.update(varDic2);
assert(varDic[10]=="Scarlet")
print("\n")
print("--varSet--")
varSet = set(["Broccoli", "Cabbage", "Lettuce"])
#Query
if "Cabbage" in varSet:
print("Cabbage in varSet!")
#Add
varSet.add("Onion");
assert(len(varSet)==4)
#Remove
varSet.remove("Cabbage");
assert(len(varSet)==3)
if "Cabbage" not in varSet:
print("Cabbage not in varSet!")
#Merge Sets
varSet2 = set(["Flamingo"])
varSet.update(varSet2);
Branches and Loops
varSet = set(["Broccoli", "Cabbage", "Lettuce", "Onion"])
varStr = "Lettuce";
#Give examples of How to use if as C++
if varStr is "Cabbage":
print("varStr is Cabbage")
elif varStr is "Lettuce":
print("varStr is")
else:
print("varStr is not Cabbage or Lettuce!")
#Give examples of How to use loop
varIndex = 0
while varIndex < len(varSet):
print("varIndex="+str(varIndex))
varIndex=varIndex+1
for item in varSet:
print(item)
#below snippet only output 1 and 2, though range(1,3).
for i in range(1,3):
print(i)
i += 1
for character in "abc":
print(character)
Functions and Recursion
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Multifiles
#file -- test.py --
myvar = 42
def test_func():
print("Hello!")
#file -- use_test.py --
import test
test.test_func() #prints "Hello!"
print (test.myvar) #prints 42
from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar) #Exception (NameError)
from test import *
test_func() #prints "Hello"
print(myvar) #prints 42
IO – Console
#Take input from the console with the input function
varStr = input("Please enter your name: ")
print("Welcome", varStr)
varNum = int(input('Enter a number: '))
print("varNum", varNum)
#Combine (concatenate) letters and numbers
print("If you had", 1, "shot, or", 1, "opportunity, to seize...")
#Format output
x = 5
y = 10
print('The value of x is {} and y is {}'.format(x,y))
Class And It's Instance
class Person:
def __init__(self, name, age):
#public attribute
self.name = name
#single underscore begin name is protected attribute.
self._age = age
#If a attribute name begin with double underscore, this is a private attribute.
#No underscore prefix begin is a public method.
def APublicMethod(self):
print("My age is ",self.age," and i like drink!")
#Single underscore prefix begin is a protected method.
def _AProtectedMethod(self):
print("AProtectedMethod")
#Double underscore prefix begin is a private method.
def __APrivateMethod(self):
print("APrivateMethod")
p1 = Person("John", 36)
print(p1.name)
#print(p1.age) will throw a exception, because you can not access the private attribute.
p1.APublicMethod()
#Invoke p1.__APrivateMethod() will throw a exception, because you can not access the private method.
#Release the object if you feel memory is insufficient.
del p1
print("\nThe example of inheritance")
class Villain(Person):
def __init__(self, name, age):
super().__init__(name, age)
self.money = "Sufficient"
#The Example of override parent's method
def APublicMethod(self):
print("Devil drink a beverage.")
print("My money is ", self.money)
self._AProtectedMethod()
#Invoke self.__APrivateMethod() will throw a exception.
v1 = Villain("King",2000)
v1.APublicMethod()
print("\nThe example of multi inheritance")
class AbsolutePower:
def show(self):
print("My Power is limitless!");
class Devil(Villain,AbsolutePower):
def DevilsShow(self):
print("I will conquer the whole world!")
d1 = Devil("Great King",5000)
d1.APublicMethod()
d1.show()
d1.DevilsShow()
Access Text File
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Reference
- https://docs.python.org/3.11/tutorial/index.html
- https://docs.python.org/3.11/index.html