Python每日一练
问题:
编写一个程序来检查一个单词是否为同源词。
同源词是指不包含任何重复字母的单词,例如brown,fox,quick等。
定义函数is_string_isogram(),参数为一个单词word。
在函数内,如果单词是同源词,则返回True,否则返回False。
不区分大小写。
题目来源:PythonTip
https://edu.py2fun.com/
代码实现
代码如下(示例):
def is_string_isogram(word):
# 将单词转换为小写
word = word.lower()
# 在此处编写你的代码
for i in word: # for把单词的每一个字母拿出来,
num = 0 # 请读者考虑一下,为什么这次将计数的变量放在for循环里面,而不是在一开始定义,下篇博客我们聊一聊
for j in word: # 将拿出来的字母与单词的每个字母重新比较,也包含了本身,因此只要有重复字母num必将大于1
if j == i:
num += 1
if num > 1:
return False
return True
# 从用户处获取输入
word = input()
# 调用函数
print(is_string_isogram(word))
示例输入:
house
示例输出:
True
总结
Python内置函数可以实现字符串字母大小写转换,使用方法如下:
# 转小写
string ="HEllo,world!"
print(string.lower())
示例输出:
hello,world
# 转大写
string ="hello,world!"
print(string.upper())
示例输出:
HELLO,WORLD!