Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python สร้าง Series ความยาวคู่ ของ PIN 4 หลักสุ่ม รับความยาวจากผู้ใช้ จนกว่าจะถูกต้อง


ผลลัพธ์สำหรับการสร้าง PIN 4 หลักสุ่ม ความยาว Series เป็นเลขคู่ คือ

enter the series size 4
Random four digit pin number series
0     0813
1     7218
2     6739
3     8390

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนด้านล่าง −

Solution

  • สร้าง List ว่าง และตั้ง Result เป็น True

  • ตั้ง While Loop และรับ Size จากผู้ใช้

  • ตั้ง If Condition หา Size ว่าเป็นคู่หรือคี่ หากเป็นคี่ กำหนด Result = False และรัน Loop จนกว่าจะกรอกเลขคู่

l = []
while(True):
    size = int(input("enter the series size"))
    if(size%2==1):
        result = False
  • หาก Size เป็นคู่ กำหนด Result = True และตั้ง For Loop เข้าถึง Range ของ Size

result = True
for i in range(size):
  • สุ่มตัวเลข 4 หลัก และเก็บใน rand_pin

  • Append ค่า rand_pin เข้า List แล้วสร้าง Series

rand_pin = random.sample(num,4)
l.append("".join(rand_pin))
pd.Series(l)
  • หากค่า Result เป็น True ให้ Break Loop ด้วย If Condition

if(result==True):
    break

ตัวอย่าง

import pandas as pd
import random,string
num = string.digits
result = True
l = []
while(True):
    size = int(input("enter the series size"))
    if(size%2==1):
        result = False
    else:
        result = True
        for i in range(size):
            rand_pin = random.sample(num,4)
            l.append("".join(rand_pin))
        series = pd.Series(l)
        print("Random four digit pin number series\n",series)
    if(result==True):
        break

ผลลัพธ์

enter the series size 3
oops! enter an even number!
enter the series size 5
oops! enter an even number!
enter the series size 4
Random four digit pin number series
0     0813
1     7218
2     6739
3     8390
dtype: object