Python [for loop and while loop]

1. Enter two odd numbers n, m Be Be

Write a loop using a for statement that computes the sum of all odd numbers from n to m Be Be

‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬

Example of input and output

enter output
Example 1 1,11 36

Answer code:

m, n = tuple([int(i) for i in input().split(',')])

print(sum(i for i in range(m, n + 1) if i % 2))

Test Case: 

2.

Input data n, use the while statement to find the sum of 1+2+3+...+n

Example of input and output

enter output
Example 1 3 6

Answer code: 

n=int(input())
S=0
i=1
while i<=n:
    S=S+i
    i=i+1
print(S)

Test Case: 

3. 

input data n and m

Use the while statement to calculate the sum of all data from n to m

‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬

Example of input and output

enter output
Example 1 3,5 12

Answer code: 

s = input()
l = s.split(',')
n = int(l[0])
m = int(l[1])
sum = 0
while n <= m:
    sum = sum + n
    n = n + 1
print(sum)

Test Case:

 

4.

Input a number to determine whether it is a prime number

If yes, output "is prime", otherwise output "not prime" Be Be

‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬

Example of input and output

enter output
Example 1

3‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬

6‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬

is a prime number Be

not prime

 Answer code:

x = eval(input())
for i in range(2,x):
    if x%2==0:
        print("不是素数")
        break
    else:
        print("是素数")
        break

Test Case:

 

 

 

Guess you like

Origin blog.csdn.net/qq_54587141/article/details/123776641