current position:Home>[Python exercises]
[Python exercises]
2022-07-24 21:24:46【lxw-pro】
python List of exercises
- 1. Count the number of vowels in the string
- 2. Generate 3 The power table of
- 3. Guess the number game
- 4. Special 7
- 5. Use for sentence , Realize printing 99 multiplication table
- 6. Use only while sentence , Print digital pyramid
- 7. Use while sentence , Realize printing 99 multiplication table
- 8. Use list derivation , Realize printing 99 multiplication table ( Choose to do )
- 9. A mixture of for、while sentence , Realize printing 99 multiplication table
- 10. Use python Realize the function of printing digital pyramid
- 11. Use for sentence , Realize the function of printing 99 multiplication table
- 12、 Create a function , To receive n Sum the numbers and enter
- 13、 Please use recursive function to find 10 The factorial
- 14、 Grade judgment
- 15. Classic questions
- Programming to achieve the following functions :
- pandas Practice every day :
- 6. Fill in the average of the upper and lower values of the null value
- 7. extract popularity The median value of the column is greater than 145 The line of
- 8. according to project Column to remove duplicate values
- 9. Calculation popularity Column average
- 10. take project Column to list
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 30 ~3n 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 :
- Create two folders in the current directory :test1、test2
- stay test1 Under the folder , New text file a1.txt, And write content :test a1
- Copy test1 Under the a1.txt To test2 Under the folder , The file named a2.txt
- 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:
9~10:
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 effortDirection
!
Comment on , Your opinion is my progressWealth
!
Focus on , Your love is my lastinginsist
!
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
The sidebar is recommended
- Python integer type
- Python branching and selection structure
- Solved (the problem that PIP in python3 cannot install urllib reports an error)
- "Python practical secret 09" better function operation cache
- Recursive functions and anonymous, higher-order functions in Python
- Python (IX)
- Python sequence type
- Python3 processing XML file learning
- django.db.utils. How to source the unknown connection address of operationalerror?
- What are the * and * * functions often used with zip in Python pattern transfer parameters?
guess what you like
What does zip mean in Python pattern parameters?
What is enumerate used in Python pattern transfer parameter zip?
What is the sorted function used in Python pattern parameters?
What is the zip function used in Python pattern parameters?
What is the difference between having "*" and not having "*" in Python parameters?
When transferring parameters in Python patterns, what is the content of using * and your choice?
Python analyzed 5000+ Tiktok big V and found that everyone likes this kind of video!
The original cool visual map can be done with Python!
Young people don't talk about martial virtue, but use Python to let Mr. Ma perform lightning five whip!
After reading this article, I completely fell in love with Python dynamic charts!
Random recommended
- What, three lines of Python code can get massive data?
- Debug Python code and stop printing!
- 25 great lines of Python code, recommended collection!
- Recommended collection, 22 Python Mini projects (with source code)
- Cyberpunk is so popular. How cool can it be combined with Python?
- 2021 is coming. Exchange Python for a avatar until the New Year!
- "Python practical secret 09" better function operation cache
- About the indentation error caused by sublime text writing Python: unindent does not match any outer indentation level error
- Functions of Python
- Advanced order and closure of Python function
- What are the formulas and characteristics of Jaccard similarity calculation in Python data mining?
- How to use Jaccard similarity to calculate in Python data mining?
- In Python data mining, what does ontology mean in text similarity calculation?
- In Python data mining, what are the other methods of text similarity calculation?
- Python multi label classification reference
- What is the idea of simhash algorithm in Python data mining?
- What are the steps of simhash algorithm in Python data mining?
- How to use simhash algorithm in Python data mining?
- Python crawler other
- Import class of Python
- When Python translates, the return value is empty, but the result can be printed
- Basic operations of Python files
- Python absolute path and relative path explanation
- Python comments (multi line comments and single line comments) usage details
- Four methods of python3 list merging
- Seven methods of string splicing in python3
- In Python__ new__ Method explanation and use
- Common methods of Python requests Library
- Install common third-party packages such as numpy, CV2, and Matplotlib when Python is offline
- Python brute force crack zip file decompression password
- PythonStudy2
- Design and implementation of hotel housing management system based on Python
- Design and implementation of job duplication checking system based on Python
- Design and implementation of Python based third class hospital website
- Python returns an error in the dictionary. How to solve it?
- How does Python monitor the keyboard?
- How to install pandas into visual studios code?
- WxPython static text, drop-down box, button conflict with controller
- Problems of dictionary classes in Python
- Python modulenotfounderror: no module named popular explanation and method