Python loop statement simple exercise questions and answer analysis

1. The problem here is to guess what number is stored in the computer. You are going to write a program that randomly generates a number between 0 and 100, inclusive. This program prompts the user to enter a number continuously until it matches the randomly generated number. For each number entered by the user, the program will prompt whether it is too high or too low, so the user can choose the next number to enter more wisely.

import random
com = random.randint(0, 100)
while True:
    num = int(input("请输入一个0-100之间的整数: "))
    if num == com:
        print("恭喜你!!!答对了,奖励你一根棒棒糖")
        break
    elif num > com:
        print("你猜的数过大")
    else:
        print("你猜的数过小")

Operation results:
Insert image description here
2. The greatest common divisor (GCD) of two integers 4 and 2 is 2. The greatest common divisor of the integers 16 and 24 is 8. How to find the greatest common divisor? Suppose the two integers input are nl and n2. You know that the number 1 is their common divisor, but it is not their greatest common divisor. So, you have to check whether k (k=2, 3, 4,...) is the common divisor of n1 and n2 until k is greater than n1 or n2. Store the common denominator in a variable called gcd. In the initial state, the value of gcd is 1. Each time a new common divisor is found, assign it to gcd. After you have tested all possible common divisors from 2 to n1 or from 2 to n2, the value stored in gcd is the greatest common divisor.

num1,num2 = eval(input("请输入两个数: "))
a = min(num1,num2)#选取两个数中较小的数
b = max(num1,num2)#选取两个数中较大的数
for gcd in range(0,a+1):#定义公约数在0到较小数之间取
	gcd += 1#定义公约数从0开始,依次加一直到a
	if a % gcd == 0 and b % gcd == 0:#判断a是否能被两数整除
		gcd1 = gcd#若能整除,则将数赋给新数gcd1
	elif a % gcd != 0:
		gcd = gcd#若不能整除,则还是原数
print("%s和%s的最大公约数是: %s"%(num1,num2,gcd1))

Running results:
Insert image description here
3. Monte Carlo simulation uses random numbers and probability to solve problems. It has very wide applications in computer mathematics, physics, chemistry and economics. Now, let's look at an example of estimating π using Monte Carlo simulation.
First, draw a circle with a circumscribed square.
Suppose the radius of this circle is 1. Therefore, the area of ​​the circle is π and the area of ​​the rectangle
is 4. Randomly generate a point within this square. The probability of this point falling within the circle is
circleArea/squareArea=π/4.
Write a program to randomly generate 1,000,000 points within the square, and use numberOfHits to represent the number of points falling within the circle. Therefore, numberOfHits is approximately 1 000 000* (π/4). π can be approximated as 4*numberOfHits/1 000 000.

import random
for num in range(0,1000000):#定义选取0到1000000随机数
	x = random.random() * 2 - 1
	y = random.random() * 2 - 1
	a = (x ** 2 + y ** 2) ** 0.5#计算半径
	if a <= 1:#判断是否在圆内
		num += 1
pi = num * 4 / 1000000
print(pi)

Running results: Insert image description here
4. (Count the number of positive and negative numbers and then calculate the average of these numbers) Write a program to read an unspecified number of integers, and then determine how many positive numbers and how many in the integers that have been read. negative numbers and calculates the sum of these input values ​​(not counting 0), and finally obtains their average value. The program ends with the input value 0. Display this average using a floating point number. Below is a simple example run.
Insert image description here

p = 0 
n = 0
sum = 0
while True:#建立while循环
	num = int(input("请输入数值: "))#定义不断输入数
	if num > 0:#判断是否为正
		p += 1
	elif num < 0:#判断是否为负
		n += 1
	elif num == 0:#只有输入0,才会停止输入数值
		break;
	sum += num
total = p + n#求和
mean = sum / total#求平均值
if total == 0:
	print("不得行")
else:
	print("正数个数是: ",p) 
	print("负数个数是: ",n)
	print("和是: ",sum)
	print("平均数是: ",mean)

Running results:
Insert image description here
5. (Find all factors of an integer) Write a program to read an integer and then display all its smallest factors, also called prime factors. For example: If the input integer is 120, then the output should be as follows.
2, 2, 2, 3, 5

n = int(input("输入一个整数: "))
i = 2 #定义从2开始验证是否能整除
print("该数的素因子有: ")
while True:
	if n % i == 0:#定义循环,依次往下除,
		print(i,end = " ")
		n /= i
	else:
		i += 1
	if n == 1:
		break

Running results:
Insert image description here
6. (Display - a pyramid) Write a program to prompt the user to input - an integer between 1 and 15, and then display a pyramid. The sample operation is as follows.
Insert image description here

n = int(input("请输入你要打印的行数: "))
for i in range(0,n):
	spce_num = n - i
	for k in range(0,spce_num):#定义空格数
		print(" ",end="")
	for j in range(-i,i+1):
		print(abs(j)+1,end="")'''从负数开始取,加个绝对值+1可以达到题目的效果
		例:若i=2(表示第3行),则取-2到2为,加绝对值+1则为3,2,1,2
		,3'''
	print("")

Running results:
Insert image description here
7. (Use loops to display four modes) Use nested loops to display the following four modes in four independent programs.
Insert image description here
Mode A
code:

n = int(input("请输入你要打印的行数: "))
for i in range(1,n+1):
	spce_num = n - i
	for k in range(spce_num,0):
		print(" ",end="")
	for j in range(1,i+1):
		print(j,end=" ")
	print("")

Running results:
Insert image description here
Mode B
code:

n = int(input("请输入你要打印的行数: ")) 
for i in range(n,0,-1):
	spce_num = n - i
	for k in range(spce_num,0):
		print(" ",end="")
	for j in range(1,i+1):
		print(j,end=" ")
	print("")

Running results:
Insert image description here
Mode C
code:

n = int(input("请输入你要打印的行数: "))
for i in range(1,n+1):
	spce_num = n - i
	for k in range(0,spce_num):
		print(" ",end="")
	for j in range(i,0,-1):
		print(j,end="")
	print("")

Running results:
Insert image description here
Mode D
code:

n = int(input("请输入你要打印的行数: "))
for i in range(n,0,-1):
	spce_num = n - i
	for k in range(0,spce_num):
		print(" ",end="")
	for j in range(1,i+1):
		print(j,end="")
	print("")

Running results:
Insert image description here
8. (Display numbers in pyramid mode) Write a nested for loop to display the following output.
Insert image description here
Code:

n = int(input("请输入你要打印的行数: "))
for i in range(0,n):
	spce_num = n - i
	for k in range(spce_num,0,-1):
		print("",end="\t")
	for j in range(1,i+1):
		print(2 ** (j-1),end="\t")
	for k in range(i+1,0,-1):
		print(2 ** (k-1),end="\t")
	print()

operation result:
Insert image description here

Guess you like

Origin blog.csdn.net/Nirvana92/article/details/124226988