"Python from entry to practice" reading notes-Chapter 2 variables and simple data types

"Python from entry to practice" reading notes-Chapter 2 variables and simple data types

Variable rules

  • Variable names can only contain letters, numbers and underscores. Variable names can start with letters or underscores, but cannot start with numbers. For example, you can name the variable message_1, but you cannot name the variable 1_message.
  • Variable names cannot contain spaces, but underscores can be used to separate words. For example, the variable name greeting_message works, but the variable name greeting message will cause an error.
  • Do not use Python keywords and function names as variable names, that is, do not use words reserved by Python for special purposes, such as print.
  • Variable names should be short and descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name.
  • Be careful with the lowercase letter l and uppercase letter O, because they may be mistaken for the numbers 1 and 0.

Variables are labels that can be assigned to values

String

A string is a series of characters. In Python, all quotation marks are strings. The quotation marks can be single or double quotation marks.

“This is a string."
'This is also a string.'

This flexibility allows you to include quotes and apostrophes in strings:

'I told my friend , "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community"

Use method to modify the case of a string

name = "ada lovelace"
print(name.title())

Output Ada Lovelace

In the function call print(), the methodtitle() appears after this variable. Methods are operations that Python can perform on data. In the name.title()latter, name a period (.) So that Python title () method to perform the specified action on the variable name. Each method is followed by a pair of parentheses, because methods usually require additional information to complete their work. This information is provided in parentheses. The function title() does not require additional information, so the parentheses after it are empty.
The method of title()displaying each word in uppercase first letter of the way, is about the first letter of each word to uppercase. This is useful because you often need to treat names as information. For example, you might want the program to treat the values ​​Ada, ADA, and ada as the same name and display them all as Ada.
There are several other useful capitalization processing methods.

name = "Ada Lovelace"
print(name.upper())
print(name.lower())

Output

ADA LOVELACE
ada lovelace

When storing data, the method lower()is useful. In many cases, you cannot rely on the user to provide the correct case, so you need to convert strings to lower case before storing them. When you need to display this information in the future, convert it to the most appropriate case.

Use variables in the string (f string is quoted in 3.6, before using the method format ())

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)

Output

ada lovelace

To insert the value of a variable in a string, add a letter before the quotation mark f, and then put the variable to be inserted in curly braces. This way, when Python displays the string, it will replace each variable with its value.
This kind of string is called f string . f is short for format, because Python sets the format of the string by replacing the variable in the curly braces with its value.
Many tasks can be accomplished using f-strings, such as using information associated with variables to create complete information, as shown below:

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello,{full_name.title()}!")

Output

Hello,Ada Lovelace!

You can also use the f string to create a message, and then assign the entire message to a variable:

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
message = f"Hello,{full_name.title()}!"
print(message)

Use tabs or newlines to add whitespace

Tabs \t

>>> print("Python")
Python
>>> print("\tPython")
        Python 

Newline \n

>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript

Can contain both

>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
        Python
        C
        JavaScript

Delete blank

Whitespace is important.'python' and'python' are two different strings.
Fortunately, Python can find the extra whitespace at the beginning and end of the string
rstrip()

>>> favorite_language = 'python   '
>>> favorite_language
'python   '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python   '

There is extra white space at the end of the string associated with the variable favorite_language. Calls rstrip()later, the extra spaces are removed, however, this is only temporary deletion, the next time again asked, still including the extra white space.
To permanently delete the blanks in this string, you must associate the result of the delete operation to a variable:

>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
'python'

Similar excluding beginning of a string of blank lstrip()simultaneously remove both sides of the blank string strip()
in the actual program, the most commonly used functions be removed before cleaning storing user input.

Avoid syntax errors when using strings

When the program contains illegal Python code, it will cause syntax errors. For example, if an apostrophe is included in a string enclosed in single quotes, it will cause an error. This is because this will cause Python to treat the content between the first single quotation mark and the apostrophe as a string, and then treat the remaining text as Python code, causing an error.

#ex2-4
first_name = 'lao'
last_name = 'wang'
print("小写表示")
print(f"{first_name.lower()} {last_name.lower()}")
print("大写表示")
print(f"{first_name.upper()} {last_name.upper()}")
print("首字母大写")
print(f"{first_name.title()} {last_name.title()}")
#ex-2-6
famous_person = "Albert"
message = '"A personn who never made a mistake never tried anything new."'
print(f'{famous_person} said {message}')
#2-7
name = " Bill "
print(name.rstrip().lstrip())
print(name.strip())

summary:

  • Methods are operations that Python can perform on data. In name.title(), the period (.) after name allows Python to perform the operation specified by title() on the variable name
  • The method of title()displaying each word in uppercase first letter of the way
  • upper() Change the string to all uppercase
  • lower() Change the string to all lowercase
  • f string
    • To insert the value of a variable in a string, add the letter f in front of the quotation mark, and then put the variable to be inserted in curly braces. This way, when Python displays the string, it will replace each variable with its value.
  • Add tabs in the string \tnewline character\n
  • Delete blank rstrip() lstrip() strip()

number

Integer

  • It can perform addition (+) subtraction (-) multiplication (*) division (/) operations on integers.
  • Use two multiplication signs for exponentiation
>>> 3 ** 2
9
  • White space does not affect the way the expression is calculated

Floating point

Python all number with a decimal point called floating-point numbers .

  • The number of decimal places included in the result may be uncertain
>>> 0.2 + 0.1
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004

Integer and floating point

  • When dividing any two numbers , the result is always a floating-point number, even if the two numbers are both integers and divisible:
>>> 4/2
2.0
  • In any other operation, if one operand is an integer and the other operand is a floating-point number, the result is always a floating-point number.
    • No matter what kind of operation, as long as the operand is a floating point number, Python will always get a floating point number by default, even if it is an integer.

Underscore in number

  • When writing large numbers, you can use underscores to group the numbers to make them more legible:
>>> universe_age = 14_000_000_000
  • When you print the number defined with underscores, Python will not print the underscores:
>>> print(universe_age)
14000000000
  • When storing such numbers, Python will ignore the underscore in them. This representation method is suitable for integers and floating-point numbers, but only supported by Python 3.6 and higher.

Assign values ​​to multiple variables at the same time

x,y,z=0,0,0

constant

  • Constants are similar to variables, but their value remains the same throughout the life of the program. Python had no built-in constants type, but Python programmers will use all uppercase to indicate that a variable should be treated as a constant, and its value should always be the same.
MAX_CONNECTIONS = 5000
  • In the code, it is necessary to point out that a particular constant should be treated as a variable, and its letters can be all capitalized.

Comment

  • In Python, comments are marked with a pound sign (#)
#向大家问好
print("Hello Python people!")

What kind of comment should be written

  • The main purpose of writing comments is to explain what the code does and how it does it.
  • Ask yourself: Have you considered multiple solutions before finding a reasonable solution? If the answer is yes, write a comment to explain your solution. It is much easier to delete redundant comments than to add comments afterwards.

Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Guess you like

Origin blog.csdn.net/qq_31714533/article/details/109269344