简体   繁体   中英

Ask user if they want results printed in upper or lower case python

I have this code below... but can't seem to get it to work. For starters, if the user types that they want the results printed in uppercase, it stays lower case. In addition to this, the results instead of displaying in one organized list, the code just keeps looping individually through the contents. What am I doing wrong?


def list_movies(movies):
   

        for i in range(0, len(movies)):
            movie = movies[i]
            case = input("Would you like it printed in (U)pper or (L)ower case? ").strip().lower()
            if case == "u":
                print(str(i+1) + ". " + movie[0] + " (" + movie[1] + ")".upper())
            else:
        
                print(str(i+1) + ". " + movie[0] + " (" + movie[1] + ")")
            print()

Any help is greatly appreciated!

Your code is a great start, but I think some of your issues can be solved by refactoring to make it less complicated.

For example, I think if you used an additional variable it would have been more clear to see your issue. This line: print(str(i+1) + ". " + movie[0] + " (" + movie[1] + ")".upper()) is not doing what you think it is. The upper() method is only being applied to the ")" . To avoid this in the future, I suggest using an [f string]( https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/ and a local variable to store the output string. This would make it easier to read, and thus less error-prone. In addition, I'd suggest that you restructure your list movies logic to slightly decouple it from the if statements. This will further make it easier to read. For example, try this:

def list_movies(movies):
    #ask the user if they want it printed in upper or lower case using .upper()/.lower()

      for movie in movies:
          output_string = f"{str(i+1)}.{movie[0] ( {movie[1]} \n)}"

          case = input("Would you like it printed in (U)pper or (L)ower case? ").strip().lower()
          if case == "u":
              output_string = output_string.upper()
        
          print(output_string)

Now it is more clear where the upper case is being applied, and you don't need an else statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM