Home > front end >  if statement not printing correctly when adding elif
if statement not printing correctly when adding elif

Time:10-01

I wrote the following code to create a url from users choice,

def create_parameter_url(weather_data):
    list_parameters = str(input('Would you like to see available parameters? y/n \n>>>'))
    for i in range(len(weather_data['resource'])):
        if list_parameters == 'y':
            print(i 1 , ":" , weather_data['resource'][i]['title'] , weather_data['resource'][i]['summary'])            
    choose_parameter = str(input('\nEnter the index of a parameter (integer): \n>>>'))
    parameter_url = first_url_no_json   choose_parameter
    return parameter_url

It's working fine and i'm getting back what i want( it lists out a few choices for the user), but when i try to add elif, in case the user chooses no, it only prints one row,

def create_parameter_url(weather_data):
    list_parameters = str(input('Would you like to see available parameters? y/n \n>>>'))
    for i in range(len(weather_data['resource'])):
        if list_parameters == 'y':
            print(i 1 , ":" , weather_data['resource'][i]['title'] , weather_data['resource'][i]['summary'])            
            choose_parameter = str(input('\nEnter the index of a parameter (integer): \n>>>')) 
        elif list_parameters == 'n':
            choose_parameter = str(input('\nEnter the index of a parameter (integer): ))
    parameter_url = first_url_no_json   choose_parameter
    return parameter_url

i.e if the users answers with a no to list_parameters, i just want to move on without the print after the if statement! How can i do that? the weather data is a result of reading a json file from a url, here is the code

def json_from_url(requested_url):
    with urllib.request.urlopen(requested_url) as url:
        weather_data = js.load(url)
    return weather_data   

requested_url = 'https://opendata-download-metobs.smhi.se/api/version/1.0/parameter.json'
weather_data = json_from_url(requested_url)

CodePudding user response:

You need to move the if so that it controls the for loop instead:

def create_parameter_url(weather_data):
    list_parameters = str(input('Would you like to see available parameters? y/n \n>>>'))
    if list_parameters == 'y':
        for i in range(len(weather_data['resource'])):
            print(i 1 , ":" , weather_data['resource'][i]['title'] , weather_data['resource'][i]['summary'])            
    choose_parameter = str(input('\nEnter the index of a parameter (integer): \n>>>')) 
    parameter_url = first_url_no_json   choose_parameter
    return parameter_url
  • Related