Chapter 2 variables and simple data types

Run hello_ World PY

Last py indicates that this is a python program, so the editor will use the Python interpreter to run it.

variable

message = "Hello Python World!"
print(message)

The result will show Hello Python World!
and

message = "Hello Python World!"
print(message)
message = "Hello Python Crash Course world!"
print(message)

The results will be displayed

Hello Python World!
Hello Python Crash Course world!

From this, we can see that the value of a variable can be modified at any time in the program, and Python will always record the latest value of the variable.

Naming and use of variables

  • Variable names can only contain letters, numbers, and underscores. Variable names can start with letters or underscores, but not numbers. For example, you can name the variable message_1, but cannot be named 1_message.
  • Variable names cannot contain spaces. You can use underscores to separate words.
  • Do not use Python keywords and function names as variable names.
  • Variable names should be short and descriptive.
  • Use the lower case letter l and upper case letter O with caution, which may be mistaken for the numbers 1 and 0.

Avoid naming errors when using variables

message = "Hello Python Crash Course reader!"
print(mesage)

traceback is a record that indicates where the interpreter gets stuck trying to run the code
When we execute this python program, the following error occurs

Traceback (most recent call last):
1.  File "Error demonstration.py", line 2, in <module>
2.    print(mesage)
3.NameError: name 'mesage' is not defined

The interpreter indicates an error in the file demonstration The second line of py has an error (see 1); It lists this line of code to help you find errors quickly (see 2); It then points out in the third line what error you have made (see 3). Here is that the message we need to output is not defined, and Python cannot recognize the variable name you provide.

character string

In Python, strings are enclosed in quotation marks, which can be either single quotation marks or double quotation marks, as shown below:

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

This flexibility allows you to include quotation marks and apostrophes in strings

"I told my friend,"Python is my favorite language!"
"One of Python's strengths is its diverse and supportive community."

Use the method to change the case of a string

  • title(): display each word in uppercase
name = 'ada lovelace'
print(name.title())

The results of running this program are as follows:

Ada Lovelace
  • upper(): capitalize all strings

  • lower(): lower all strings

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

The results of running this program are as follows:

ADA LOVELACE
ada lovelace

Merge strings

Python uses the plus sign (+) to merge strings:

first_name = " ada"
last_name = "lovelace"
full_name = first_name+" "+last_name
print(full_name)
print("Hello,"+full_name.title()+"!") 

The output result is

ada lovelace
Hello, Ada Lovelace!

Use tabs or line breaks to add white space

  • Tab \t:
>>>print("Python")
Python
>>>print("\tPython")
	Python
  • Newline \n:
>>>print("Language:\nPython\nC\nJavascript")
Language:
Python
C
Javascript

Delete blank

In Python, you can use rstrip() to remove no whitespace at the end of a string:

>>>favorite_language = 'python '
>>>favorite_language
'python '
>>>favorite_language.rstrip()
'python'
>>>favorite_;language
'python '

It can be seen from the results that rstrip() only temporarily deletes the extra space. To permanently delete this space, you must save the result of the deletion operation back to the variable:

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

Delete the blanks at the beginning of the string with lstrip(), and delete the blanks at both ends of the string with strip():

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

This delete function is most commonly used to clean up user input before storing it

Avoid syntax errors when using strings

When writing a program. The syntax highlighting function of the editor can help you quickly find out some syntax errors.

print statement in Python2

>>>Python2.7
>>>print "Hello python world!"
Hello python world!

In Python2, it is not necessary to put the contents to be printed in brackets. Technically, print in Python3 is a function, so parentheses are essential.

number

In programming, numbers are often used to record scores, represent visual data, and store Web application information.

integer

  • Addition, subtraction, multiplication and division
>>>2 + 3
5
>>>5 - 4
1
>>>3 * 2
6
>>>3 / 2
1.5
  • Two multiplication signs are used in Python to represent the power operation
>>>3 ** 2'
9
  • You can use parentheses to change the order of operations in Python
>>>2 + 3 * 4
14
>>>(2 + 3) * 4
20

Floating point number

Numbers with decimal points are called floating-point numbers in Python. Floating point numbers are usually handled no differently than integers. However, it should be noted that the number of decimal places contained in the result may be uncertain:

>>>0.2 + 0.1
0.3000000000000004
>>>3 * 0.1
0.3000000000000004

All languages have this problem, so there is basically nothing to worry about.

Use str() to avoid type errors

For example, the following code:

age=23
message="Happy "+age+"rd birthday!"

print(message)

You thought it would show Happy 23rd birthday!
But the results will show

Traceback (most recent call last):
  File "str Error demonstration.py", line 2, in <module>
    message="Happy "+age+"rd birthday!"
TypeError: can only concatenate str (not "int") to str

This is a type error. Python found a variable with the value int, but it doesn't know how to interpret the value** Python knows that the value represented by this variable may be the number 23, or the characters 2 and 3** This is why we can use the function str() to convert non string values to Strings:

age=23
message="Happy "+str(age)+"rd birthday!"

print(message)

Finally, it will be displayed as Happy 23rd birthday!

Integer in Python2

In Python2, dividing two integers yields slightly different results:

>>>Python 2.7
>>>3 / 2
1

The above results occur because in Python2, the integer division only contains the integer part, and the decimal part is deleted.
To avoid this, make sure that at least one operand is a floating-point number:

>>>3 / 2
1
>>>3.0 / 2
1.5
>>>3 / 2.0
1.5

annotation

How to write notes

In python, comments are identified by \

# Say hello to everyone
print("Hello Python people!")

The result will show Hello Python people!, The first line is automatically ignored and only the second line is executed.

What kind of comments should be prepared

Clear and concise comments should be written in the code.

Python Zen

  1. Beautiful is better than ugly.
  2. Simple is better than complex.
  3. Complex is better than complicated
  4. Readability counts.
  5. There shuould be one–and preferably only one–obvious way to do it.
  6. Now is better than never.

Tags: Python Programming regex string

Posted by MarkR on Tue, 31 May 2022 08:16:16 +0530