Kawin M
Kawin M

Reputation: 306

Creating variable to assign multiple values in python3

I have a code:

import random

vowels, consonants='aeiou','bcdfghjklmnpqrstvwxyz'

terms = int(input("How many letters you want for your baby's name? "))

def babyname():
    for i in range(0, terms):
        j=['','','','','']
        k = input("What letter do you want? Enter 'v' for vowels, 'c' for consonants: ")
        if k == 'v':
            j[i] = random.choice(vowels)
        elif k == 'c':
            j[i] =random.choice(consonants)
        else:
            k = input("What letter do you want? Enter 'v' for vowels, 'c' for consonants: ")
        print(j)

babyname()

Input: i) It will ask for the number of letters for the word to be generated. ii)It will ask whether the letter should be consonant or vowel for each letter.

Expected output: i) Print the generated word with the inputted number of letters

But output yielded: i) Only the letter generated before the limit. If 5 is entered. It generates the 5th letter only.

What I did: I thought of making the variable j a list with index i so that I can add all the strings later to generate the word. But it is not happening.

What to do?

Upvotes: 1

Views: 246

Answers (3)

Davide Del Papa
Davide Del Papa

Reputation: 378

Just moving the declaration of J outside the for block will do the trick. In fact, at every iteration of the for loop, the variable j is reassigned the values ['','','','',''], overwriting the earlier values.

def babyname():
j=['','','','',''] // here
for i in range(0, terms):
    a = {'v':'v','c':'c','l':'l'} // This too is better off near the j
    ...

However, you should consider rewriting your code altogether, maybe letting j grow with every iteration (right now only a 5 letter name is possible):

def babyname():
    j=[]
    a = {'v':'v','c':'c'}
    for i in range(0, terms):
        k = input("What letter do you want? Enter 'v' for vowels, 'c' for consonants: ")
        if a[k] == 'v':
            j.append(random.choice(vowels))
        elif a[k] == 'c':
            j.append(random.choice(consonants))
        else:
            pass
    print(j)

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113978

separate it into distinct problems

problem 1: user picks a letter

def pick_letter():
    while True:
        user_choice = input("Would you like a [v]owel or [c]onsonant?")
        if user_choice[0].lower() == "v":
           return random.choice(vowels)
        elif user_choice[0].lower() == "c":
           return random.choice(consonants)
        else:
           print("Unknown Input: %r"%user_choice)

print(pick_letter())

problem 2: pick number_of_letters random characters and join them

def baby_name(n_letters):
    return "".join(pick_letter() for _ in range(n_letters))

print(baby_name(5))

Upvotes: 1

MooingRawr
MooingRawr

Reputation: 4991

Your code has more errors than what you are just asking.

For example if user enters 7 letters, you're j list only has room for 5, thus throwing an index error.

Solution is to make an empty list and append to that list every time.


Your dictionary of a is redundant, maybe you just wanted to learn how to use dictionary? You can just compare with :

if k == 'v':
     #do something

elif k == 'c':
     #do something

Your else statement makes no sense since your user can enter anything and if it's not in your dictionary it will throw a keyError, maybe get rid of it? Maybe this isn't implemented yet fully but looking up user input as a key to your dictionary is generally a bad idea. Use something else.


Finally to answer your question, move the line print(j) outside of your for loop. When all said and done it should look something like:

import random

vowels, consonants='aeiou','bcdfghjklmnpqrstvwxyz'

terms = int(input("How many letters you want for your baby's name? "))

def babyname():
    j = []
    for i in range(0, terms):
        a = {'v':'v','c':'c','l':'l'}
        k = input("What letter do you want? Enter 'v' for vowels, 'c' for consonants: ")
        if a[k] == 'v':
            j.append(random.choice(vowels))
        elif a[k] == 'c':
            j.append(random.choice(consonants))
        else:
            print('not an option')
    print(j)

babyname()

This will print a list though so maybe you want to combine it to a string using join():

print(''.join(j))

Upvotes: 1

Related Questions