程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Introduction to Python basic grammar (1)

編輯:Python

1. notes

In the process of coding our work , If the logic of a piece of code is complex , It's not particularly easy to understand , You can add notes appropriately , To help yourself Or other coders interpret the code .

Comments are for programmers to see , In order to make it easy for programmers to read the code , The interpreter ignores comments . Use your familiar language , It is a good coding habit to annotate the code properly ( Be careful to deduct salary without writing notes ).

1.1 Single-line comments

With # start ,# Everything on the right is for illustration , It's not really a program to execute , To assist in explaining .

# Output hello world
print("hello world")# Output hello world

Shift + 3, perhaps Ctrl + ? Can be generated # Number

Comments are usually written at the top of the code , Try not to follow the code . Keep good coding habits

1.2 Multiline comment

With ‘’’ Start , And ‘’’ end , We call it multiline annotation .


''' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Buddha bless never BUG Buddha says : Office room in office building , Programmers in the office ; Programmers write programs , And program for drinks . Drunk only sit on the Internet , Drunken to sleep under the net ; Drunk and sober day after day , Online next year after year . I wish I could die in the computer room , Don't bow to the boss ; Mercedes Benz and BMW , Bus self programmer . People laugh at me for being crazy , I laugh at my life ; No beautiful girls in the street , Which one belongs to the programmer ? '''

2. Variables and data types

2.1 Definition of variables

For reuse , And often need to modify the data , Can be defined as a variable , To improve programming efficiency .

The syntax for defining variables is : Variable name = A variable's value .( there = The function is to assign values .)

After defining a variable, you can use the variable name to access the variable value .

# Define a variable to represent this string . If you need to modify the content , Just modify the value corresponding to the variable 
# Be careful , Variable names do not need to be enclosed in quotation marks 
weather = " It's a beautiful day "
print(weather)
print(weather)
print(weather)

explain :

1) A variable is a variable , It can be modified at any time .

2) The program is used to process data , Variables are used to store data .

2.2 The type of variable

stay Python In order to meet different business needs , Also divide the data into different types .

Focus on :int、float、String、List

python There is no double type , either char Character type

Tuple: and List similar , A collection of data represented by one data

Dictionary: It is similar to the function of dictionary in reality

# int
money = 100
print(100)
# float
price = 99.9
print(price)
# boolean
# Variables should be known by name , Don't use Chinese pinyin , Will be looked down upon 
# male True, Woman False
sex = True
print(sex)
# String
# Single or double quotation marks can be used for strings , But it must appear in pairs 
str = 'hello '
str2 = 'world'
print(str + str2)
# Nesting of single and double quotation marks 
str3 = '" ha-ha "'
str4 = "' ha-ha '"
print(str3)
print(str4)
# Single and double quotation marks match closely , The same cannot be nested 
# str5 = "" Hey "" Incorrect usage 
# list
name_list = [' Zhang Fei ', ' Guan yu ']
print(name_list)
# obtain list Subscript is 0 String , Subscript from 0 Start calculating :0、1、2、3....
print(name_list[0])
# tuple
age_tuple = (18, 19, 20)
print(age_tuple)
# dictionary Dictionaries 
person = {
'name': ' Zhang San ', 'age': 18}
print(person)

2.3 View data type

stay python in , Just define a variable , And it has data , Then its type has been determined , We don't need developers to take the initiative To explain its type , The system will automatically identify . That is to say, when using " Variable has no type , Data has type ".

str5 = "hello"
print(type(str5))
#<class 'str'>
#str yes string An abbreviation of 

If you want to view the data type stored in a variable temporarily , have access to type( The name of the variable ), To see the data type stored in the variable .

3. Identifiers and keywords

In computer programming languages , identifier ( Or variables ) Is the name used by the user when programming , Used to give variables 、 Constant 、 function 、 Statement block and so on , To establish a relationship between the name and the use .

  1. Identifiers are made up of letters 、 Underline and numbers make up ($ And so on ), And Cannot start with a number .

  2. Case sensitive .

  3. Out of commission keyword .

3.1 Naming specification

  • Identifier naming should be as the name suggests .

Make a meaningful name , Try to see what it means at a glance ( Improve code availability Readability ) such as : name It's defined as name , Define what students use student

# The correct sample 
name = " Zhang San "
age = 18
# Wrong naming 
a = " Zhang San "
b = 18
  • Follow certain naming conventions .
    • Hump nomenclature , It is also divided into large hump naming method and small hump naming method .

1) Little hump nomenclature (lower camel case): The first word begins with a lowercase letter ; The first letter of the second word is capitalized , for example :myName、aDog

2) Big hump nomenclature (upper camel case): The first letter of each word is capital , for example :FirstName、LastName.

3) Another naming method is to underline “_” To connect all the words , such as send_buf.

​ Python The command rules of follow PEP8 standard

3.2 keyword

  • The concept of keywords

Some identifiers with special functions , This is the so-called keyword .

keyword , Has been python Official use of , Therefore, developers are not allowed to define identifiers with the same name as keywords .

  • keyword
False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield

4. Type conversion

function explain explain int(x) take x Convert to an integer float(x) take x Convert to a floating point number str(x) Put the object x Convert to string bool(x) Put the object x Convert to Boolean

Convert to an integer

print(int("123")) # 123 Convert a string to an integer 
print(int(123.78)) # 123 Convert an integer to a floating point number 
print(int(True)) # 1 Boolean value True Converting to an integer is 1 
print(int(False)) # 0 Boolean value False Converting to an integer is 0 
# The conversion will fail in the following two cases 
''' 123.456 and 12ab character string , Both contain illegal characters , Cannot be converted to an integer , Will report a mistake print(int("123.456")) print(int("12ab")) '''

Convert to floating point number

f1 = float("12.34")
print(f1) # 12.34 
print(type(f1)) # float Will string "12.34" Convert to floating point number 12.34 
f2 = float(23)
print(f2) # 23.0 
print(type(f2)) # float Convert an integer to a floating point number 

Convert to string

str1 = str(45)
str2 = str(34.56)
str3 = str(True) #True
print(type(str1),type(str2),type(str3))

Convert to Boolean

print(bool(1)) #True, Not 0 All the integers of are True
print(bool(' ')) #True, So is the space True
print(bool(0.1)) #True, Not 0 All floating-point numbers are True
# The following situations are False
print(bool(0)) #False
print(bool(0.0)) #False
print(bool('')) #False, All strings without content are False
print(bool("")) #False
print(bool({
})) #False, As long as there is data in the dictionary , Cast to bool, Just go back to True
print(bool([])) #False, As long as there is data in the list , Cast to bool, Just go back to True
print(bool(())) #False As long as there is data in the tuple , Cast to bool, Just go back to True
tuple1 = (0)
print(bool(tuple1)) #False
tuple2 = (0, 0)
print(bool(tuple)) #True

5. Operator

5.1 Arithmetic operator

With a=10 ,b=20 For example, calculate

Operator describe example + Add Add two objects a + b Output results 30- reduce Get a negative number or a number minus another number a - b Output results -10* ride Multiply two numbers or return a string repeated several times a * b Output results 200/ except b / a Output results 2// Divide and conquer Returns the integer part of the quotient 9//2 Output results 4 , 9.0//2.0 Output results 4.0% Remainder Returns the remainder of the Division b % a Output results 0** Index ( power )a**b by 10 Of 20 Power () parentheses Increase operation priority , such as : (1+2) * 3

Be careful : In mixed operation , The priority order is : ** higher than * / % // higher than + - , To avoid ambiguity , It is recommended to use () To handle shipping

Operator priority . also , When different types of numbers are mixed , Integers will be converted to floating-point numbers for operation .

>>> 10 + 5.5 * 2
21.0
>>> (10 + 5.5) * 2
31.0

5.2 The use of arithmetic operators in strings

Be careful : stay python in , + You can splice strings only when both ends are strings , Data that is not a string type can be passed through str() Strong to string , Splicing again

Multiplication of strings , Is how many times the string is repeated

print('11' + '22') #1122
print(' hello world' * 3) # hello world hello world hello world

5.3 Assignment operator

Operator describe example = Assignment operator hold = The result to the right of the number Assign to The variable on the left , Such as num = 1 + 2 * 3, result num The value of is 7
# Assign values to multiple variables at the same time ( Use the equal sign to connect ) 
>>> a = b = 4
>>> a
4
>>> b
4
>>> # Multiple variable assignments ( Separated by commas ) 
>>> num1, f1, str1 = 100, 3.14, "hello"
>>> num1
100
>>> f1
3.14
>>> str1
"hello"

5.4 Compound assignment operator

Operator ** describe ** example += Addition assignment operator c += a Equivalent to c = c + a-= Subtraction assignment operator c -= a Equivalent to c = c - a*= Multiplication assignment operator c *= a Equivalent to c = c * a/= Division assignment operator c /= a Equivalent to c = c / a//= Integer division assignment operator c //= a Equivalent to c = c // a%= Modulo assignment operator ( Remainder , Modular remainder )c %= a Equivalent to c = c % a**= Power assignment operator c **= a Equivalent to c = c ** a
# Example :+= 
>>> a = 100
>>> a += 1 # Equivalent to execution a = a + 1 
>>> a
101
# Example :*=
>>> a = 100
>>> a *= 2 # Equivalent to execution a = a * 2 
>>> a
200
# Example :*=, Operation time , The expression to the right of the symbol calculates the result first , And then with the value of the variable on the left 
>>> a = 100
>>> a *= 1 + 2 # Equivalent to execution a = a * (1+2) 
>>> a
300

5.5 Comparison operator

The following hypothetical variables a by 10, Variable b by 20:

Operator describe Example == be equal to : Compare objects for equality ( Also called identity )(a == b) return False!= It's not equal to : Compare two objects for inequality (python2 in <> The representative is not equal to )(a != b) return True> Greater than : return x Is it greater than y(a > b) return False>= Greater than or equal to : return x Greater than or equal to y(a >= b) return False< Less than : return x Is less than y. All comparison operators return 1 Said really , return 0 Said the false . This is different from special variables True And False Equivalent (a < b) return True<= Less than or equal to : return x Less than or equal to y(a <= b) return True

5.6 Logical operators

operation meaning Logical expression describe example and And x and y As long as one operand is False, The result is False; Only all operands are True when , The result is True When doing value calculation , Take the first as False Value , If all the values All for True, Take the last value True and True and False–> The result is False True and True and True–> The result is Trueor or x or y As long as one operand is True, The result is True; Only all operands are False when , The result is False When doing value calculation , Take the first as True Value , If all the values are by False, Take the last value False or False or True–> junction Fruit True False or False or False–> junction Fruit Falsenot Not 、 Take the opposite not x Boolean " Not " - If x by True, return False . If x by False, It returns True.not True --> False

Performance improvement

Interview questions : What is the output of the code , Why is there such an output .

a = 34
a > 10 and print('hello world') # Output 
a < 10 and print('hello world') # No output 
a >10 or print(' Hello world ') # No output 
a <10 or print(' Hello world ') # Output 

reflection :

  1. Short circuit problem of logic operation

    • When and In front of is False Under the circumstances , Then the following code will not execute
    • or: As long as one side True, So the result is True
  2. Why is the rule when logic and operation and logic or operation take value .
    and and or Short circuit effect

6. Input and output

6.1 Output

age = 10
print(" I this year %d year " % age)
name = " Zhang San "
print(" My name is %s, Age is %d" % (name, age))

6.2 Input

stay Python in , The way to get the data input by keyboard is to use input function

password = input(" Please input a password :")
print(' The password you just entered is :%s' % password)

Be careful :

  • input() What is put in the parentheses of is the prompt information , A simple tip for users before getting data

  • input() After getting the data from the keyboard , It will be stored in the variable to the right of the equal sign

  • input() Any value entered by the user will be treated as a string

7. Flow control statement

7.1 if Judgment statement

if Sentences are used to make judgments , Its use format is as follows :

if The conditions to judge :
When conditions are met , What to do
# Example 
if age >= 18:
print(" I'm an adult ")

A small summary :

  • if The function of the judgment : That is, when you meet a certain Condition to execute the code block statement , Otherwise, code block statements are not executed .

  • Be careful :if The next line of code is indented with a tab key , perhaps 4 A space .PyCharm Can press Ctrl + Alt + L Direct format code

7.2 if else

if-else The use format of

if Conditions :
The operation when the condition is satisfied
else:
Operation when conditions are not met
age = 18
if age >= 18:
print(" You are an adult ")
else:
print(" You're a minor ")
age = int(input(" Please enter age :"))
if age >= 18:
print(" You are an adult ")
else:
print(" minors ")

7.3 elif

elif The function of

if xxx1:
Thing 1
elif xxx2:
Thing 2
elif xxx3:
Thing 3

explain :

  • When xxx1 When satisfied , Do something 1, And then the whole if end

  • When xxx1 When not satisfied , So judge xxx2, If xxx2 Satisfy , Then do something 2, And then the whole if end

  • When xxx1 When not satisfied ,xxx2 Not satisfied , If xxx3 Satisfy , Then do something 3, And then the whole if end

Example :

score = int(input(" Please enter the score "))
if score >= 90:
print(" good ")
elif score >= 80:
print(" good ")
elif score > 60:
print(" pass ")
else:
print(" fail, ")

7.4 for

stay Python in for Loop can traverse any sequence of items , Such as a list or a string .

fo The format of the loop

for Temporary variable in Iteratable objects such as lists or strings :
Code executed when the loop meets the conditions

for The use of recycling

7.4.1 Traversal string :

for s in "hello":
print(s)

7.4.2 range

range Can generate numbers for for Loop traversal , It can pass three parameters , respectively start 、 End and step .

  • Print digit
for i in range(5):
print(i)

7.4.3 Loop list

a_list = [' Zhang San ', ' Li Si ', ' Wang Wu ']
for i in a_list:
print(i)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved