current position:Home>[Python exercises]

[Python exercises]

2022-07-24 21:24:46lxw-pro


Personal Nickname :lxw-pro
Personal home page : Welcome to your attention My home page
Personal perception : “ Failure is the mother of success ”, This is the same truth , Sum up in failure , Grow in failure , To be IT A generation of masters in the world .

So-called If you want to learn programming well , Code problems are inevitable , Come on , Get started with the code , Feel the mystery !!!

1. Count the number of vowels in the string

Enter a string ending with a newline , Count and output the number of vowels in the string ( vowel :‘A’,‘E’,‘I’,‘O’,‘U’
,‘a’,‘e’,‘i’,‘o’,‘u’)

s = input().upper()
cs = 0
for i in s:
    if i == '\n':
        break
    if 'A' in i or 'E' in i or 'I' in i or 'O' in i or 'U' in i:
        cs += 1

print(cs)

2. Generate 3 The power table of

Enter a non negative integer n, Generate one 3 The power table of , Output 3​0​​ ~3​n​​ Value . Power function calculation can be called 3 Power of .

import math

n = int(input())
for i in range(n+1):
    print(f"pow(3, {
      i}) = {
      pow(3, i)}")

3. Guess the number game

Two people participate in , One person input ( Set up ) A number , Guess the numbers alone , When the guesser enters a number , Prompt whether you guessed :
If the guessed number is greater than the set number , Tips “ unfortunately , You guessed big ”; If the guessed number is less than the set number , Tips “ unfortunately , You guess it's small ”;
If the guessed number is equal to the set number , Tips “ Congratulations , Guess success ”; People who guess numbers guess at most 5 Time , If more times , Tips “ Guess number failed ”.

num = int(input(" Please enter the number you want to enter :"))
cs = 0
for i in range(1, 6):
    guess = int(input(' Guess the number :'))
    if i == 5:
        print(" Guess number failed !")
    elif guess == num:
        print(' Congratulations , Guess success ')
        break
    elif guess > num:
        print(' unfortunately , Guess how big ~')
    else:
        print(' unfortunately , Guess it's small ~')


4. Special 7

Output 100 within , All contain 7 or 7 The number of multiples of .

for i in range(1, 101):
    if '7' in str(i) or i % 7 == 0:
        print(i)

5. Use for sentence , Realize printing 99 multiplication table

for i in range(1, 10):
    for j in range(1, i+1):
        print(f'{
      j}*{
      i}={
      i*j}\t', end='')
    print()

6. Use only while sentence , Print digital pyramid

jc = int(input())
out = 1
while out <= jc:
    inn = 1
    while inn <= out:
        print(inn, end=" ")
        inn += 1
    print()
    out += 1

7. Use while sentence , Realize printing 99 multiplication table

a = 1
while a < 10:
    b = 1
    while b <= a:
        print("%d*%d=%d"%(b, a, a*b), end='\t')
        b += 1
    print()
    a += 1

8. Use list derivation , Realize printing 99 multiplication table ( Choose to do )

for n in range(10):
    print(" ".join(["%d*%d=%-2d" % (m, n, m*n) for m in range(1, n+1)]))


9. A mixture of for、while sentence , Realize printing 99 multiplication table

for k in range(1, 10):
    w = 0
    while w < k:
        w += 1
        print("{}*{}={}".format(w, k, k*w), end='\t')
    print()

10. Use python Realize the function of printing digital pyramid

num = int(input(" Please enter a number :"))
for i in range(0, num):
    for j in range(num - i - 1, 0, -1):
        print(' ', end=' ')
    for k in range(-i, i + 1):
        print(abs(k)+1, end=' ')
    print()

11. Use for sentence , Realize the function of printing 99 multiplication table

for i in range(1, 10):
    for j in range(1, i+1):
        print(f'{
      j}*{
      i}={
      i*j}\t', end='')
    print()

12、 Create a function , To receive n Sum the numbers and enter

def s():
    n = int(input(" Please enter a number "))
    s = 0
    for i in range(1, n+1):
        s += i
    print(s)


s()


13、 Please use recursive function to find 10 The factorial

def jc(n):
    if n == 0:
        return 1
    else:
        return n*jc(n-1)


print(jc(10))

14、 Grade judgment

Through function import, the randomly generated 10 Students' grades are judged and output .

import random

for i in range(1, 11):
    n = random.randint(1, 101)
    print(n)

    if n >= 90:
        print(' good ')
    elif 80 <= n < 90:
        print(" good ")
    elif 70 <= n < 80:
        print(" secondary ")
    elif 60 <= n < 70:
        print(" pass ")
    else:
        print(" fail, , There's work to be done ")

15. Classic questions

python Programming to achieve the following functions :

Yes 30 A man is trapped on a desert island , There is a ship , You can only install 15 people . So people lined up , The queue is their number . Number off , from 1 Start , Count to 9 People can't get on board . So circular , Until only 15 So far , Ask the number of people who can't get on board ?

peo = {
    }
for x in range(1, 31):
    peo[x] = 1
# print(peo)

i = 1
down = 0
hans = 0

while i <= 31:
    if i == 31:
        i = 1
    elif down == 15:
        break
    else:
        if peo[i] == 0:
            i += 1
            continue
        else:
            hans += 1
            if hans == 9:
                peo[i] = 0
                hans = 0
                print('{} No. can't go on board '.format(i), end=',')
                down += 1
            else:
                i += 1
                continue


Programming to achieve the following functions :

  1. Create two folders in the current directory :test1、test2
  2. stay test1 Under the folder , New text file a1.txt, And write content :test a1
  3. Copy test1 Under the a1.txt To test2 Under the folder , The file named a2.txt
  4. open a2.txt file , Appending the content of writing :write a2
import os
from shutil import copyfile

path1 = 'test1'
path2 = 'test2'
folder1 = os.path.exists(path1)
folder2 = os.path.exists(path2)
if not folder1:
    os.makedirs(path1)
if not folder2:
    os.makedirs(path2)
with open('test1/a1.txt', 'w') as f:
    f.write('test a1')
copyfile('test1/a1.txt', 'test2/a2.txt')
with open('test2/a2.txt', 'a') as f:
    f.write('write a2')

————————————————————————————————————————————

pandas Practice every day :

print() Just to change careers and see the results

# -*- coding = utf-8 -*-
# @Time : 2022/7/19 14:45
# @Author : lxw_pro
# @File : pandas-2  practice .py
# @Software : PyCharm

import pandas as pd
import numpy as np

lxw2 = {"project": ['Python', 'Java', 'C', 'MySQL', 'Linux', 'Math', 'English', 'Python'],
       "popularity": [91, 88, 142, 136, np.nan, 146, 143, 148]}

df = pd.DataFrame(lxw2)

6. Fill in the average of the upper and lower values of the null value

df['popularity'] = df['popularity'].fillna(df['popularity'].interpolate())
print(df)

print()

7. extract popularity The median value of the column is greater than 145 The line of

tq = df[df['popularity'] > 145]
print("popularity The column is greater than 145 Row has :\n", tq)

print()

8. according to project Column to remove duplicate values

qc = df.drop_duplicates(['project'])
print(" After removing duplicate values :\n", qc)

print()

9. Calculation popularity Column average

avg = df['popularity'].mean()
print("popularity The average value of the column is :{:.2f}".format(avg))

print()

10. take project Column to list

lst = df['project'].to_list()
print("project Column to list by \n", lst)

The relevant operation results are as follows :

6~8:
 Insert picture description here
9~10:
 Insert picture description here


A word a day :

A kind reminder , Don't turn the sense of urgency of ambition into the sense of panic of seizing the day , Everyone must get used to the reality of standing at the crossroads of life without traffic lights !!


Ongoing update …

[^1] notes : This article is only for learning , If there is an error , Comments or private letters are welcome .

give the thumbs-up , Your recognition is my creation power
Collection , Your favor is my effort Direction
Comment on , Your opinion is my progress Wealth
Focus on , Your love is my lasting insist
 Insert picture description here

Welcome to your attention WeChat official account Programmed life 6】, Discuss and study together !!!

copyright notice
author[lxw-pro],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/202/202207201751433845.html

Random recommended