我的任务之一是获取用户输入,将其转换为列表,然后根据每个单词中的字符数,相应地更改为大写/小写。有人告诉我必须使用范围,这是我正在努力的一部分。这是我的最新尝试,但是没有用。任何建议将不胜感激。
poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
list_len = len(words_list)
for word in range(0,list_len):
if len(words_list[word]) < 4:
word = word.lower()
elif len(words_list[word]) > 6:
word = words.upper()
答案 0 :(得分:0)
怎么样?
poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
out = ""
for word in words_list:
if len(word) < 4:
word = word.lower()
elif len(word) > 6:
word = word.upper()
out += " " + word
print(out)
已删除未使用的“ list_len”变量,在“ words_list”中循环并检查“ word”的长度。并使用“ out”变量集中输出。对于输出,可能会有更好的技术,我只是做了一个简单的技术。
答案 1 :(得分:0)
poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
list_len = len(words_list)
# word is not a word here, it was an integer
# by a convention we use 'i' for the iterator here
for i in range(0,list_len):
# here we assign an actual 'word' to the word variable
word = words_list[i]
if len(word) < 4:
# therefore you couldn't use .lower() or .upper() on the integer
word = word.lower()
elif len(word) > 6:
word = word.upper()
使用适当的IDE进行编码,例如PyCharm。它会提醒您所有的错误。
如果您确实需要使用范围,那将起作用,但是您仍然需要弄清楚打印/返回值。
如果您不知道发生了什么,只需在需要的地方放置一些print
。如果在代码中放入打印件,您将自己解决。
答案 2 :(得分:0)
只需对原始代码进行少量修改。由于要转换为大写/小写,因此还可能要保存输出。您也可以使用新列表保存输出,而不是替换原始列表words_list
for word in range(0,list_len):
if len(words_list[word]) < 4:
words_list[word] = words_list[word].lower()
elif len(words_list[word]) > 6:
words_list[word] = words_list[word].upper()
print(words_list)
输出
Enter a poem, verse or saying: My name is bazingaa
['my', 'name', 'is', 'BAZINGAA']
答案 3 :(得分:0)
您的代码有几个问题。 word
是迭代器的值,因此是整数。您不能在整数上使用函数upper
和lower
。但是,您可以通过更简单的方式解决它:
poem = input("Enter a poem, verse or saying: ")
words_list = poem.split()
for i in range(0,len(words_list)):
word = words_list[i]
word = word.lower() if len(word) < 4 else word
if len(word) > 6:word = word.upper()
print(word)
在执行上述代码时:
Enter a poem, verse or saying: Programming in Python is great
PROGRAMMING
in
Python
is
great
您还可以使其函数返回列表(也使用range
):
def get(string):
words_list = string.split()
output = []
for i in range(0,len(words_list)):
word = words_list[i]
word = word.lower() if len(word) < 4 else word
if len(word) > 6:word = word.upper()
output.append(word)
return output
print(get(input("Enter a poem, verse or saying: ")))
测试:
Enter a poem, verse or saying: Programming in Python is great
['PROGRAMMING', 'in', 'Python', 'is', 'great']