Variables, strings, numbers, comments in python

Posted by jdubwelch on Fri, 24 Dec 2021 19:24:03 +0100

1, Variable

A variable is a label that can be assigned to a value (a variable points to a specific value)

message="I really miss you."
print(message)
I really miss you.

Message is a variable, and each variable points to a value. The value pointed to is the text "I really miss you." After adding the variable, the python interpreter will match the variable message with the text "I really miss you." Then print the value associated with message to the screen.

message="I really miss you."
print(message)
message="But I deeply love you!"
print(message)
I really miss you.
But I deeply love you!

The value of the variable can be modified at any time, and python will always record the latest value of the variable.

Variable naming rules: it can only be composed of letters, underscores (instead of spaces) and numbers (can not start); it is short and descriptive; try not to appear i and O (easy to be confused with 1 and 0); do not use python keyword and built-in function as variable name (keyword as variable name will cause errors, and built-in function as variable name will overwrite function behavior)

message="I really miss you."
print(mesage)

Traceback (most recent call last):
  File "F:\python_work\simple_message.py", line 2, in <module>
    print(mesage)
NameError: name 'mesage' is not defined

A traceback is a record of where a program gets stuck when it runs. Line 1: where is the error, line 2: list the specific code, and line 3: indicate what error

Name error NameError main reason: 1 Forget to assign a value to a variable before using it. 2. The spelling of variable name is incorrect

2, String

A string is a series of characters. The string should be enclosed in quotation marks, including "" and ''.

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

'I told my friend,"This is a string"'

1. String case processing

title(): capitalize the first letter of each word in the string (ADA, ADA and ADA are regarded as the same person and expressed as Ada)

upper(): change the string to all uppercase

lower(): change the string to all lowercase (you can't rely on the user to provide correct case, so all strings are changed to lowercase storage)

The print(name.title()) method is an operation that python can perform on data

.: Let python perform the operation specified by the method title () on the variable name

title(): the method is followed by a pair of parentheses (), because the method usually needs additional information to complete its work. This information is provided in (), and the function title() does not need additional information, so the parentheses are empty

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

Ada Lovelace

name='ada lovelace'
print(name.upper())

ADA LOVELACE

name='ada lovelace'
print(name.lower())

ada lovelace

2. Use variables in strings (f strings)

Add the letter F before the quotation mark "/ 'and put the variable to be inserted into the curly bracket {} f is the abbreviation of format. python formats the string by replacing the variable in {} with its value. It is only feasible if the string is above version 3.6

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

Ana lovelace

Use the f string {to create a complete message using the information associated with the variable

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

Hello! Ana Lovelace

python recognizes that print() will display the contents in (). There can be only variable names in () and other contents can be added by using f string, and then {} introduces variables. There can be mathematical operations and strings

Create a message with the f string and assign the whole message to the variable

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

Hello! Ana Lovelace

3. Add tabs or line breaks to the string to add white space

Tab \ tthe blank space generally refers to any nonprinting character, such as space, tab, and newline

Newline character \ n (wrap the output) \ t\n can be used at the same time for easier reading

print("python")
print("\t python")
print("message:\npython\n\tlike\n\t\tme")

python
	 python
message:
python
	like
		me

4. Delete redundant whitespace in the string (strip function)

Eliminate whitespace at the end of string {method rstrip()

Eliminate whitespace at the beginning of a string. lstrip() method

Eliminate whitespace at both ends of the string} method strip()

To permanently delete whitespace in this string, you must associate the result of the delete operation with a variable

>>> favorite_language='  python'
>>> favorite_language.lstrip()
'python'
>>> favorite_language
'  python'
>>>
>>> favorite_language=' python '
>>> favorite_language=favorite_language.strip()
>>> favorite_language
'python'

4. Syntax errors in strings

To correctly use single quotation marks and double quotation marks, if an apostrophe is included in a single quotation mark, python will treat the first single quotation mark and the apostrophe as a string. Python's syntax highlighting function can identify some syntax errors

message="One of the python's strength id diverse community."
print(message)
One of the python's strength id diverse community.

message='One of the python's strength id diverse community.'
print(message)
  File "F:\python_work\apostrophe.py", line 1
    message='One of the python's strength id diverse community.'
                               ^
SyntaxError: invalid syntax

3, Count

1. Integer

You can add (+), subtract (-), multiply (*) and divide (/) integers. The power (* *) also supports the operation order. You can use parentheses () to modify the operation order

>>> 6+2
8
>>> 6-2
4
>>> 6*2
12
>>> 6**2
36
>>> 6/2
3.0
>>> 6+2.0
8.0

>>> universe_age=14_000_000_000
>>> print(universe_age)
14000000000

>>> x,y,z=0,0,0

>>> MAX_CONNECTIONS=500

 2. Floating point number

Floating point number: a number with a decimal point. When any two numbers are divided, one is an integer and the other is a floating point number. The result is a floating point number

3. Underline in number

For reading convenience, underline is often added to large numbers, but python will not print underline because it will be ignored when storing such numbers

4. Assign values to multiple variables at the same time

It helps to shorten the program, assign a series of numbers to a group of variables, and separate the variables and values with commas. As long as the number of variables and values is the same, python can correctly associate them.

5. Constant

Similar to variables, a variable is treated as a constant in all uppercase, and its value remains unchanged.

print(3+5)
print(10-2)
print(4*2)
print(16/2)

8
8
8
8.0

4, Notes (#)

When the program becomes larger and more complex, you can add notes to the program in natural language through notes. The notes in python are # explained, and the # contents will be automatically ignored by the python interpreter.

#Say hello to everyone
print('hello,lovely python people!')

hello,lovely python people!

Beautiful code

>>> import this

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!

Keyword: false; ture; import; break; except; and; continue; for; in; if; while; or; raise; class; finally; is; return; await; else; pass;   lambda; try; as; def; from; nonlocal; assert; del; global;   not; with; async; elif; yield

Built in function: abs() all() any() ascii() bin() bool() breakpoint() byte array() bytes() callable() chr() classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() eval() exec())       filter()     float()     format()  frozonset()     getattr()      globals()     hasattr()     harsh()     help()     hex()     id()     input()  int()     isinstance()     issubclass()     iter()     len()    list()     locals()     map()     max()  memoryview()     min()      next()     object()     oct()     open()     ord()    pow()    print()     property()     range()     repr()     reversed()    round()     set()     setattr()      slice()     sorted()     staticmethod()     str()     sum()     tuple()     type()    vars()     zip()     _ import_ ()

Topics: Python