使用 Python 編寫一個程式,生成一個偶數長度的隨機四位數 PIN 碼序列。從使用者獲取序列長度,並在輸入無效時提示使用者重新輸入。
生成偶數長度隨機四位數 PIN 碼的結果如下所示:
enter the series size 4 Random four digit pin number series 0 0813 1 7218 2 6739 3 8390
為了解決這個問題,我們將遵循以下步驟:
解決方案
建立一個空列表,並將結果設定為 True。
設定 while 迴圈並從使用者獲取大小。
設定 if 條件以判斷大小是偶數還是奇數。如果大小為奇數,則將結果設定為 False,並執行迴圈,直到輸入偶數。
l = []
while(True):
size = int(input("enter the series size"))
if(size%2==1):
result = False如果大小為偶數,則將結果設定為 True,並設定 for 迴圈以訪問大小範圍。
result = True for i in range(size):
生成隨機四位數,並將其儲存在 rand_pin 中。
將 rand_pin 值追加到列表中,然後生成一個序列。
rand_pin = random.sample(num,4)
l.append("".join(rand_pin))
pd.Series(l)如果結果值為 True,則使用 if 條件退出迴圈。
if(result==True): break
示例
讓我們瞭解一下下面的程式碼:
# importing pandas as pd
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP