1. 程式人生 > >Python變量、字符練習1

Python變量、字符練習1

ring 統計 too import span isa ios record ffffff

1、判斷一個變量是否合法:(變量由字母、數字下劃線組成;且開頭不是數字)

while True:

s = raw_input("please input values:")

if s=="exit":

print "welcome use nexttime!"

break

if s[0].isalpha() or s[0] == "_":

for i in s[1:]:

if not(i.isalnum() or i =="_"):

print "%s變量名不合法!" %s

break

else:

print "%s變量名合法!" %s

二、輸入的單詞逆向輸出(小米筆試)

Sentenct = raw_input("please input sentenct:")

a = Sentenct.split(" ")

print " ".join(a[::-1])

三、輸入兩個字符串,刪除第二個字符串中的所有字符(例:輸入:hello world 輸出:world hello)

char1 = raw_input("please input first string:")
char2 = raw_input("please input second string:")


for i in char1:
if i in char2:
continue
else:
print "%s" % i,

四、用戶輸入一個整型數,求該數的階乘

num = int(raw_input("請輸入整型數:"))
rest = 1
for i in range(1, num + 1):
rest *= i
print "輸出%d的階乘:%d" % (num, rest)

五、用戶登陸,且不超過三次

for i in range(3):
username = raw_input("please input username:")
password = raw_input("please input password:")


if username == "root" and password == "westos":
print "login success!!"
break
else:
print "login error!!"
print "you have %d times changes" %(2-i)
else:
print "more than three times! please try again after 10s"

六、判斷一個學生的缺勤記錄(不超過一個A且沒有兩個來連續的L有獎勵)

while True:
Record = raw_input("請輸入該學生的缺勤記錄:")
print Record.count("LLL") == 0
if Record == "exit":
print "退出。。。"
break
if (Record.count("A") <= 1 and Record.count("LLL") == 0):
print "有獎勵!"

else:
print "沒有獎賞!!"

七、輸入一行字符,統計其中有多少個單詞,每兩個單詞之間以空改革隔開
Line = raw_input("please input sentence:")
li = Line.split()
b = len(li)
print "There are %d words in the line" %(b)
八、求列表中的字符個數
char = raw_input("please input sentence:")
print len(char)

九、是否是回文數
num = raw_input("please input values:")
if (num == num[::-1]):
print "是回文數!"
else:
print "不是回文數"

十、求最大公約數和最小公倍數

min_num = min(num1, num2)
for i in range(1, min_num + 1):
if (num1 % i == 0 and num2 % i == 0):
gys = i
gbs = num1 * num2 / gys
print "%d和%d的最大公約數為:%d" % (num1, num2, gys)
print "%d和%d的最大公為:%d" % (num1, num2, gbs)

十一、猜數字遊戲

import random
Systom = random.randint(1, 100)
print Systom
num = 1
while (num <= 5):
Guest = int(raw_input("請輸入您猜測的數字(1-100):"))
if Guest < Systom:
print "too small!!"
elif Guest > Systom:
print "too big!!"
else:
print "congratulations!!"
break
num += 1

十二、仿照終端執行操作

import os # 可以執行系統的命令
while True:
cmd = raw_input("[kiosk@foundation21 ~]$")
if cmd:
if cmd == ‘exit‘:
print "logout"
break
else:
#print ‘run %s‘ %cmd
os.system(cmd)
else:
continue

Python變量、字符練習1