Some practice questions about loops in python.

Question: Find the sum of all even numbers up to 100

code show as below

sum = 0#定义求和的数从0开始
for i in range(0,101,2):'''利用for循环语句定义i在0到100之间,由左
闭右开的原则,i可以取到0,但是取不到101,故i在0到100之间。再定义每两
个数之间间隔为2,即0,2,4,6······100,从而取到偶数'''
	sum += i#定义每个取到的数进行相加
print(sum)

insert image description here

Topic: Find the sum of all odd numbers up to 100

The code is as follows: sum = 0

sum = 0
for x in range(1,101,2):'''与上题相符,从0开始该为从1开始,间隔还
是2,故取到奇数'''
	sum += x
print(sum)

insert image description here

Topic: 3. Write an isosceles triangle

Example:
* * *
* *
* * *
* * * *
* * * * *

code show as below

n = int(input("请输入行数: "))
for i in range(1, n + 1):
    for k in range(0, abs(i - n)):
        print(" ", end="")
    for j in range(1, i + 1):#定义行数,行数为1到i
        if j <= i and i + j <= 2 * n:
            print("* ", end="")
    print()

insert image description here

Title: The problem here is to guess what the number stored in the computer is. 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.

code show as below:

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("你猜的数过小")

insert image description here

Topic: 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 out the greatest common divisor? Assume that the two input integers are nl and n2. You know the number 1 is their common divisor, but it's not the greatest common divisor. So, you want to check whether k (k=2, 3, 4, ...) is a common divisor of n1 and n2 until k is greater than n1 or n2. Store the common divisor in a variable named gcd. In the initial state, the value of gcd is 1. Every time a new common divisor is found, it is assigned to gcd. After you have checked all possible common divisors from 2 to n1 or from 2 to n2, the value stored in gcd is the greatest common divisor.

code show as below:

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))

insert image description here

Guess you like

Origin blog.csdn.net/Zombie_QP/article/details/124364178
Recommended