Is 2 equal to 2.0 in python? [1:2] in python

This article will talk about whether 2 is equal to 2.0 in python, and [1:2] in python. I hope it will be helpful to you. Don’t forget to bookmark this site.

 

Variables and assignments

Variables in Python do not need to be declared, they can be defined directly. The "type" of the variable will be determined at the time of initialization.
Use = to perform initialization and assignment operations

When defining a variable, you don’t need to write the type. This type will be defined during initialization.
About; This can be written or not, it is recommended not to write.
Put the cursor below num and pi above will display the type of this variable

Regarding floating-point numbers, they are divided into float and double in C++ and java.
Python does not distinguish between float and double, and they are all regarded as float but double

num = 10
pi = 3.14
name = '张三'
num = 10
num += 1
print(num)
输出:11

Note: there is no ++ in python -
python sees ++ - as two plus and minus signs

num = 10 # This is a number
num = '10' # This is a string
, but such code can run
Reason:
Python is a dynamically typed language
, a variable can change its type during operation

C++ and jave are both static types.
Static code means that your code is written and the type is determined. During the running process, the type cannot change.

Variable naming
1. Numbers and letters are composed of underscores, numbers cannot start with
2. It is best to be familiar with the name

Extension: Can the variable name use pinyin?
In most cases, use English, and pinyin can be used as a last resort


Recognize 'Numbers'

Recognize "numbers"
Python does not have keywords such as int, float,
but in fact the type of numbers distinguishes types such as "int" and "float".
Use the built-in function type to view the type extension of variables
: built-in functions, The functions that come with python itself can be used without including other modules

num = 10
print(type(num))
output: <class 'int'>
class means class
Then: in python, a type like int is essentially an object

num = 10.0
float 

复数
num = 10 + 5j
print(type(num))
输出:<class 'complex'>

Extension: In python2, Chinese cannot be entered after the comment, and python can use
int in python, which is not only represented by four bytes, but an infinite number


string

Single quotes ('), double quotes ("), and triple quotes ('''/""") can be used in Python to represent strings. The differences between
these three strings will be discussed later

If the string content contains quotation marks, it can be used flexibly
name = 'zhangsan'
name = """hehe''' my name 'is' zhang "da" san'''hehe""" print
( name)
output: hehe''' my name 'is' zhang “da” san'''hehe

Extension: Built-in functions built
-in functions in python, you can directly use
1.print 2.type 3.len

Find the length of the string
name = 'abcdefg'
print(len(name))
output: 7
question Is there \0 in it?
After the C language, there is no such setting as \0 in any language

取下标
name = 'abcdef'
print(name[1])
输出:b

name = 'abcdef'
print(name[100])
输出:IndexError: string index out of range
索引器错误:字符串索引超出范围

name = 'abcdefg'
print(name[-1])
输出:g
下标为负数:想当于:len(name)负数

切片: slice
name = 'abcdefg'
print(name[1:3])
输出:bc
[]内容为:左闭右开区间,里 面的数字也可以为负数,
也可以省略:省略前面, 相当于从零开始,省略后面,相当于到最后结束

a = 'hello'
b = 'world'
print(a+b)
输出:helloworld

a = 'hello'
print(a*3)
输出:hellohellohello
数字在后,字符串在前

num = 10
a = 'num = %d' % num
print(a)
输出:num = 10
不推荐使用这种格式,这种格式容易写错

num = 10
a = 'num = {}'.format(num)
print(a)
输出:num = 10
也不太推荐使用这种方式,因为这种方式有点麻烦

num = 10
a = f'num = {num}'
print(a)
输出:num = 10
这种写法在现在很多情况下都有,
C++和java没有,其余大部分都有
这种写法在3.6以后才支持

Boolean type

True and False

a = True
print(True)
print(type(a))
输出:
True
<class 'bool'>在这里插入代码片

a = True
print(a+1)
在C++中True代表1,False代表0,python也一样
在java中这个写法不成立

input Output

a = 'name'
print(a)
输出:
name

print(a,end = '')
输出:name
但是我自己写的代码中,这两个都没有下一行,可以推断,这个新版本改了

输入:
s = input("请输入一个字符串:")
print("s: ",s)

错误示例
s = input("请输入一整数:")
print("result: ",s + 100)
输出:TypeError: can only concatenate str (not "int") to str
不能够把整数和字符串进行相加

修改:
s = input("请输入一整数:")
print("result: ",int(s) + 100)

note

The source code of Python only supports ASCII by default, so if you want to include Chinese, you need to indicate # - -coding: UTF-8 - - or #coding:utf8
at the beginning of the code file . This is only for python2, and python3 does not have this Question, can this be written or not?


operator

/ is "exact division"
print(1/2)
output: 0.5

// is "divisible". The result will be rounded
print(1//2)
output: 0

the rest are the same

** Indicates the power operation (remember that Python data has no upper limit)
print(2**3)
output: 8

Python also supports standard comparison operators.
< >= <= == != The result of the expression of these operators is a Boolean value

print(1<4<3)
is 1<4 in C++, so it returns 1, and then 1<3 is true, so it finally returns True.
In python, this directly returns False

Python also supports logical operators. and or not ----" && || !
The above code can be written as:
print(1<4 and 4<3)

You can use == != between strings to determine whether the contents of the strings are the same
print('haha' == 'hehe')

The size can also be compared between strings. The result of this size depends on the "lexicographical order" of the string
print('haha' > 'hehe')


list/tuple/dictionary

Lists and tuples are similar to arrays in C.
Use [] to represent lists and () to represent tuples.

The list list
is essentially our array, but there is no array in python

a = [9,5,2,7]
print(a[1])
print(a[-1])
print(a[1:-1])
print(len(a))

元组
a = (9,5,2,7)
print(a[1])
print(a[-1])
print(a[1:-1])
print(len(a))

区别:
a = [9,5,2,7]
a[0] = 100
print(a[0])
# 

b = (9,5,2,7)
b[0] = 100
print(b[0])
TypeError: 'tuple' object does not support item assignment
tuple这个元素不能被修改

Then: the list can be modified,
the tuple cannot be modified, only a new element object can be constructed

The elements in the list and the tuple are not necessarily of the same type
a = [9,'hehe',2,7]
this is also possible ----"dynamic type

dictionary:

A dictionary is a mapping data type in Python. It stores key-value pairs (key-value).
Almost all types of Python objects can be used as keys. However, numbers and strings are generally the most commonly used.
Use {} to represent a dictionary

This format is in json,
a = { 'ip':'127.0.0.1', 'port':80 } print(a['port']) # output: 80 bottom layer is essentially the hash table in the hash table The time complexity of finding an element is: O(1)






quote

You can use the built-in function id in Python to view the "address" of variables.
The reference in python is the same as in java,
and the difference with C++ is still quite big

id is also a built-in function that can check the identity of a variable
id is just an identity, it has nothing to do with the address
address: it has two meanings
1. identity: two things have the same address, it is the same thing
2 .The address also indicates where your object is stored in the memory?

a = 100
b = a
print(id(a))
print(id(b))
输出:
2048510350800
2048510350800
则证明:a和b 是同一个对象

Code Blocks and Indentation

Python uses indentation to indicate code blocks. It is equivalent to naturally specifying the code style from a grammatical point of view.
Python is unique in using indentation instead of {}, which avoids a partisan dispute


if statement

result = input("你会认真学习吗?1.会的 0.不会")
if result == '1':
    print('牛逼')
    print('继续努力')
elif result == '0':
    print('菜鸟')
else:
    print('输入错误')

switch statement doesn't have
do... while in python neither


while loop

The while loop statement is similar to the if statement syntax.
As long as the value of the expression is not 0 or True, do_something will be executed in a loop

打印0-9
num = 0
while num < 10:
    print(num)
    num+=1
输出:竖着打印0-9

for loop

Python's for is equivalent to C++ range based for
is equivalent to for each in JAVA

for num in range(0,10):
    print(num)
输出:打印0-9(竖着)
for 也可以遍历列表,元组,字典
a = [9,5,2,7]
for num in a:
    print(a)
输出:竖着打印0-9

字典:
a = {
    'ip':'127.0.0.1',
    'port':80
}
for key in a:
    print(key,a[key])
输出:
ip 127.0.0.1
port 80

Extension: What does the ip address of 127.0.0.1 mean?
Loopback IP, no matter what your own ip is, you can use this ip to access yourself

break,continue
打印0-10,遇见3的倍数就停下
for num in range(1,10):
    if num% 3 == 0:
        break
    print(num)
输出:
1
2

for num in range(1,10):
    if num% 3 == 0:
        continue
    print(num)
输出:1-8,没有3的倍数,(竖着打印)

pass statement

Indicates an empty statement
In order to indicate that our statement format can be correct

if x % 2 == 0:
    pass
else:
    do_something

List comprehensions (list comprehensions)

Requirements: Given a list, there are some numbers in the list, you need to transform the odd numbers in it
, and then generate a new list, for example, transform according to the power

#传统C语言思路
#append相当于C++中的push back
#就是插入到列表的最后
a = [1,2,3,4,5,6,7,8,9]
b = []
for num in a:
    if num % 2 == 0:
        continue
    num = num*num
    b.append(num)
print(b)
输出:[1, 9, 25, 49, 81]
python思路
a = [1,2,3,4,5,6,7,8,9]
b = [num ** 2 for num in a if num % 2 == 1]
print(b)
输出:[1, 9, 25, 49, 81]
这样的方式就叫做列表解析
我们可以通过一个表达式,通常是一个循环语句
来帮助我们生成一个新的列表

In C language, it is called a function, in Java, it is called a method.

函数
def add(x,y):
    result = x + y
    return result

print(add(1,2))
print(add('hello','world'))
输出:
3
helloworld

也可以这样
def add(x,y):
    if x > 0:
        return 'aaa'
    if x<0:
        return -1
    result = x + y
    return result

Function overloading
Both C++ and Java have function overloading
. The function name is the same, but the number of parameters is different, or the type is different.

def add(x,y):
    return x+y

def add(x,y,z):
    return x+y+z

print(add(10,20))
TypeError: add() missing 1 required positional argument: 'z'
add这个函数缺了一个参数 ’z'

It proves:
Python does not support function overloading,
when there are multiple functions with the same name, the latter overrides the former

The default parameters
are in C++, but not in java.

def add(x = 0,y = 0):
    return x+y

print(add(10))
print(add())
都可以
python中可以同时返回多个值
def get_point():
    x = 10
    y = 20
    return x,y

这种方式叫做:解包 unpack
x,y = get_point()
print(x,y)

如果不想要其中一个值可以:
_,y = get_point()

Functions are also "objects". A function, like a number or a string, can define an "alias" to refer to it.

def get_point():
    x = 10
    y = 20
    return x,y

print(type(get_point))
输出:<class 'function'>

Explanation: Its type is "<class 'function'>.
This function type means that this function can be used as a parameter of another function
or as a return value of another function.

We say that this function is also an object, then we can
get_point. to get some attributes in it


file operation

General steps:
1. Open file 2. Close file 3. Read file 4. Write file

Extension: The file is stored on the disk,
which means: the variables and objects that are usually operated are all in memory,
while our files are on the disk, that is, in external memory
. In contrast, we need to access variables Easier than accessing files,
which means better access in memory and more difficult in external storage
At this time, we often adopt a strategy to operate files,
first create a handle related to this file and then operate

File Open
If the file does not exist, the file will not be opened successfully
f = open("C:\Users\wyw15\Desktop\test.txt", "r")

Output:
FileNotFoundError: [Errno 2] No such file or directory:
“C:\Users\wyw15\Desktop\test.txt”
ie: this path does not exist

f = open("C:\Users\wyw15\Desktop\test.txt", "r")
f.close()
Let's create this file
Run: there will be no problem

After the file is opened, it must be closed in time after use.
If it is not closed in time, we will fail to open a new file.
C++: In our operating system kernel, there is a file description table in each process
. There is a hole in the file, but this table has an upper limit on the length
, so this hole cannot be dug infinitely, you can only close one and open another.
We call this problem: file descriptor leakage problem

When we don't write this # f.close() When the statement cycle of this file ends,
this file will be recycled, and when it is recycled, it will also be closed
But we can't count on it, because when it is closed, we can't close it manually

f = open("C:/Users/wyw15/Desktop/test.txt","r")

for line in f:
    print(line)

f.close()
输出:输出文件里面的内容,
但是每一行中间都有空行

Reason: Because when we read this file, the end of each line of this file contains \n
when we print, there will be an extra \n after print

解决:
f = open("C:/Users/wyw15/Desktop/test.txt","r")

for line in f:
    print(line,end = '')

f.close()
输出:正常输出

另外一种读文件
f = open("C:/Users/wyw15/Desktop/test.txt","r")
readlines返回的是一个列表
lines= f.readlines()
print(lines)

f.close()
输出:['hello\n', 'world\n', 'aaa\n', 'bbb\n', 'ccc\n', 'aaa\n', 'ccc\n', 'bbb']

写文件
f = open("C:/Users/wyw15/Desktop/test.txt","w")

f.write('hello world')

f.close()
打开外部文件,我们会发现这个文件里面就只剩下了 hello world

count word frequency in text

f = open("C:/Users/wyw15/Desktop/test.txt","r")

word_dirt = {}
for word in f:
    if word in word_dirt:
        word_dirt[word] += 1
    else:
        word_dirt[word] = 1

print(word_dirt)

f.close()
输出:{'hello\n': 1, 'world\n': 1, 'bbb\n': 1, 'ccc\n': 1, 'aaa\n': 1, 'bbb': 1}
问题:每个字符串后面都跟着一个\n,问如何去掉?
修改1:切片
f = open("C:/Users/wyw15/Desktop/test.txt","r")

word_dirt = {}
for word in f:
    word = word[:-1]
    if word in word_dirt:
        word_dirt[word] += 1
    else:
        word_dirt[word] = 1

print(word_dirt)

f.close()
输出:{'hello': 1, 'world': 1, 'bbb': 1, 'ccc': 1, 'aaa': 1, 'bb': 1}
不对,bb  bbb数据异常
修改二:
f = open("C:/Users/wyw15/Desktop/test.txt","r")

word_dirt = {}
for word in f:
    word = word.strip() # 去掉字符串两侧的空白字符
    print(word)
    if word in word_dirt:
        word_dirt[word] += 1
    else:
        word_dirt[word] = 1

print(word_dirt)
f.close()
输出:{'hello': 1, 'world': 1, 'bbb': 2, 'ccc': 1, 'aaa': 1}
延伸:空白字符:空格,tab 换行 垂直翻页符

module

When we have a large amount of code in a project, we need to put the code in multiple different .py files. We can
use the import keyword to refer to the code in other .py files.
The imported code file is called For "module".
The imported file, remove the .py suffix name, is the module name

The import here is not only the module name, but also the namespace. We know that function names cannot conflict, and if they are the same , calc
will be overwritten : calculate import calc print(calc.add(1,2))


For a module to be imported correctly, it must be placed in a suitable directory.
One is test.py and calc.py must be in the consent folder
or the system directory (python timer installation directory)

Guess you like

Origin blog.csdn.net/mynote/article/details/132178302