一.回文数判断
1.使用循环
line = input('Enter a string:')
isPalidrome = True
for i in range(0, len(line) // 2):
if line[i] != line[len(line)-i-1]:
isPalidrome = False
if isPalidrome:
print(line, ' is a palindrome.')
else:
print(line, 'is not a palindrome.')
2.使用字符串切片,更为简单
def palindrome(s):
return s==s[::-1]
二.判断密码是否符合规范(使用ASCLL码)
编写一个确定密码是否好的函数。我们将定义一个好的密码为一个至少有8个字符长且包含至少一个大写字母、至少一个小写字母和至少一个数字的密码。如果传递给它的密码的唯一参数正确,那么您的函数应该返回true。否则,它应该返回false。包括一个主程序,读取密码并报告它是否好。
def checkPassword(password):
has_upper = False
has_lower = False
has_num = False
# Check each character in password and see which requirement it meets
for ch in password:
ch=ord(ch)
if ch >= ord('A') and ch <=ord('Z'):
has_upper = True
elif ch >= ord('a') and ch <=ord('z'):
has_lower = True
elif ch >= ord('0') and ch <=ord('9'):
has_num = True
if len(password)>=8 and has_num and has_lower and has_upper:
return True
return False
def main():
p=input('Enter a password')
if checkPassword(p):
print("That's a good password.")
else:
print("That's a bad password.")
if __name__=="__main__":
main()
三.彩票号码生成
为了在某一特定的彩票中赢得最高奖金,人们必须将他或她的彩票上的所有6个号码与由彩票组织者抽取的1到49之间的6个号码相匹配。编写一个程序,为一张彩票随机选择6个数字。请确保所选的6个数字不包含任何副本。按升序显示这些数字。
from random import randrange
MIN_NUM = 1
MAX_NUM = 49
NUM_NUMS = 6
# Keep a list of the numbers for the ticket
ticket_nums = []
# Generate NUM_NUMS random but distinct numbers
for i in range(NUM_NUMS):
# Generate a number that isn’t already on the ticket
rand = randrange(MIN_NUM, MAX_NUM + 1)
while rand in ticket_nums:
rand = randrange(MIN_NUM, MAX_NUM + 1)
# Add the distinct number to the ticket
ticket_nums.append(rand)
# Sort the numbers into ascending order and display them
ticket_nums.sort()
print('Your numbers are:', end='')
for n in ticket_nums:
print(n, end=' ')
print()
四.易错题
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
f(2)#输出为[0, 1]
f(3)#输出为[0, 1, 0, 1, 4]
五.打印自己
编写一个不接受输入的Python程序,并生成一个它自己的源代码的副本作为其唯一的输出(这就像一个可以复制自己的计算机病毒)。
with open(__file__, 'r',encoding='UTF-8') as f:
self_source_code = f.read()
print(self_source_code)