题目:编写一个函数,判断传入的字符串参数是否为“回文联”。
(回文联即用回文形式写成的对联,既可顺读,也可倒读。例如:上海自来水来自海上)
#首尾依次对比
s = input('请输入一个字符串:')
if not s:
print('请不要输入空字符串!')
s = input('请重新输入一个字符串:')
a = len(s)
i = 0
count = 1
while i <= (a/2):
if s[i] == s[a-i-1]:
count = 1
i += 1
else:
count = 0
break
if count == 1:
print('您所输入的字符串是回文')
else:
print('您所输入的字符串不是回文')
注:也可采用
reversed()函数方法
题目:通过socket编程将服务器时间发送到客户端。
# server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
# client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))
题目:socket编程,通过客户端将任意数据发送到服务器,服务器再将数据回显在客户端。
Server
# echo_server.py
import socket
host = '' # Symbolic name meaning all available interfaces
port = 12345 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Client
# echo_client.py
import socket
host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
题目:实现用户输入用户名和密码,当用户名为 seven或alex且 密码为123时,显示登陆成功,否则登陆失败,失败时允许重复输入三次。
for i in range(3):
name=input("请输入您的用户名:")
pwd = int(input("请输入您的密码:"))
if name == "seven" or name == "alex" :
if pwd == 123 :
print("欢迎您,"+name)
break
print("登陆失败!")
题目:有红、黄、蓝三种颜色的求,其中红球 3 个,黄球 3 个,绿球 6 个。先将这 12 个球混合放在一个盒子中,从中任意摸出 8 个球,编程计算摸出球的各种颜色搭配(三色球问题)。
print('red\tyellow\tblue')
for red in range(0, 4):
for yellow in range(0, 4):
for green in range(2, 7):
if red + yellow + green == 8:
print(red, '\t', yellow, '\t', green)
# lowercase converted uppercase
l2u = open('test.txt', 'w')
astring = raw_input("Ple enter a string:\n")
astring = astring.upper()
l2u.write(astring)
l2u = open('test.txt', 'r')
print l2u.read()
l2u.close