[Deep Learning] Python Quick Start

1. IPython and Jupyter Notebooks

Jupyter notebook is a web application that allows users to combine explanatory text, mathematical equations, code, and visualization content into an easy-to-share document, which is very convenient for research and teaching, and makes writing and reading clear at a glance. Jupyter notebook is especially suitable for scientific computing and data processing. Its uses can include data cleaning and exploration, visualization, machine learning and big data analysis. It has the following characteristics:

  • When programming, it has the functions of syntax highlighting, indentation, and tab completion;
  • The code can be run directly through the browser, and the running results are displayed below the code block;
  • Display calculation results in rich media formats, including: HTML, LaTeX, PNG, SVG, etc.;
  • When writing documentation or statements for code, Markdown syntax is supported;
  • Support for writing mathematical explanations using LaTeX.

1.1 Jupyter installation

The easiest way to install Jupyter is to use Anaconda, whose distribution comes with Jupyter Notebook. To install Jupyter Notebook in the conda environment, you can use:

conda install jupyter

Of course, it can also be installed via pip:

pip install jupyter

After installation, enter the following command in the terminal to start:

# jupyter notebook

或者
# jupyter-notebook

1.2 Jupyter common operations

insert image description here

2. Variables

A name used to represent something or a value is called a variable. In Python, variables can be declared and assigned values ​​as follows:

x = 2
y = 5
xy = 'Hey'
print(x+y, xy)
#输出:7 Hey

Multiple variables can be given the same name.

x = y = 1
print(x,y)
#输出:1 1

operator

3.1 Arithmetic operators

insert image description here

3.2 Relational Operators

insert image description here

3.3 Bitwise operators

insert image description here

4. Built-in functions

4.1 Numeric functions

The round( ) function rounds an input value to the specified number of digits or to the nearest integer.

print(round(5.6231))
print(round(4.55892, 2))
# 6
# 4.56

complex( ) is used to define a complex number abs( ) outputs the same absolute value.

c =complex('5+2j')
print(abs(c))
# 5.385164807134504

divmod(x,y) outputs the quotient and remainder in tuple format (quotient, remainder).

divmod(9,2)
# (4, 1)

isinstance( ) returns True if the first argument is an instance of this class. It is also possible to examine multiple classes at the same time.

print(isinstance(1, int))
print(isinstance(1.0,int))
print(isinstance(1.0,(int,float)))
# True
# False
# True

pow(x,y,z) can be used to find the power function xyx^yxy can also find the mod value of the third specified number, ie:(xyx^yxy % z)。

print(pow(3,3))
print(pow(3,3,5))
# 27
# 2

The range( ) function outputs an integer within the specified range. It can also be used to generate a sequence by specifying the difference between two numbers in a specific range, with the elements returned as a list.

print(list(range(3)))
print(list(range(2,9)))
print(list(range(2,27,8)))
# [0, 1, 2]
# [2, 3, 4, 5, 6, 7, 8]
# [2, 10, 18, 26]

4.2 User input

input( ) takes input and saves it as a string.

abc = input("Type something here and it will be stored in variable abc \t")
# Type something here and it will be stored in variable abc 	此处我们键入10

Check the type of 10 entered:

type(abc)
# str 字符串类型

4.3 Printout

print("Hello World")
# Hello World

In Python, single, double, and triple quotes are used to denote strings:

  • In most cases single quotes are used to declare a character;
  • Use double quotes when declaring a line and triple quotes when declaring paragraphs/multiple lines.
print('Hey')
a = 'line1\
line2\
\
'
print(a)

#Hey
#line1line2
print("""My name is Rajath Kumar M.P.

I love Python.""")

# My name is Rajath Kumar M.P.
# 
# I love Python.

String concatenation is the "addition" of two strings. Note that when concatenating, there will be no spaces between the strings:

print('Hello' + string1 + string2)
# HelloWorld!

4.4 Formatted output

- %s -> string
- %d -> Integer
- %f -> Float
- %o -> Octal
- %x -> Hexadecimal
- %e -> exponential

For conversion inside the print function itself:

print("Actual Number = %d" % 18)
print("Float of the number = %f" % 18)
print("Octal equivalent of the number = %o" % 18)
print("Hexadecimal equivalent of the number = %x" % 18)
print("Exponential equivalent of the number = %e" % 18)

# Actual Number = 18
# Float of the number = 18.000000
# Octal equivalent of the number = 22
# Hexadecimal equivalent of the number = 12
# Exponential equivalent of the number = 1.800000e+01

Use parentheses when referencing multiple variables:

print("Hello %s %s" % (string1,string2))
# Hello World !

5 data structures

5.1 List

Lists are the most commonly used data structures. Think of it as a sequence of data enclosed in square brackets, separated by commas. These data can all be accessed by calling their index values. The declaration of list only needs to equate the variable to [ ] or list.

a = []
print(type(a))
# <class 'list'>

A data sequence can be directly assigned to a list x as follows:

x = ['apple', 'orange', 'peach']
print(x)
# ['apple', 'orange', 'peach']

5.1.1 Index

In Python, indexing starts at 0. So now the two-element list x has an apple index of 0 and an orange index of 1.

x[0]
# 'apple'

Indexing can also be done in reverse order. This is the last element that can be accessed first. Here, the index starts from -1. So, index -1 corresponds to orange and index -2 corresponds to apple.

x[-1]
# 'peach'

Declare two lists x and y each containing its own data. Now these two lists can again be put into another list z which also has its own data. This list of lists is called a nested list, and this is how arrays are declared, as we'll see later. This is different from many other computer languages. It does not require the elements of the list to be of the same type, so it is very convenient when programming, which is why Python is more friendly to humans.

x = ['apple', 'orange', 'peach']
y = ['carrot','potato']
z  = [x,y, 'Test']
print(z)
# [['apple', 'orange', 'peach'], ['carrot', 'potato'], 'Test']

z[0][1]
# 'orange'

How to get an element in a nested list? Let's get the data 'apple' in the above nested list as an example:

  • First at index 0, there is a list ['apple','orange'] and at index 1 there is another list ['carrot','potato'] ;
  • So z[0] should give us the first list containing 'apple'.
z1 = z[0]
print(z1)
# ['apple', 'orange', 'peach']

Now observe that z1 is not a nested list, so to get 'apple', the index of z1 should be 0.

z1[0]
# 'apple'

In python, instead of doing the above, you can access "apple" by writing the index value side by side each time:

z[0][0]
# 'apple'

5.1.2 Slicing

Indexing is limited to accessing a single element, while slicing is accessing a sequence of data within a list. In other words, slicing returns a list.

Slicing is done by defining the index values ​​of the first and last elements (exclusive, i.e. left closed and right open) in the parent list that are required in the sliced ​​list. It is written as parentlist[a: b], where a, b are the index values ​​of the parent list. If a or b is undefined, the index value is considered to be the first value if a is undefined, and the last value if b is undefined.

num = [2,3,2,3,4,5,6,7,8,9]
print(num[1:4])
print(num[0:])
print(num[:])
print(num)

# [3, 2, 3]
# [2, 3, 2, 3, 4, 5, 6, 7, 8, 9]
# [2, 3, 2, 3, 4, 5, 6, 7, 8, 9]
# [2, 3, 2, 3, 4, 5, 6, 7, 8, 9]

print(num[0:4])
print(num[4:])

# [2, 3, 2, 3]
# [4, 5, 6, 7, 8, 9]

It is also possible to slice the parent list with a fixed length or stride:

num[:9:3]
# [2, 3, 6]

5.1.3 Built-in functions for lists

The length of a list or the number of elements in a list:

len(num)

min( ) and max( ) give the maximum and minimum values ​​in a list:

min(num)
max(num)

List concatenation:

[1,2,3] + [5,4,7]
# [1, 2, 3, 5, 4, 7]

Check if a specific element exists in a list:

names = ['Earth','Air','Fire','Water']
'Fir' in names
# False
'Fire' in names
# True
'fire' in names
# False

Strings converted to lists:

list('hello')
# ['h', 'e', 'l', 'l', 'o']

append( ) is used to add an element to the end of the list:

lst = [1,1,4,8,7]
lst.append(1)
print(lst)
# [1, 1, 4, 8, 7, 1]

count( ) counts the number of occurrences of a particular element in a list:

lst.count(1)
# 3

The append( ) function can also be used to append an entire list at the end:

lst1 = [5,4,2,8]
lst.append(lst1)
print(lst)
# [1, 1, 4, 8, 7, 1, [5, 4, 2, 8]]

List concatenation:

lst.extend(lst1)
print(lst)
[1, 1, 4, 8, 7, 1, [5, 4, 2, 8], 5, 4, 2, 8]

index( ) is used to find the index value of a particular element, note that if there are many elements with the same value then the first index value of the element will be returned:

lst.index(1)
# 0

insert(x,y) is used to insert element y at the specified index value x. The append( ) function makes it only insert at the end.

lst.insert(5, 'name')
print(lst)
# [1, 1, 4, 8, 7, 'name', 1, [5, 4, 2, 8], 5, 4, 2, 8]

The pop( ) function returns the last element in the list. This is similar to the operation of a stack. Therefore, it is correct to say that a list can be used as a stack.

lst.pop()

An index value can be specified to pop the element corresponding to that index value:

lst.pop(2)
print(lst)
# [1, 1, 8, 7, 'Python', 1, [5, 4, 2, 8], 5, 4, 2]

Use the remove() function to remove elements by value:

print(lst)
# [1, 1, 8, 7, 'Python', 1, 5]
lst.remove('Python')
print(lst)
# [1, 1, 8, 7, 1, 5]

The reverse() function reverses all occurrences of elements in a list:

print(lst)
# [1, 1, 5]
lst.reverse()
print(lst)
# [5, 1, 1]

sort( ) to sort elements in ascending order:

lst = [1, 4, 8, 8, 10]
lst.sort()
print(lst)
# [1, 4, 8, 8, 10]

For descending order because reverse condition is False by default. So changing it to True will sort the elements in descending order.

lst.sort(reverse=True)
print(lst)
# [10, 8, 8, 4, 1]

5.1.4

Most new python programmers make this mistake, the difference between assignment and copying of objects. Consider the following example:

lista= [2,1,4,3]
listb = lista # 对象赋值
print(listb)
# [2, 1, 4, 3]

Here, we declare a list, lista = [2,1,4,3]. Copy that list to listb via assignment, and copy that list. Now we perform some random operations on lista.

lista.pop()
print(lista)
# [2, 1, 4]
lista.append(9)
print(lista)
# [2, 1, 4, 9]
print(listb)
# [2, 1, 4, 9]

While nothing is done to listb, it is also changed. This is because you are pointing lista, listb to the same memory space.

Copy list :

lista = [2,1,4,3]
listb = lista[:]
print(listb)
# [2, 1, 4, 3]

lista.pop()
print(lista)
# [2, 1, 4]
lista.append(9)
print(lista)
# [2, 1, 4, 9]

print(listb)
# [2, 1, 4, 3]

5.2 Tuples

Tuples are similar to lists, but the only big difference is that elements in a list can be changed, while elements in a tuple cannot.

Define tuples:

tup = ()
tup2 = tuple()

Values ​​can be assigned when declaring a tuple. It takes a list as input and converts it to a tuple, or takes a string and converts it to a tuple:

tup3 = tuple([1,2,3])
print(tup3)
# (1, 2, 3)
tup4 = tuple('Hello')
print(tup4)
# ('H', 'e', 'l', 'l', 'o')

Tuples follow the same indexing and slicing as lists:

print(tup3[1])
# 2
tup5 = tup4[:3]
print(tup5)
# ('H', 'e', 'l')

5.2.1 Mapping a tuple to another tuple

(a,b,c)= ('alpha','beta','gamma')
print(a,b,c)
# alpha beta gamma

5.2.2 Tuple built-in functions

The count() function counts the number of specified elements present in the tuple:

d = tuple('RajathKumarMP')
print(d)
# ('R', 'a', 'j', 'a', 't', 'h', 'K', 'u', 'm', 'a', 'r', 'M', 'P')
d.count('a')
# 3

The index() function returns the index of the specified element. If the number of elements is greater than 1, returns the index of the first element of the specified element:

d.index('a')
# 1

5.3 Collection

Sets are mostly used to eliminate duplicate numbers in sequences/lists. It is also used to perform some standard set operations.

set is declared as set(), which initializes an empty set. set([sequence]) can also be executed to declare a set containing elements:

set1 = set()
set0 = set([1,2,2,3,3,4])
print(set0)
# {1, 2, 3, 4}

set1 = set((1,2,2,3,3,4))
print(set1)
# {1, 2, 3, 4}

Elements 2,3 repeated twice will only appear once. So in a set, every element is distinct.

5.3.1 Built-in functions

set1 = set([1,2,3])
set2 = set([2,3,4,5])

The union( ) function returns a union set that contains all elements of the two sets, but without duplicates:

set1.union(set2)
# {1, 2, 3, 4, 5}

add() will add a specific element to the collection:

print(set1)
# {0, 1, 2, 3}
set1.add(0)
print(set1)
# {0, 1, 2, 3}

The intersection( ) function outputs an intersection set that contains all the elements in both sets:

set1.intersection(set2)
# {2, 3}

The difference( ) function outputs a set containing elements that are in set1 but not in set2:

print(set1)
# {0, 1, 2, 3}
print(set2)
# {2, 3, 4, 5}
set1.difference(set2)
# {0, 1}

The remove( ) function removes an element of a specified value from a collection:

set1.remove(2)
print(set1)
# {1, 3}

clear( ) is used to clear all elements and set them to an empty set:

set1.clear()
print(set1)
# set()

5.4 Strings

Strings are text-based ordered data enclosed in single/double/triple quotes.

String0 = 'Taj Mahal is beautiful'
String1 = "Taj Mahal is beautiful"
String2 = '''Taj Mahal
is
beautiful'''

String indexing and segmentation is similar to lists explained in detail earlier:

print(String0[4])
# M
print(String0[4:])
# Mahal is beautiful
print(String0[-1])
# 1

5.4.1 Built-in functions

The find( ) function returns the index value of the given data to be found in the string, the returned index value is the index of the first element in the input data. If it is not found, it returns -1. Be careful not to confuse the returned -1 with the inverted index value:

print(String0)
# Taj Mahal is beautiful
print(String0.find('al'))
# 7
print(String0.find('am'))
# -1

capitalize( ) capitalizes the first element in a string:

String3 = 'observe the first letter in this sentence. can you change this sentence'
print(String3.capitalize())
# Observe the first letter in this sentence. can you change this sentence

center( ) is used to center a string by specifying the field width:

String0.center(70)
# '                        Taj Mahal is beautiful                        '

zfill( ) fills with zeros by specifying the field width:

String0.zfill(30)
# '00000000Taj Mahal is beautiful'

The index( ) and find( ) functions work the same way, the only difference is that find( ) returns '-1' when the input element is not found in the string, but the index( ) function throws a ValueError.

print(String0.index('Taj'))
# 0
print(String0.index('Mahal',0))
# 4
print(String0.index('Mahal',10,20))

The endswith( ) function is used to check if a given string ends with a specific character given as input:

print(String0.endswith('y'))
# False
# 指定开始和停止索引值。指定开始和停止索引值。
print(String0.endswith('M',0,5))
# True

The count( ) function counts the number of characters in a given string. It is also possible to specify a start and stop index or leave it blank:

print(String0.count('a',0))
# 4
print(String0.count('a',5,10))
# 2

The join( ) function adds a character between elements of the input strings:

'a'.join('123')
# '1a2a3'

'123' is the input string and the character 'a' is added between each element.

The join( ) function can also be used to convert lists to strings:

a = list(String0)
print(a)
# ['T', 'a', 'j', ' ', 'M', 'a', 'h', 'a', 'l', ' ', 'i', 's', ' ', 'b', 'e', 'a', 'u', 't', 'i', 'f', 'u', 'l']
b = ''.join(a)
print(b)
# Taj Mahal is beautiful

The split( ) function is used to convert a string into a list:

c = " /i/s/ /b/e/a/u/t/i/f/u/l"
d = c.split('/')
print(d)
# [' ', 'i', 's', ' ', 'b', 'e', 'a', 'u', 't', 'i', 'f', 'u', 'l']

lower( ) converts any uppercase letter to lowercase:

print(String0)
# Taj Mahal is beautiful
print(String0.lower())
# taj mahal is beautiful

upper( ) converts any lowercase letter to uppercase:

String0.upper()
# 'TAJ MAHAL IS BEAUTIFUL'

The replace( ) function replaces the element with another element:

String0.replace('Taj Mahal','Bengaluru')
# 'Bengaluru is beautiful'

The strip( ) function is used to remove unwanted elements from the right and left:

f = '    hello      '
f.strip() # 'hello'

The lstrip( ) and rstrip( ) functions have the same functionality as the strip function, but the only difference is that lstrip() only removes what is on the left, while rstrip() only removes what is on the right:

f = '   ***----hello---*******     '
print(f.lstrip(' *'))
----hello---*******   
print(f.rstrip(' *'))
   ***----hello---

5.5 Dictionaries

Definition dictionary:

d0 = {
    
    }
d1 = dict()

d0['One'] = 1
d0['OneTwo'] = 12 
print(d0)
{
    
    'One': 1, 'OneTwo': 12}

zip( ) can combine multiple lists into a tuple, and can be used with dict() to declare a dictionary:

names = ['One', 'Two', 'Three', 'Four', 'Five']
numbers = [1, 2, 3, 4, 5]
d2 = zip(names,numbers)
print(dict(d2))
{
    
    'One': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5}

5.5.1 Built-in functions

clear( ) clears the dictionary:

a1 = {
    
    1:10, 2:20}
a1.clear()
print(a1)
# {}

values( ) returns a list containing all assignments in the dictionary:

a1.values()
# dict_values([1, 2, 3, 4, 5])

keys( ) returns all indices or keys containing assignments:

a1.keys()
# dict_keys(['One', 'Two', 'Three', 'Four', 'Five'])

items() returns a list, but each element in the dictionary is a tuple in the list, 在这里插入代码片the same as you would get with the zip function:

a1.items()

for (k,v) in a1.items():
    print("[%6s] %d" % (k, v))

The pop() function is used to remove specific elements, and this removed element can be assigned to a new variable:

a2 = a1.pop('One')

Guess you like

Origin blog.csdn.net/LogosTR_/article/details/126634128