Home > Blockchain >  While loop not working when you run the code
While loop not working when you run the code

Time:04-02

def chineseZodiac(year):    
    if (year - 2000) % 12 == 0:
       sign = 'Dragon'
    elif (year - 2000) % 12 == 1:
       sign = 'Snake'
    elif (year - 2000) % 12 == 2:
       sign = 'Horse'
    elif (year - 2000) % 12 == 3:
       sign = 'sheep'
    elif (year - 2000) % 12 == 4:
       sign = 'Monkey'
    elif (year - 2000) % 12 == 5:
       sign = 'Rooster'
    elif (year - 2000) % 12 == 6:
       sign = 'Dog'
    elif (year - 2000) % 12 == 7:
       sign = 'Pig'
    elif (year - 2000) % 12 == 8:
       sign = 'Rat'
    elif (year - 2000) % 12 == 9:
       sign = 'Ox'
    elif (year - 2000) % 12 == 10:
       sign = 'Tiger'
    else:
       sign = 'Hare'
    return sign
year = int(input("enter year:"))
while (year <= 1980 and year >= 2014):
    print("your chinese zodiac is ", chineseZodiac(year))

'there is no error but the print under the while loop doesn't show when you run the code... please help me, im noob :-('

CodePudding user response:

Building on my comment. The immediate cause of your problem is there's no year that can be less than 1980 and greater than 2014. Also because you have a while loop, so I think you want to continually ask for a year until a valid year is entered

def chineseZodiac(year):
        
    signs = {
        0: 'Dragon',
        1: 'Snake',
        2: 'Horse',
        3: 'sheep',
        4: 'Monkey',
        5: 'Rooster',
        6: 'Dog',
        7: 'Pig',
        8: 'Rat',
        9: 'Ox',
        10: 'Tiger',
        11: 'Hare'
    }
    
    return signs[( year - 2000 ) % 12]

year = 0

in_range = lambda year: (1980 <= year <= 2014)
while not in_range(year):
    year = int(input("enter year:"))
    
    if in_range(year):
        print("your chinese zodiac is", chineseZodiac(year))

CodePudding user response:

You input a value for year and then check if it is within the accepted timespan. ok. But if you do this with a while-loop, you will just reprint your output again and again for eternity.

Just use a one time if-statement like so:

if year >= 1980 and year <= 2014:
    print(f"your chinese zodiac is {chineseZodiac(year)}")

Also note the nicer F-String-Formatting in the print statement.

CodePudding user response:

Replace “while” with “if”.

This will only show output for years prior to 1981 or after 2013.

  • Related