cool hit counter Python Fundamentals - Next_Intefrankly

Python Fundamentals - Next


Approximate time to read this article: 8 minutes

I. Python Interactive Interface

When Python is first installed, there is a Shell interaction tool provided, which can be found inside the start menu.

The interface when opened looks like this.

This screen can be opened directly from the menu bar or by opening the system's command prompt (Start - All Programs - Accessories - Command Prompt) and typingpython Go to that screen.

In this interface, you can directly enter code to execute, for example

We can see that, It can perform calculations directly, It is also possible to assign values toa harmonyb, reusea harmonyb carry out calculations。 And it's obvious when making comparisonsa is less thanb of, alla>b case will return aFalse,b>a then returns aTrue, This is the boolean type。

When making conditional judgments, when a condition returns True, the code under that condition is even executed, and when it returns False, the code is skipped. For example.

owing toa=100,b=200,a>b It's not valid., Based on the conditional judgment logic previously described, So skipping the firstprint, The second one was executedprint。

Much of the learning that follows can be practiced directly in this interactive interface.

II. List and Tuple

1、list

ListThis is python's built-in data type - a list. It is an ordered set. As an example, list the names of the major balls, and assign them to balls. It's formatted like this

list

balls= [' a football',' basketball',' badminton',' basketball']

Here the variable balls is a set which contains the elements football, basketball, badminton and volleyball. Typing balls in the interaction screen prints out its elements, as shown here.

We can also print parameters directly based on their position (in the computer, it counts from zero, so the first position is all zeros and the second position is a one) as shown.

Or you can count backwards.

In Python lists are mutable ordered sets that can be manipulated by some of Python's built-in functions as follows

Adding elements after the list (using the append function).

removing The element at the specified location( usepop function);

Replace the element at the specified position (directly specifying the element at a position in the list for replacement).

Adds an element to the specified position (insert function).

Reference may be made to the following chart.

A list is flexible in that its elements can be of multiple types (integers, strings, boolean types, etc.) or even another list. For example.

Flexible list

L=['b',123,True,[' Siu Ming',' floret']]

2、tuple

A tuple is also an ordered set, basically similar to a list, the difference is that tuples are immutable, whatever element is given at the beginning is whatever element, and cannot be manipulated like a list. The list is enclosed in [], while the tuples are enclosed in (). as if

tuple

#tuple is used for ()

balls=(' a football',' basketball')

#Note: If you want to define tuples with only one element, you need to use the number2 writing style. Since (1) means 1 in Python, all number here is not a tuple, but an integer variable.

number=(1)

number2=(1,)

#One way to define a mutable Tuple is to define the elements of the Tuple as a list. This way only the element list cannot change, the elements of list itself are changeable. For example.

t=('a','b',['c','d'])

t[2][]='f'# As mentioned earlier, The element positions are from0 initial, So here's thelist The location is2,list The first element position in0

t[2][1]='g'

III. dict and set

1、dict

dict is short for dictionary, which means dictionary. is built into Python, and if you know other languages, it's known as map in other languages. The data is stored in the form of (key-value) , which is fast to query.

Code Example

#After the exam, the results are announced, and the corresponding results are found by the names of the students, so if you use lists, you need two lists

names = [' Siu Ming', ' floret', ' David (name)']

scores = [95, 75, 85]

#Withdict it looks like this, note the curly brackets

result = {' Siu Ming': 95, ' floret': 75, ' David (name)': 85}

# Check Xiao Ming's results

result[' Siu Ming']

In dict, a key corresponds to only one value, which means that Xiao Ming corresponds to 95 points. If you change 95 to 85, then Xiao Ming corresponds to a score of 85. This this is the same as the reality of the situation.

Adding a key-value is also simple

Insert an element

#This would deposit an element with a key of tiger cub and a value of 110.

result[' tiger cub']=110

If the key doesn't exist, it can't be checked. Querying a non-existent key directly in the program will cause the program to error out. There are two methods in python to determine if a key exists in a dict.

Determine if a key exists in a dict

#If you have a basic understanding of English, you should be able to understand the meaning of this code. If Ming is in the result, the program will return a True, otherwise it will return a False.

' Siu Ming'inresult

# If you use get, if you don't set a return parameter, it will return None if the key doesn't exist, and -1 if you set a return parameter, such as -1, it will return -1 if it doesn't exist.

result.get(' Siu Ming')

result.get(' Siu Ming',-1)

removing andict The elements in andlist It's a bit like that.

removing

#If the deletion is successful, the value corresponding to Ming will be returned

result.pop(' Siu Ming')

A dict is not ordered; the order in which it stores elements is independent of the order in which they are put in.

Compared to list it is fast in inserting and querying and does not slow down as the elements increase, while list gets slower and slower as the elements increase. Another is that dict can be relatively resource intensive.

It can be understood that dict is trading space for time. It takes up more memory resources, but it's faster and saves time.

2、set

set harmonydict resemblance, The difference is that it onlykey, not havevalue。 consequently, itskey There can be no duplicates.。( (located) atdict Enter the samekey, In fact, it also covers the originalkey ofvalue), establish A set, Need to provide alist for the input set, as if

A set

s=set([1,22,333])

Although the elements passed in are those of a list, it is actually three elements long. If the list passed in has duplicate elements, it will automatically filter out the duplicates.

increase The element is used if theadd function, It supports increase Repetitive elements, But it doesn't work.。

increase

# Add 4 to the s

s.add(4)

Deleting elements is done with the remove function.

removing

s.remove(4)

set elements are also unordered and unduplicated。 If there are twoset, We can also do intersections on it、 The operation of concatenation is performed Elemental filtering。 as if

Elemental filtering

s1=set([1,2,3,4])

s2=set([3,4,5,6])

#& Similar to the meaning of intersection in mathematics

s1&s2

# | Similar to the meaning of parallel sets in mathematics

s1|s2

As for what the execution result looks like, just print it in the interaction screen.

IV. Circulation

1. for and while

In the above, we know that if we type balls directly it will print out all the elements in the balls. So, what if we want to print them out one by one? Then we'll have to use the loop. The loop is written in two ways.

circular statement

#Write loops with for

balls=['a','b','c','d']

forballinballs:

print(ball)

#Write loop with while to calculate 1+2+3+4; n++ means n=n+1

n=

sum=

whilen

sum=sum+n

n++

print(sum)

2. break and continue

Adding break to a loop means to end the loop directly, while adding continue means to skip this loop and go to the next one.

Continue Usage

n=

whilen

n=n+1

ifn%2==:# If n is an even number, execute the continue statement

The continue# continue statement will continue directly to the next round of loops, and subsequent print() statements will not be executed

print(n)

Break Usage

n=1

whilen

ifn>10:# propern = 11 time, Conditions met, executebreak statement

break# The break statement will end the current loop

print(n)

n=n+1

print('END')

Long press the button below to follow this public number and share and learn together!


Recommended>>
1、Ctrip service wins industry recognition again with Customer Service of the Year award
2、Is a mans life predestined
3、Cloud Protection Chain CIC debuts on OKEX today trading starts at 1600
4、Equity in Artificial Intelligence
5、How Xu Xingxing Understands the Nature of Blockchain

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号