Python basics+

python basics+

Foreword:

The code in this article is taken from the first Python introductory book written by programming Xiaobai. The main purpose of writing this article is to exercise the ability of blogging and improve programming ability. If there is any infringement, please contact to delete it. If there is an error, it will be changed in time .

The IDE used is jupyter, and the installation process is not described in detail here

1. Open a file:

insert image description here

# 打开files下的test.txt文件,且可读可写
file = open('./files/test.txt','r+') 
# 在文件中写入 Hello world!
file.write("Hello world!")
# 将文件中内容赋值给file_read
file_read = file.readline()
# 关闭文件,必不可少
file.close()
# 输出文件中内容
print(file_read)

output:
insert image description here

2. Basic usage of strings:

Next, we assign strings to last_name, first_name, and cool respectively. What will be output?

last_name = '狗'
first_name = '蛋'
cool = 'cool!'
output = last_name + first_name + cool
print(output)

Presumably you should have already thought of it, that is, the output and dog egg ccol!
insert image description here

3. Find what you need by sharding:

Export the image name in the following URL

‘http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg’
‘http://ww1.site.cn/85cc87jw1ex23yhwws5j20jg0szmzk.png’
‘http://ww2.site.cn/185cc87jw1ex23ynr1naj20jg0t60wv.jpg’
‘http://ww3.site.cn/185cc87jw1ex23yyvq29j20jg0t6gp4.gif’

Question: How to output the image file name in the above URL, take the first URL as an example.

# 将网址赋值给url
url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
# -35就是将url中的值倒着数35个数开始给file_name赋值
file_name = url[-35:]
print(file_name)

The result obtained must be able to be imagined by smart friends, it is the file name of the picture, hehe! !
insert image description here

4. Find the data location

Next, we write a simple code to find the position of a number. For example, we have a field 158 , how to find its position in a mobile phone number.

# 先将158放在我们的search中,以便调用
search = '158'
# 下面设置两个手机号
num_a = '158-9135-7829'
num_b = '167-7158-6788'

# 下面使用find()函数查找158字段的位置,并且输出
print(search + ' is at ' + str(num_a.find(search) + 1) + ' to ' + str(num_a.find(search) + len(search)))
print(search + ' is at ' + str(num_b.find(search) + 1) + ' to ' + str(num_b.find(search) + len(search)))

output:
insert image description here
The above code is not difficult to understand. It uses the splicing of the strings in Title 2. All items in the print() function are of string type, and those that are not of string type are also converted into string type. Among them, the role of the str() function is to convert other types of values ​​into string types. The find() function can find the value index position assigned by search. Since the index starts from 0, it needs to be based on the index Adding 1 is the position identified by our normal people. Later, use len() to obtain the length of the value in the search, and add the length to the index to obtain the cut-off position of the search field.

5. String formatting:

insert image description here
How can it be realized that the words in the above A and B options are filled in the air?

# 在这里大概列举三种方式:
# 1.直接使用.format进行填充{
    
    }
print('{} is a word she can get what she {} for.'.format('With', 'came'))
# 2.将字符串先赋值,然后再讲变量放入{
    
    }
print('{preposition} is a word she can get what she {verb} for.'.format(preposition = 'With', verb = 'came'))
# 3.通过索引的方式
print('{0} is a word she can get what she {1} for.'.format('With', 'came'))

insert image description here
The output results are consistent, and it has no effect when the number of blanks to be filled is small, but when there are many positions to be filled in, the first method and the third method cannot let us know the position of the filled content in time. The second method But you can quickly find out the content to fill in the blanks, so I think the second method is easier to use!

6. Built-in functions:

insert image description here

Exercise 1:

1. Beginner Difficulty: Design a weight converter, input a number in "g" and return the result converted into "Kg"

Here we design a simple function to achieve the result we need.

# 创建一个重量转换的函数
def weight_convert(weight):
	# 将输入进来的字符串转换为浮点型
    weight = float(weight)
    # 进行重量的转换
    weight /= 1000
    # 返回一个重量+‘kg’
    return str(weight) + ' Kg'

# 输入一个重量(g)
weight = input("请输入一个重量(g):")
# 调用写好的重量函数,并且将上面输入进来的重量传入函数中
weight_Kg = weight_convert(weight)
# 按照一定格式输出重量转换
print(weight + " g 以 kg 为单位的大小是" + weight_Kg )

insert image description here

2. Intermediate difficulty: Design a function to find the length of the hypotenuse of a right-angled triangle (the two right-angled sides are parameters, find the longest side), if the lengths of the right-angled sides are 3 and 4, then the returned result should be 5

The idea of ​​this question is also relatively simple, and the previous question is dead, we create a function, and write the algorithm for finding the hypotenuse into the function, so that when we need to find the hypotenuse, we only need to call the function!

Here we call a third-party library, numpy is a very powerful third-party library, which may be mentioned in future blogs

import numpy as np
# 创建一个求直角三角形斜边的函数
def  hypotenuse(a, b):
	# 求斜边定理
    c = np.sqrt((a ** 2) +(b ** 2))
    # 将斜边返回
    return str(c)

# 下面的内容就不难理解了,输入两个直角边,调用函数输出斜边
input_a = input("请输入第一条直角边:")
input_a = float(input_a)

input_b = input("请输入第二条直角边:")
input_b = float(input_b)

output_c = hypotenuse(input_a, input_b)
print("直角三角形的斜边长度为:" + output_c)

insert image description here

Exercise 2:

1. Design such a function that can create a corresponding number of files in the computer.
insert image description here
A relatively simple idea is that we use a for traversal to create ten files from 1 to 10, and use **.format()** to format the files name to number.

for i in range(1, 11):
    file = open('./files/{}.txt'.format(i), 'w+')
    file.close()

2. Compound interest is a magical thing, as Franklin said: "Compound interest is the stone that turns all lead into gold". Design a compound interest calculation function invest(), which contains three functions: amount (fund), rate (interest rate), time (investment time). Calling the function after entering each parameter should return the total amount of funds for each year. It should look like this (assuming 5% interest rate)

Here, we still create a function. After all, we learn that Python is object-oriented programming.

# 这次创建的函数需要我们输入资金,利率以及时间,想起来也比较简单
def invest(amount, rate, time):
    print("principal amount:{}".format(amount))
    for t in range(1, time + 1):
        amount = amount * (1 + rate)
        print("year{}:${}".format(t, amount))
invest(100, 0.05, 8) 

insert image description here
3. It is relatively simple to print the even numbers within 1~100
and put the code directly

for i in range(100):
    if i % 2 == 0:
        print(i)

7. Comprehensive exercises:

Next, we design a comprehensive case.
In order to save time, we directly paste the ideas in the book and divide them
insert image description here
into the following modules.

1. Dice-throwing module
In this game we have three dice. We use the function of generating random numbers to generate random numbers from 1 to 6 for the points of the dice, and control the number of dice through a while loop.

def roll_dice(numbers=3, points=None):
    print('<<<<< Roll The Dice! >>>>>')
    if points is None:
        # 在这里我们创建一个空列表来存放骰子的点数
        points = []
    while numbers > 0:
    	# 产生骰子的点数
        point = np.random.randint(1, 7)
        points.append(point)
        numbers = numbers - 1
    return points

2. Victory module

def roll_result(total):
	# 大为1118,小为310,因为最小为3,最大为18
    isBig = 11 <= total <= 18
    isSmall = 3 <= total <= 10
    if isBig:
        return 'Big'
    elif isSmall:
        return 'small'

3. Game start module

Win if our input is the same size as the random number generated, otherwise lose

def start_game():
    print('<<<<< GAME STARTS! >>>>>')
    # 下面我们来输入自己的决定
    choices = ['Big', 'Small']
    Your_choice  = input('Big or Small:')
    
    # 首先我们要确保,我们的输入的为Big以及Small,否则后续无法正常运行
    if Your_choice in choices:
        # 在这里我们调用函数,得到三颗骰子点数的列表
        points = roll_dice()
        # 求和
        total = sum(points)
        # 判定结果
        youWin = Your_choice == roll_result(total)
        if youWin:
            print('The point are', points, 'you win')
        else:
            print('The point are', points, 'you lose')
#             start_game()
# 在这里我们调用开始游戏模块,进入游戏
start_game()

insert image description here

Exercise 3:

1. Add such functions, bet amount and odds on the basis of the last item. The specific rules are as follows:

  • The initial amount is 1000 yuan
  • The game ends when the amount reaches 0
  • The default odds are 1 times, that is to say, you can get the corresponding amount if you bet right, and you will lose the corresponding amount if you bet wrong

We add some simple money functions, the idea is to add a recharge function on the start interface, and add a while loop, so that one game can be finished one after another, and when the money is 0, the game should end, when the money When it is less than 0, the comrades playing the game should be asked to "repay the money", and the game should end. We use break to end the game.

Let's take a look at the improved code

def start_game():
    money = input('充值金额:')
    while True:
        money = float(money)
        print('<<<<< GAME STARTS! >>>>>')
        choices = ['Big', 'Small']
        Your_choice  = input('Big or Small:')
        if Your_choice in choices:
            points = roll_dice()
            cash_pledge = input('How much you wanna bet ? --')
            cash_pledge = float(cash_pledge)
            balance_outstanding = money - cash_pledge
            total = sum(points)
            youWin = Your_choice == roll_result(total)
            if youWin:
                money = money + cash_pledge
                print('The point are', points, 'you win')
                print('You gained ' + str(cash_pledge) + ',you have' + str(money))
            else:
                money = balance_outstanding
                print('The point are', points, 'you lose')
                print('You lost ' + str(cash_pledge) + ',you have' + str(money))

        if money < 0:
            print('把欠的钱抓紧还了')
            break
        elif money == 0:
            print('没钱了')
            break
        
#             start_game()
start_game()

insert image description here

8. Multiple derivations:

We can also use the **b = [i for i in range(1,20000)]** method when traversing, and it has more unexpected effects. Let's test the running time. It can be seen that the method of multiple derivation has better computational power.

import time
a = []
t0 = time.clock()
for i in range(1,20000):
    a.append(i)
print(time.clock() - t0, "seconds process time")
t0 = time.clock()
b = [i for i in range(1,20000)]
print(time.clock() - t0, "seconds process time")

insert image description here

a = [i**2 for i in range(1,10)]
print(a)
c = [j+1 for j in range(1,10)]
print(c)
k = [n for n in range(1,10) if n % 2 ==0]
print(k)
z = [letter.lower() for letter in 'ABCDEFGHIGKLMN']
print(z)

insert image description here
It looks more concise, but sometimes it may be difficult to understand.

9. Slicing:

Randomly written slices, the parameters entered in the brackets are the positions that need to be sliced.

# eg1
lyric = 'The night begin to shine, the night begin to shine'
words = lyric.split('e')
print(words)

insert image description here
Is the output a bit ugly? Let’s slice the spaces to see if the output
insert image description here
looks much better. We should also pay attention when we process the data and don’t mess around.

Epilogue:

This sharing is over, if you have any mistakes or questions, please ask! ! Welcome everyone's criticism! correct me!

Guess you like

Origin blog.csdn.net/qq_44636114/article/details/121672314