Python basic syntax

1, Variables and data types

   Python data types are not declared, and the compiler automatically recognizes them. The common data types are as follows; There is no need to add a semicolon at the end of each line of Python code; Python code blocks need to follow strict indentation rules; Python 3 habitually adds parentheses when printing messages, and defaults to line breaking after printing; Python adopts #, single line annotation and ""... "", multi line annotation.

  1. Integer (int)
  2. Floating point
  3. Boolean (bool)
  4. String: divided into single quotation marks and double quotation marks. Usage: String case modification, string splicing, str() forced type conversion, and deletion of blank string

[note] the code can be tried through the python interactive interface. The command is Python 3

#Modify string case -- title() / upper() / lower())
name = "ada lovelace"
print(name.title())        #The first letter of the string is capitalized. Print result: Ada Lovelace 
print(name.upper())        #         All capital letters ADA LOVELACE
print(name.lower())        #         All lowercase ada lovelace

#Splice string - "+"
first_name = "ada"
last_name = "lovelace"
full_name = "ada" + " " + "lovelace"
print(full_name)           #Splicing string print result: ada lovelace 

#String cast -- str()
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)             #Type conversion print result: Happy 23rd Birthday!

#(temporarily) delete whitespace -- rstrip()/lstrip()/strip())
favorate_language = ' python '
favorate_language.rstrip()          #Remove end blank
favorate_language.lstrip()          #Remove leading blanks
favorate_language.strip()           #Remove the blank at both ends of the first row

2, List base []

   list, similar to "array", consists of a series of elements arranged in a specific order, * * represented by brackets "[]" and separated by commas ",". In python, it is customary to give a list a noun that represents the plural (such as letters, nums, etc.).
   lists are divided into string lists and number lists, which are described below with string lists.

  1. Access: the index of list elements starts from 0;
  2. Adding and deleting elements: using built-in methods, append()/insert() and del()/pop()/remove();
  3. Sorting: Alphabetical / reverse, sort()/sort(reverse = True), sorted(), len()
#Access list elements
bicycles = ['trek', 'cannon', 'redline']
print(bicycles[0])                     #Print result: trek

#Add element -- applied() / insert()
bicycles.append('honda')               #Add element at the end of the list
print(bicycles)                        #Print result: ['trek ',' cannon ',' redline ',' Honda ']
bicycles.insert(0, 'ducati')           #Inserts an element at the specified location in the list
print(bicycles)                        #Print result: ['ducati ',' Trek ',' cannon ',' redline ',' Honda ']          

#Delete element - del()/pop()/remove()
del bicycles[0]                        #Deletes the element at the specified location
print(bicycles)                        #Print result: ['trek ',' cannon ',' redline ',' Honda ']
poped_bicycles = bicycles.poped()      #Delete end element
print(poped_bicycles)                  #Print result: ['trek ',' cannon ',' redline ']
bicycles.remove('cannon')              #Delete element based on value
print(bicycles)                        #Print result: ['trek ',' redline ',' Honda ']

#(permanent) list sorting - sort()/sort(reverse=True)
cars = ['bmw', 'audi', 'toyato', 'subaru']
cars.sort()
print(cars)                            #Print results: ['audi ',' BMW ',' Subaru ',' Toyato ']
cars.sort(reverse=True)
print(cars)                            #Print results: ['toyato ',' Subaru ',' BMW ',' Audi ']

#(temporary) list sorting - sorted
cars = ['bmw', 'audi', 'toyato', 'subaru']
print(sorted(cars)                     #Print results: ['audi ',' BMW ',' Subaru ',' Toyato ']
print(cars)                            #Print result: ['bmw ',' Audi ',' Toyato ',' Subaru ']

#List reverse printing, and length -- reverse()/len()
cars = ['bmw', 'audi', 'toyato', 'subaru']
cars.reverse()
print(cars)                            #Print result: ['subaru ',' Toyato ',' Audi ',' BMW '] 
len(cars)                              #Print result: 4

3, Operation list [] - traversal

   list traversal, that is, use the for loop to perform the same operation on each element in the list. The elements in the list can be modified. There is also a special kind of list. The elements cannot be changed and become tuples (immutable lists).

  1. Traversal: for loop implementation;
  2. Create a number list: built in method implementation, range() - generate a series of numbers, list() - convert the range() result into a list;
  3. Slice: process some elements of the list, [x:y], and the list cannot be assigned directly.
  4. Tuple: represented by parenthesis "()", in which the element cannot be modified.
#Traversal array -- for loop
magicians = ['alice', 'david', 'bob']
for magicain in magicians:                 #Traversal array
	print(magician.title() + ", that was a great trick!") 
print("I can't wait to see your next trick, " + magician.title() + ".\n")

#Print results:
Alice, that was a great trick!
David, that was a great trick!
Bob, that was a great trick!
I can't wait to see your next trick, Bob.

#Create a list of numbers - list(range())
nums = list(range(1,6))                    #Create a list of numbers
print(nums)                                #Print result: [1, 2, 3, 4, 5]
even_nums = list(range(1,6,2))             #Create a list of numbers and specify the step size
print(even_nums)                           #Print results: [1, 3, 5]

#List slicing -- use a part of the list [x:y], [x:], start from scratch [: y], return the last x elements of the list [- X:], and copy the list [:]
players = ['mrac', 'jim', 'tom', 'bob', 'pierr', 'clerry']
print(players[1:4])                        #Print result: ['Jim ',' Tom ',' Bob ',' Pierre ']
print(players[:2])                         #Print result: ['marc ',' Jim ',' Tom ']
print(players[4:])                         #Print result: ['pierre ',' clerry ']
print(players[-3:])                        #Print result: ['bob ',' Pierre ',' clerry ']

my_players = players[:]                    #Copy list elements
print(my_players)                          #Print result: ['mrac ',' Jim ',' Tom ',' Bob ',' Pierre ',' clerry ']   

#Tuple ()
dimensions = (200, 50)                     #Define tuples
for dimension in dimensions:
	print(dimension)                       #Print result: 200
	                                       #           50

4, Dictionary {key: value, key: value}

   in Python, a dictionary is a series of key value pairs, and the values associated with it can be accessed through keys. The values associated with keys can be numbers, strings, lists, dictionaries, and so on.
   a dictionary is a dynamic structure in which key value pairs can be added at any time.

  1. Access the value in the dictionary: through the key;
  2. Add and delete key value pairs: unordered addition;
  3. Modify the value in the dictionary: reassign;
  4. Dictionary traversal: unordered output, traversal of key value pairs, traversal of all keys, traversal of all values; Methods: items() / keys() / values().
#Access, (unordered) add, delete key value pairs
alien_o = {'color' : 'green', 'points' : 5}
print(alien_o['color'])                  #Print result: green
print(alien_o)                           #Print results: {color ':' green ',' points': 5}

alien_o['x_position'] = 0
alien_o['y_position'] = 25               #Add key value pair
print(alien_o)                           #Print results: {color ':' green ',' points': 5, 'y_position': 25, 'x_position': 0}

#Modify the value in the dictionary - reassign
alien_o['color'] = 'yellow'
print(alien_o['color'])                  #Print result: yellow

#(permanent) delete - del
del alien_o['points']                    #Delete key value pair
print(alien_o)                           #Print results: {color ':' green ',' y_position ': 25,' x_position ': 0}

#Traversal key value pair - for
user_0 = {
	'username' : 'efermi',
	'first' : 'enrico',
	'last' : 'fermi',
}
for key,value in user_0.items():         #Traversal key-Value pair     #Print results: unordered output
	print("\nKey: " + key)                                #Key: last
	print("Value", + value)                               #Value: fermi
for key in user_0.keys():                #Traversal key          #                          #Print results: unordered output
	print(key.title())                                    #Key: first                #Username
for value in user_0.values():            #Traversal value          #Value: enrico             #Last                       #Print results: unordered output
	print(value.title())                                  #                          #First                      #Efermi
                                                          #Key: username                                         #Enrico
                                                          #Value: efermi                                         #Fermi

5, User input and while loop

   the function input() will pause the program, give a prompt, wait for the user to enter some text (string), and python will store it in a specified variable. Sometimes, if the prompt may exceed one line, you can store the prompt in a variable and pass the variable to input().

prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat's your first name?"
name = input(prompt)
print("\nHello, " + name + "!")

#Print results:
If you tell us who you are, we can personalize the message you see.
What's your first name? Eric

Hello, Eric!
#while loop -- break ends the loop, continue ends the loop, and returns to the beginning of the loop
while True: 
	city = input("\nPlease input the name of a city, enter 'quit' when you are finished: ")
	if city == 'quit':
		break                      #End cycle
	else:
		print("I'd like to go to " + city.title() + "!")
	
num = 0	
while num < 10:
	num += 1
	if num % 2 == 0:
		continue                   #End this cycle and return to the beginning of the cycle
	print(num)                     #Print result: 1 3 5 7 9

6, if statement

The core of   if statements is an expression with a value of True or False, that is, conditional test. The conditional test supports the check of multiple conditions and specific values. A colon should be added at the end:.

  1. Multi condition check Keywords: and, or, in, not in, etc;
  2. Multi conditional format: if... Elif... else... else can be omitted, elif... else... Can also be omitted
#if statement format
age = 23
if age >= 18 and age == 23:
	print("You are old enough to vote!")

#Use if to process lists
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
	if requested_topping == 'green peppers':
		print("Sorry, we are out of green peppers right now.")
	else:
		print("Adding " + requested_topping + ".")
print("\nFinishing making your pizza!")

7, Function def

   functions in python are defined by the keyword def, and the definition ends with a colon. Information about functions:

  1. Parameter passing: actual parameter - > formal parameter (the default value of formal parameter can be set, and there can be no spaces on both sides of the equal sign);
  2. Return value: the function needs to provide a variable to store the return value;
  3. Functions can be stored in modules: import modules through the keyword import, or import specific functions in modules;
  4. Function alias: assign an alias to a function / module through the keyword as.
#Positional arguments - pass one-to-one correspondence, keyword arguments - no spaces on both sides of the equal sign
def describe_pet(animal_type, pet_name='dog'):
	"""Display pet information"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('hamster', 'harry')                        #Call function, position argument
describe_pet(animal_type='hamster', pet_name='harry')   #The second call to the function, keyword argument

#Return value - return returns the value to the code line of the calling function
def get_formatted_name(first_name, last_name, middle_name=''):     #Set argument optional (implemented by empty end string)
	"""Return neat name"""
	if middle_name: 
		full_name = first_name + ' ' + middle_name + ' ' + last_name
	else:
		full_name = first_name + ' ' + last_name
	return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)                                          #Print result: Jimi Hendrix

  storing functions in modules:

#pizza.py
def make_pizza(size, *toppings):          #*Toppings: indicates to create an empty ancestor named toppings
	"""Overview of pizza to be made"""
	print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
	for topping in toppings:
		print("- " + topping)
#making_pizzas.py
import pizza                              #Import specific function: from pizza import make_pizza 

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

#Assign alias to module - as
#import pizza as p
#pizza.make_pizza(16, 'pepperoni')
#pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

8, class

   the first letter of the class name in python must be capitalized. The class contains properties and methods, just like other languages.

  1. Method__ init__ (): the default method of python, in which the formal parameter self is essential. When the class creates a new instance, init() will run automatically and the actual parameter self will be passed in automatically. Each method call associated with the class automatically passes in the argument self, which is a reference to the instance itself, so that the instance can access the properties and methods in the class. Variables prefixed with self can be used by all methods in the class.
  2. Class instantiation: during class instantiation, arguments will be passed in to call the methods in class through the instantiation name.
  3. Class inheritance: syntax class ElectricCar(Car): when subclassing, the methods in the subclass__ init__ () the parent class is required to create. Subclass__ init__ () calls the in the parent class Car through the keyword super__ init__ () method to associate parent and child classes.
  4. Taking an instance of a class as an attribute: This is equivalent to instantiating this attribute class and storing the attribute in the corresponding variable.
#dog.py
class Dog():
	"""A simple attempt to simulate a puppy"""
	def __init__(self, name, age):
		""""initialization name and age"""
		self.name = name                         #Attributes (variables) in class and variables prefixed with self can be used by all methods in class
		self.age = age
	def sit(self):                               #Methods in class
		"""Simulate a dog squatting when ordered"""
		print(self.name.title() + "is now sitting.")
	def roll_over(self):
		"""Simulate the dog rolling when ordered"""
		print(self.name.title() + "rolled over!")		

my_dog = Dog('willie', 6)                        #Instantiate, pass parameters
my_dog.sit()                                     #Call method
my_dog.roll_over()

Inheritance of   class:

#Parent class
class Car():
	def __init__(self, make, model, year):
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0               #Adds a default value to the specified attribute
	def get_descriptive_name(self):
		long_time = str(slef.year) + ' ' + self.name + ' ' + self.model
		return long_time.title()
	def read_odometer(self):
		print("This car has " + str(self.odometer_reading) + " miles on it.")
	def update_odometer(self, mileage):
		if mileage >= self.odometer_reading:
			self.odometer_reading = miles
		else:
			print("You can't roll back an odometer!")

class Battery():
	def __init__(self, battery_size=70):
		self.battery_size = battery_size
	def describe_battery(self):                 
		print("This car has a " + str(self.battery_size) + "-kWh battery.") 

class ElectricCar(Car):                         #inherit
	def __init__(self, make, model, year):
		super.__init__(make, model, year)       #Call the in the parent class Car through the keyword super__ init__ () method, associating parent and child classes
		self.battery = Battery()                #Add a new attribute, take the instance as an attribute, and create a Battery instance


my_tesla = ElectricCar('tesla', 'model s', 2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()             #Call the method of the property class in the current class

9, Import class

   importing classes is an effective programming method. It is flexible and versatile in Python, which can greatly save the amount of code.

  1. Store multiple classes in the module: the standard library of python contains a large number of existing modules for users to use
  2. Import multiple classes in one module: there are various import methods, as follows:
  3. Import class: it is equivalent to copying the class to the current file.
#Importing class Car from module Car supports importing multiple classes
from car import Car
from car import Car, ElectricCar

#Direct import module
import car

10, File and exception

  1. Open file: the function open('file_name ') opens the specified file, and python will find the specified file in the directory where the current file is located. The function open() returns an object representing a file, which Python stores in a variable to be used later. The keyword with closes the file after it does not need to be placed.
  2. Read file: read() reads the contents of the entire file and stores it as a long string in the specified variable. redlines() reads each line of the file and stores each line in a list. When reading a file, python interprets all text in it as strings.
#Read the entire file - read()
with open('digital.txt') as file_object:
	conetents = file_object.read()
	print(contents)

#Read the file lines -- redlines(), and store the file lines in a list
with open('digital.txt') as file_object:
	lines = file_object.readlines()
for line in lines:
	print(line.rstrip())         #Print the contents of each line in the list
  1. Write file: call write() to write the contents of the file, and specify the file opening mode - write mode ('w '), read mode ('r'), additional mode ('a '), read and write mode ('r +). If the mode argument is omitted, python will open the file in read only mode by default. Python can only write strings to text files. To write data, you must first use str() for conversion.
filename = 'programming.txt'

with open(filename, 'w') as file_object:
	file_object.write("I love programming.\n")                     #The write function cannot wrap lines automatically
	file_object.write("I love creating new games.\n")
  1. Exception: exceptions in python are handled using a try exception code block. The try except code block lets python perform the specified operation and tells python what to do when an exception occurs. When the try except code block is used, the program will continue to run even if an exception occurs.
print(5/0)

#report errors:
Traceback (most recent call last)
	file "filename.py", line 1, in <module>
		print(5/0)
ZeroDivisionError:division by zero

   in order to avoid python reporting the above errors and interrupting the program, you can continue to run the program through try exception to avoid program crash, as follows:

#Print the specified prompt on failure - specify the operation
try: 
	print(5/0)
except ZeroDivisionError:
	print("You can't divide bu zero!")

#Fail without saying a word - pass
try: 
	print(5/0)
except ZeroDivisionError:
	pass

Keywords: Python Back-end

Added by Theramore on Sun, 27 Feb 2022 10:45:49 +0200