Home > front end >  Unable to pass/exit a python function
Unable to pass/exit a python function

Time:07-04

Just starting out with python functions and I can't seem to get out (via "no" or False) once in the loop:

global movies
movies = {}

def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")


movies [name] = [genre]

a = True
while a == True:
    query = input("Do you want to input another movie? (yes/no) ")
    if query == "yes":
        name = input("Insert movie name: ")
        genre = input("Input genre: ")
        movies_if = {}
        movies_if [name] = [genre]
        movies.update(movies_if)

    elif query == "no":
        a = False
                
    else:
        print ("Wrong input!")
        query = input("Do you want to input another movie? (yes/no) ")
        
        return movies

Code works fine when not called via import. When called via import, it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.

Thanks in advance!

CodePudding user response:

global movies
movies = {}

def fun_movies():
    name = input("Insert movie name: ")
    genre = input("Input genre: ")


    movies [name] = [genre]

    a = True
    while a:
        query = input("Do you want to input another movie? (yes/no) ")
        if query == "yes":
            name = input("Insert movie name: ")
            genre = input("Input genre: ")
            movies_if = {}
            movies_if [name] = [genre]
            movies.update(movies_if)
        elif query == "no":
            a = False
        else:
            print ("Wrong input!")        
    return movies

A few things:

Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.

Secondly, only use the input at the start of the loop as you want to ask once per iteration

Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.

CodePudding user response:

global movies
movies = {}

def fun_movies():
    name = input("Insert movie name: ")
    genre = input("Input genre: ")
    movies[name]= genre
    a = True
    while a:
        query = input("Do you want to input another movie?   (yes/no) ")
        if query == "yes":
            name = input("Insert movie name: ")
            genre = input("Input genre: ")
            movies_if = {}
            movies_if [name] = genre
            movies.update(movies_if)       
        elif query == "no":
            break
              
        else:
            print ("Wrong input!")
            # continue
    return movies

print(fun_movies())

Hope It works for you!

  • Related