porpo
Posts: 2
Joined: Sun Oct 06, 2019 12:45 pm

def function get_color does not show_msg

Sun Oct 06, 2019 12:52 pm

Code: Select all

from sense_hat import SenseHat
from time import sleep

sense = SenseHat()
sense.set_rotation(180)
red = (255, 0, 0)
def get_color(color):
    keep_looping = True
    no_of_try=1
    while keep_looping:
        
        #color_str=input("Enter the value of the" + color + \ "color for message (0 to 255):")
        while no_of_try < 4:
          color_str = input("Enter the value of the " + color + " color for message (0 to 255):")
          no_of_try += 1
          
          if int(color_str) in range(0, 256):
            print(color_str)
            return color_str
          else:
              print("Input only 0 to 255.")      
        print('number of tries exceeded')
        return 0      
          
          
#---------------------------------------------------------          
r_int = get_color("red")
g_int = get_color("green")
b_int = get_color("blue")
msg_color = (r_int, g_int, b_int)
sense.show_message("I got it!", text_colour = msg_color, scroll_speed = 0.05)

scotty101
Posts: 3750
Joined: Fri Jun 08, 2012 6:03 pm

Re: def function get_color does not show_msg

Mon Oct 07, 2019 4:22 pm

The problem is to do with the value your get_color function returns. show_message expects the colour to be a list of integers not a list of strings so get_color must return an integer

See a working version at https://trinket.io/python/1e485d316c

Code: Select all

def get_color(color):
    keep_looping = True
    no_of_try=1
    while keep_looping:
        
        #color_str=input("Enter the value of the" + color + \ "color for message (0 to 255):")
        while no_of_try < 4:
          color_str = input("Enter the value of the " + color + " color for message (0 to 255):")
          no_of_try += 1
          
          if int(color_str) in range(0, 256):
            print(color_str)
            #Changed the below line
            return int(color_str)
          else:
              print("Input only 0 to 255.")      
        print('number of tries exceeded')
        return 0  
Also note that your code doesn't handle the case where the user enters something other than a number, for example "q" and an exception will be raised. You might want to add a try/except to handle that condition.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Return to “Astro Pi”