Experiment report 5. Python program control structure

1. Experimental purpose:

1. Familiar with Python relational operators.

2. Familiar with Python control structures (selection structure, loop structure).

2. Experiment content:

1. Write a program to generate a list containing 50 random integers, and then delete all odd numbers (tip: delete from back to front).

2. Write a program to generate a list containing 20 random integers, and then sort the elements with even subscripts in descending order, leaving the elements with odd subscripts unchanged (tip: use slicing).

3. Write a program where the user inputs an integer less than 1000 from the keyboard and factors it. For example, 10=2×5, 60=2×2×3×5.

4. Write a program to calculate the sum of all odd numbers within 100 using at least two different methods.

5. Write a program to output all prime numbers consisting of the four numbers 1, 2, 3, and 4, and use each number only once in each prime number.

  • Experimental steps:
  1. code

first question:

import random

list_num = [random.randint(0,100) for i in range(50)]

print(" 50 random numbers generated:")

print(list_num)

for i in range(49,-1,-1):

    if list_num[i] % 2 == 1:

        del list_num[i]

print(" After deleting odd elements:")

print(list_num)

Second question:

import random

f=[random.randint(0,100) for i in range(20)]

print(' The generated data is:')

print(f)

y=f[::2]

y.sort(reverse=True)

f[::2]=y

print(' The sorted data is:')

print(f)

Question 3:

x = input(' Please enter a number less than 1000:')

x = eval(x)

t = x

i = 2

result = []

while True:

    if t==1:

        break

    if t%i==0:

        result.append(i)

        t = t/i

    else:

        i+=1

print(x,'=','*'.join(map(str,result)))

Question 4:

lst1 = [i for i in range(1,100,2)]

print(sum(lst1))

sum = 0

for i in range(101):

    if i % 2 == 1:

       sum += i

print(sum)

Question 5:

data = set()

for n in range(1234,4321,1):

    if n % 2 ==0:

        continue

    for i in range(3,int(n ** 0.5) + 1,2):

        if n % i == 0:

            break

    else:

        data.add(n)

for num in data :

    a = str(num)

    b = set(a)

    if ('1' in b) and ('2' in b) and ('3' in b) and ('4' in b):

        print(number)

Result picture

first question:

 

Second question:

 

Question 3:

Question 4:

Question 5:

Guess you like

Origin blog.csdn.net/m0_65168503/article/details/131143586