current position:Home>[Python] variables, comments, basic data types

[Python] variables, comments, basic data types

2022-02-01 22:42:07 Love nuggets, love learning

install python Running environment

 install python Interpreter    install pyCharm development tool 
 notes : If there's a problem with these two steps , Can be in CSDN Search inside , With many tutorials )
 Copy code 

Print Hello world

Interactive command line

  1. The input terminal python Access to python Interactive command line ;
  2. Next, you can enter python Code :print("Hello world")

The terminal runs the script

  1. Use vs code To write python Script , Input python Code :print("Hello world"), Save as test.py file , be-all python File suffixes are py;
  2. Terminal execution python Script , Input python file name ;

Variables and comments

Variable

The meaning of the variable

  1. Extract variables , Use the same variable in multiple places , If you want to change the variable value, you only need to change one place , Easy to maintain code ;
  2. Variables can change dynamically , For example, there is a variable to store student information , The student may change his name or add new students , At this time, we need some methods of variables to meet the requirements of the program ;
name=" Zhang San "
age=18
print(name)		#  Zhang San 
print(age)		# 18

# Multivariable assignment is more concise 
name,age=" Zhang San ",18
print(name)		#  Zhang San 
print(age)		# 18

 Copy code 

Variable naming rule

  1. Variable names can contain Letter 、 Numbers and underscores , But don't start with a number ;
  2. Variable names cannot contain spaces ;
  3. Variable name cannot be the same as keyword name ;

keyword

Changes in variable values

a = 1
a = " Zhang San "
print(a)		#  Zhang San 
 Copy code 

notes

Single-line comments

# The content code of the comment will not execute 
 Copy code 

Multiline comment

# Single quotes and multi line comments 
'''  The first line notes   Second line of notes   wait  '''
# Double quotes and multi line comments 
"""  The first line notes   Second line of notes   wait  """
 Copy code 

Common data types
View data type :type function

Numeric type

integer int
Number without decimal point , Such as -1,2,3...

floating-point float
A number with a decimal point , Such as 1.0,-2.2...

Numerical calculation

Add +

reduce -

** ride ***

except /、//、%
/: division , Get decimal

//: Take business

%: Take the remainder

** Power ****

character string

# String with single quotation marks 
' Zhang San asked Li Si :" What's your name? ?"'
# String with double quotation marks 
" Zhang San asked Li Si :' What's your name? ?'"

# String splicing 
name = " Zhang San "
hobit = " Love football "
print(name + hobit)		#  Zhang Sanai football 

# String length 
len(name)			# 2

 Copy code 

Number to string conversion

a = 2
b = "10"
d = "10.1"
#  The string d Convert to float
e = float(d)
print(type(e))                          # <class 'float'>
# int(b)  Convert string to int
print(a+int(b)) 			# 12
# str(a)  Convert numbers to strings 
print(str(a)+b) 			# 210

 Copy code 

Special characters

# \n Line break 
str = " full name \n Zhang San "
print(str)                           #  full name 
                                        Zhang San 
                                      
# \t Indent  
str = " full name \t Zhang San "
print(str)                           #  full name   Zhang San 

 Copy code 

Indexes

# Positive index  01234
  str = "Hello"
# Negative index  -5-4-3-2-1
# Take the last character :str[-1]
print(str[-1])			# o

 Copy code 

section

str = "Hello world"
# [ The starting position : Final position : step ],  In steps of 1 Don't write 
str[0:4:2]   
str3=" Zhang San is playing "
# str3 Index from 0 To 3,4 It doesn't contain , In steps of 2
print(str3[0:4:2])			#  Zhang Zai 


#  Take the first to 5 individual 
#  Left inclusion , Right does not contain 
print(str[0:5]) 		# Hello
# str[ Starting index : Terminate index +1: step ]  Step size is like climbing stairs , If 1 It can be omitted , Step by step at a time , If 2, Every time to climb 2 Stairs 
print(str[::2])			# Hlo
print(str[0:11:2])		# Hlo
#  take o w
print(str[4:7:1])		# o w
print(str[4:7])			# o w

 Copy code 

String method

String search

str = "hello world"
# find The method has been found , Returns the index of the first element 
print(str.find("hello"))        # 0

# find Method can't find , return :-1
print(str.find("111"))          # -1

# find Is the index of the first element returned 
print(str.find("l"))            # 2

# rfind Is the index of the last element returned 
print(str.rfind("l"))           # 9

# index Is the index of the first element returned 
print(str.index("l"))           # 2

# rindex Is the index of the last element returned 
print(str.rindex("l"))          # 9 

# index If the method is not found, it will throw the wrong 
print(str.index("112"))         # SyntaxError: invalid syntax

#  Count the number of times 
print(str.count("l"))           # 3

 Copy code 

String substitution

str = "hello world"
# replace( String to replace , New string after replacement ), Returns a new string , Not in the original string 
str1 = str.replace("l","L")  
print(str1)        # heLLo worLd

 Copy code 

String delimitation

str = "hello wor ld"
#  Go to find out if there is... In the string " ", eureka ,  Remove the blanks , Put the cut elements in the list 
a = str.split(" ")
print(a)                # ['hello', 'wor', 'ld']

names = " Zhang San ; Li Si ; Wang Wu "
#  Go to find out if there is... In the string ";", eureka ,  hold ";" Get rid of , Put the cut elements in the list 
nameList = names.split(";")
print(nameList)         # [' Zhang San ', ' Li Si ', ' Wang Wu ']
#  Go to find out if there is... In the string 1, Can't find , Put the whole string into the list 
nameList1 = names.split("1")
print(nameList1)        # [' Zhang San ; Li Si ; Wang Wu ']

str = "hello world"
#  Go to the string to find the separator "o",  Find the first element to appear , Take all the elements to the left of the separator as the first element , The separator itself acts as the second element , The to the right of the separator is the third element 
str1 = str.partition("o")
print(str1)             # ('hell', 'o', ' wor ld')
#  Go to the string to find the separator "lll", Can't find , Take the whole string as the first element , The last two elements are empty strings 
str2 = str.partition("lll") 
print(str2)             # ('hello world', '', '')

 Copy code 

The first letter of the string is capitalized

str = "hello world"
str1 = str.capitalize()
print(str1)             # Hello world

 Copy code 

Each word in the string is capitalized

str = "hello world"
str2 = str.title()
print(str2)             # Hello World

 Copy code 

Determine whether a string begins or ends with a string , The result returned is bool type :True/False

str = "hello world"
print(str.startswith("hello"))          # True
print(str.startswith("hello1"))             # False
print(str.endswith("d"))                # True
print(str.endswith("l"))                    # False

 Copy code 

Convert all strings to case

str = "hello world"
str1 = str.upper()
print(str1)             # HELLO WORLD
str = "HELLO WORLD"
str1 = str.lower()
print(str1)             # hello world

 Copy code 

String to remove specific characters , Remove specific characters on both sides , The middle one won't get rid of

str = "00000003210Runoob01230000000"
#  Remove the strings at the beginning and end 
print(str.strip("0"))           # 3210Runoob0123
#  Remove the string on the left 
print(str.lstrip("0"))          # 3210Runoob01230000000
#  Remove the string on the right 
print(str.rstrip("0"))          # 00000003210Runoob0123

###  The middle string cannot be removed 
print(str.strip("R"))           # 00000003210Runoob01230000000
 Copy code 

String type judgment

str = "helloworld1232"
#  Judge whether it's a number , If the string contains only numbers , Then return to  True. conversely , Then return to  False
print(str.isdigit())        # False
#  Decide if it's a letter , If the string contains only letters , Then return to  True.  conversely , Then return to  False
print(str.isalpha())        # False
#  Determine whether numbers or letters , If there is at least one character in the string and all characters are letters or numbers , Then return to  True. conversely , Then return to  False
print(str.isalnum())        # True

spa = " "
#  Determine whether the string is a space , If the string contains only spaces , Then return to True. conversely , Then return to  False
print(spa.isspace())        # True

 Copy code 

String splicing of elements in the list

#  String splicing of elements in the list 
a = [" Zhang San "," Li Si "," Wang Wu "]
str = "he".join(a)
print(str)              #  Zhang San he Li Si he Wang Wu 
 Copy code 

Boolean expression

a = 1
b = 2
print(1 == 1)           # True
print(1>2)              # False
print(a == 1 and b == 2)        # True

# and To express and , On both sides true It's just true
print(a == 2 and b == 2)        # False
# or Represents or , As long as one on both sides is true, Namely true
print(a == 2 or b == 2)         # True
# != Means not equal to 
print(a != 2)           # True
 Copy code 

The input from the client is of string type

num = input(" Please enter a number :")
print(type(num))			# <class 'str'>
# Convert string to int: int(num)
print(type(int(num)))		# <class 'int'>
 Copy code 

copyright notice
author[Love nuggets, love learning],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202012242040837.html

Random recommended