对不起,如果这是一个愚蠢的问题,但我正在尝试编写一个函数,它将对一个单词进行置乱,并删除任何空格,并返回单词lengh和通过返回的单词被置乱的单词。另外,我希望能够通过调用函数来赋值变量,而不仅仅是从函数中打印出来。但它甚至不计算和返回数字的长度,更不用说存储函数中的变量了。我确信这是一个简单的答案,但我无法理解,代码在变量方面很混乱,因为我一直在尝试另一种解决方案
import random
import os
def scrambleWord (word_to_scramble, number_of_letters):
number_of_letters = len(word_to_scramble)
number_of_letters = len(word_to_scramble) - word_to_scramble.count(" ") # Assign lengh of word minus whitespace to variable
return word_to_scramble
return number_of_letters
user_word = input("Enter word\t")
user_count = 0
user_word_scrambled = ""
scrambleWord(user_word_scrambled, user_count)
print("Word to scramble is {0}, and is {1} letters long.".format(user_word, user_count))发布于 2021-05-20 10:46:08
在scrambleWord中有两个返回调用,如果您试图从一个函数返回两个变量,可以使用一个元组,例如:
def scrambleWord (word_to_scramble):
number_of_letters = len(word_to_scramble) - word_to_scramble.count(" ")
scramble_word=scramble(word_to_scramble)
return (scramble_word,number_of_letters)然后主要是:
user_word = input("Enter word\t")
scrambled_word,user_count=scrambleWord(user_word)
**print the output对于加扰词,您可以使用随机包:import random
def scramble(word):
word = list(word)
random.shuffle(word)
return ''.join(word)我建议阅读更多关于函数变量的内容,以及它们是如何从函数中传递和返回的,您似乎混淆了引用传递和值传递。
发布于 2021-05-20 10:46:32
对我来说,编写代码很容易,而不是硬算法。你可以把字数从功能中计算出来,而你只是为你的业务提供了一个功能。不管怎样,你的回答是这样的:
def scrambleWord (word_to_scramble, number_of_letters):
number_of_letters = len(word_to_scramble)
number_of_letters = len(word_to_scramble) - word_to_scramble.count(" ") # Assign lengh of word minus whitespace to variable
return number_of_letters,word_to_scramblehttps://stackoverflow.com/questions/67618654
复制相似问题