python Basics - if, while, for loop exercise 2021-10-31

Keywords: Python R Language

1, Simple arithmetic practice

1: Input two variables on the console and exchange the values of these two variables [complete with XOR]

#The console inputs two variables and exchanges the values of the two variables
#[complete with XOR]
print("Please enter a,b Value of: ")
a = int(input("Please enter a Value of"))
b = int(input("Please enter b Value of"))
print("Before transformation: a = "+ str(a) +",b = "+ str(b))
print("After transformation: a = {},b = {}".format(a,b))

2: Determine whether an integer is odd or even

num = int(input("Please enter a number:"))
if (num% 2)==0:
	print("{0}It's an even number".format(num))
	print("{0}It's an odd number".format(num))

3: Find the area and perimeter of a rectangle

#   Find the area and perimeter of a rectangle
def the measure of area(long, wide):
      return long * wide
def Perimeter(long , wide):
      return (long+wide)*2
 wide = eval(input("Please enter the width of the rectangle:"))
long = eval(input("Please enter the length of the rectangle:"))
print("the measure of area=", the measure of area(long, wide))

4: According to the radius of the known circle (input from the console), calculate its area and perimeter (PI can use Math.PI or 3.14).

#Calculate the area and perimeter of a given circle according to its radius (input from the console) (PI can use Math.PI or 3.14)
r=float(input("Enter the radius of the circle:"))    #Remove the [] supplementary code to obtain the value of the input radius
L=2*PI*r             #Remove the [] supplementary code to calculate the circumference of the circle
S=PI*r**2            #Remove the [] supplementary code to realize the calculated area
print("Circumference length","{:.2f}".format(L),",Area","{:.2f}".format(S),sep="")

2, if and while exercises

1. Health plan
User input height (m), weight (kg)
Calculation formula: BMI = weight / height ^ 2
BMI < 18.5: too light
18.5 ≤ BMI < 24: normal
24 ≤ BMI < 27: Overweight
27 ≤ BMI < 30: mild obesity
30 ≤ BMI < 35: moderately obese
BMI ≥ 35: severe obesity

m=float (input("Your height is:"))
kg=float (input("Your weight is:"))
BMI = kg//(m*m)
if BMI<18.5:
	print("Too light")
elif BMI>=18.5 and BMI<24:
elif BMI>=24 and BMI<27:
elif BMI>=27 and BMI<30:
	print("Mild obesity")
elif BMI>=30 and BMI<35:
	print("Moderate obesity ")	
elif BMI>=35:
	print("Severe obesity")
	print("You're not human!")

2. Let the user enter a month to judge which season this month is?
It is assumed that March to April is spring, may to August is summer, September to October is autumn, and November, December, January and February are winter

month = int(input("Please enter month:"))

if month == 3 or month == 4:
elif month == 5 or month == 6 or month == 7 or month == 8:
elif month == 9 or month == 10:
elif month == 11 or month == 12 or month == 1 or month == 2:
	print("The month you entered is not a month!")

3. Prompt the user to enter the user name, and then prompt for the password. If the user name
If it is "admin" and the password is "88888", the prompt is correct. Otherwise, if
If the user name is not admin, you will be prompted that the user name does not exist. If the user name is
admin will prompt the password error. "" "

name = input ("Please enter user name:")
password = int (input("Please input a password:"))
if (name=="admin" and password==88888):
elif (name =="admin"):
	print("Password error")
	print("user name does not exist") 

4. Chicken and rabbit are in the same cage. There are 35 heads from above and 94 feet from below. How many chickens and rabbits are there?

chicken = 1
while chicken <= 35:
	rabbit = 1
	while rabbit <= 35:
		if (chicken + rabbit == 35) and (2 * chicken + 4 * rabbit == 94):
			print(f"Chicken is{chicken}A duck is{rabbit}only")
		rabbit += 1
	chicken += 1

5. Receive the data "addition, subtraction, multiplication and division" input by the user on the console

n1 = float(input("Please enter the first number:"))
op = input("Please enter the symbol you want to calculate(+,-,*,/,%,//,**): ")
n2 = float(input("Please enter the second number:"))
# Data operation
if op == "+":
	print("%s + %s = %s"%(n1, n2, (n1 + n2)))
elif op == "-":
	print("%s - %s = %s" %(n1, n2, (n1 - n2)))
elif op == "*":
	print("%s * %s = %s" %(n1, n2, (n1 * n2)))
elif op == "/":
	print("%s / %s = %s" %(n1, n2, (n1 / n2)))
elif op == "%":
	print("%s %% %s \\n= %s " %(n1, n2, (n1 / n2)))

6. Enter the length of the three sides and calculate the area and perimeter of the triangle (Helen formula)

a = float(input('Enter the first edge a: '))
b = float(input('Enter the first edge b: '))
c = float(input('Enter the first edge c: '))
if a + b > c and a + c > b and b + c > a:
    print("Perimeter of triangle: %f" % (a + b + c))
    p = (a + b + c) / 2
    area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
    print("Area of triangle: %f" % (area))
    print('Cannot form a triangle!')

3, for loop exercise

1. Enter a number to judge whether the number is a prime number (for)

num = int(input("Please enter a number: "))
# Prime number greater than 1
if num > 1:
   # View factor
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"Not prime")
       print(num,"Is a prime number")
# If the entered number is less than or equal to 1, it is not a prime number
   print(num,"Not prime")

2. What are the prime numbers between 50 and 150?

for i in range(50,150):
	flag = True
	for j in range(2,i):
		if i % j == 0:
			flag = False
	if flag:
		print("%s Is a prime number" %(i))

3. Print out the number of standard daffodils and output these daffodils

#Narcissus number refers to an n-bit positive integer (n ≥ 3), and the sum of the N powers of the numbers in each bit is equal to itself. 
#For example: 153 = 1 × one × 1+5 × five × 5+3 × three × 3. 

n=int(input("Please enter a positive integer:"))
for i in range(10**(n-1),10**n):
	while j>=1:
	if sum==i:

4. Verify that the difference obtained by subtracting the sum of its digits from any integer greater than 9 can be divided by 9

num = int(input("Please enter an integer greater than 9:"))
# (12 - (1 + 2)) / 9
# If it's two
if num < 100:
	gewei = num % 10
	shiwei = num // 10
	if (num - (gewei + shiwei)) % 9 == 0:
		print("Verification passed")
		print("Validation failed")
elif num > 99 and num < 1000:
	# Three digit
	gewei = (num%100)%10
	shiwei = (num%100)//10
	bawei = num//100
	if (num - (gewei + shiwei + bawei)) % 9 == 0:
		print("Verification passed")
		print("Validation failed")

5. Program to find A four digit natural number ABCD, which is multiplied by A and becomes DCBA

#Use the range() function to determine the four digit iteration object
for i in range(1000,10000):
	gewei = (i%1000)%100%10
	shiwei = (i%1000)%100//10
	baiwei = (i%1000)//100
	qianwei = i//1000
    #Calculation method of DCBA
	change = gewei*1000+shiwei*100+baiwei*10+qianwei
	if (i*qianwei) == change:

6. Enter a year to judge whether a year is a leap year

#Can be divided by 4 but not 100;
#Can be divided by 400;
year = int(input("Please enter a year:"))
if (year%4==0 and year%100!=0) or year%400 == 0:
	print("%s It's a leap year"%year)
	print("{}Not a leap year".format(year))

7. The quotient of a number divided by 80 is not only a multiple of 7, but also 2, 3, 4, 5 and 6. The remainder is 1. Find this natural number

#Analysis: the result of dividing a number by 80 can be% 7 as 0; a number% 2, 3, 4, 5, 6 as 1
flag = 0
for i in range(1,1000):
	shang = 80//i
	yushu = i%80
	a = i%2
	b = i%3
	c = i%4
	d = i%5
	e = i%6
	if shang%7==0 and a==1 and b==1 and c==1 and d==1 and e==1:
		flag += 1
		#When the flag is 5 or 10, line feed is used to output the result, which is easy to observe
		if flag == 5 or flag == 10:

8. There is a simplest true fraction. The product of their numerator and denominator is 140. Print all such true fractions from small to large

#First, confirm the size range of numerator and denominator. Of course, it can be written larger to save trouble, but in order to reduce the time and space complexity of the code, it is recommended to analyze it first

for i in range(1,11):
	for j in range(i+1,141):
		if i*j == 140:

9. For a five digit number, if you write a 7 after it, you get a six digit A. if you write a 7 before it, you get a six digit B. B is five times of A. find the five digits

#Use the range() function to determine the five digit iteration object
for i in range(10000,100000):
	gewei = (i%10000)%1000%100%10
	shiwei = (i%10000)%1000%100//10
	baiwei = (i%10000)%1000//100
	qianwei = (i%10000)//1000
	wanwei = i//10000
	#A. Calculation method of B
	a = 7+gewei*10+shiwei*100+baiwei*1000+qianwei*10000+wanwei*100000
	b = gewei+shiwei*10+baiwei*100+qianwei*1000+wanwei*10000+7*100000
	if b == a*5:

10. Program to find the three digits that meet the following conditions: the quotient obtained by dividing it by 11 is equal to the sum of its digits

#Use the range() function to determine the three digit iteration object
for i in range(100,1000):
	baiwei = i//100
	gewei = (i%100)%10
	shiwei = (i%100)//10
	if (i//11) ==(gewei+shiwei+baiwei):

11. Guessing game: a game of stone, scissors and cloth

#Import random number
import random
print("The guessing game begins")
#Generate random number random.randint(a,b) in the range of ()
computer = random.randint(0,2)
0 =="stone"
1 =="scissors"
2 =="cloth"
while True:
#n is the number corresponding to your fist
 n = int(input("Please enter 0-2 The number you guessed:"))

 if n==computer:
  print("it ends in a draw:")
 elif (n== 1 and computer==0) or(n==2 and computer ==1)or(n==0 and computer ==2):
  print("Unfortunately, you lost:")
  print("Congratulations, you won:")

12, # guessing numbers game

"""The number within a random range of the brain is judged by the user's input data,
	If the number is large, the number of "provided" is large“
	After success, add whether the user continues the function"""
#Import random number
import random
print("The number guessing game begins")
#Generate random number random.randint(a,b) in the range of ()
number = random.randint(0,100)
while True:
 n = int(input("Please enter 0-100 The number you guessed:"))

 if n==number:
  print("Congratulations, you guessed right:")
 elif n > number:
  print("Your guess is a little big:")
  print("Your guess is a little small:")

13. There is a pile of coins. You can only take one or two coins at a time. Please ask how many times you can get all the coins at least
[10, 8, 5, 3, 27, 99]

for i in ls:
    if i % 2 ==0:

14, # find the sum of numbers between 1 and 100 that cannot be divided by 3

while i<=100:
    if i % 3 ==0:

15, 99 multiplication table

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

16. Calculate PI formula PI/4=1-(1/3)+(1/5)-(1/7) +
The numerator is all 1, and the denominator is an arithmetic sequence with an interval of 2

import sys
n=int(input("Please enter a positive integer n: "))
if n<=0:
 print("You entered n Invalid:")
s =0
flag = True
for i in range (1,n+1,2):#Range (start value, end value, interval)
 if flag:
  flag = False
  flag = True
print("PI Approximate value of:",4*s,sep="") 

Posted by sevenupcan on Sun, 31 Oct 2021 03:51:09 -0700