Home > Software engineering >  How to combine all function togetger
How to combine all function togetger

Time:12-02

I want to make a function that can show first char, last char, count of char, and count of vowels from a string, so I make this

> def text(a):
>         result = a[0]
>         return result;    
>     def text (a):
>         result = a[-1]
>         return result
>     def text(a):
>         result= text.len(original_str)
>         return result
>     vowels = {'a','e','i','o','u'}
>     text = "a"
>     for a in my_string:
>       if a in vowels:
>         len(a)    
>     Text("American")

Expected out put

first_char = A 
Last_char = n
num_char = 8
num_vowels = 4

how to make the function working at one time when I put the "text"

hope you all can help

CodePudding user response:

You don't want to write a different function each time. Just include all of the things you want to find inside one function.

def Text(a):
    first_char = a[0]
    last_char = a[-1]
    num_char = len(a)
    num_vowels = sum([l in "aeiou" for l in a.lower()])
    print("first_char:", first_char)
    print("last_char:", last_char)
    print("num_char:", num_char)
    print("num_vowels:", num_vowels)

Text("American")

Output:

first_char: A
last_char: n
num_char: 8
num_vowels: 4

CodePudding user response:

It looks like you're quite new to python, so I've made the following longer than necessary to allow for comments and clarity. The key point is to identify all the things you want your function to return and then make sure you get them, then return everything at once.

def text(a):
    first = a[0] #Store first element in string
    last = a[-1] #Store last element in string
    length = len(a) #Store length of string
    nVowel = 0 #Variable to count vowels
    vowels = {'a','e','i','o','u'} #Set of vowels
    for s in a.lower(): #Loop over all characters in lower case
        if s in vowels: #Check if character is a vowel
            nVowel  = 1 #Add to count if vowel
    return (first, last, length, nVowel) #Return results

print(text("American"))

This can be made significantly shorter, but I'll leave that to you as an opportunity to practice and understand what's going on.

CodePudding user response:

You can execute them all in one function, and simply return all the values in a big chunk. The main problem with your original code is that not only does the code not work to well to begin with, but you are constantly overwriting your function. Also your vowels were represented with braces {} instead of square brackets [], which are used in python.

def Text(string):
    # Calculate
    first = string[0]
    last = string[-1]
    length = len(string)
    vowels = sum([string.lower().count(v) for v in ["a", "e", "i", "o", "u"]])
    # Return
    return first, last, length, vowels

first_char, last_char, num_char, num_vowels = Text("American") # Or for any other string
  • Related