Jack Rogers
Jack Rogers

Reputation: 695

Variable not defined error, and if statement doesn't execute

I'm trying to code horoscope that comes after the user input the birth month and day.

print("To figure out your horoscope, enter the following questions")
month = int(input("what month were you born(january,december,august: "))
days = int(input("what day were you born(2,4,12: "))
if month == 'december':

    astro_sign = 'Sagittarius are nice people' if (day < 22) else 'Capricon are adventurous'
print(astro_sign)

However, every time I execute the code, it gives me an error:

print(astro_sign)
NameError: name 'astro_sign' is not defined

Currently, I only put one month which is 12 and day is below 22, later on when one piece of this code works, I'm going to add more months. Can anyone please help me?

Upvotes: 2

Views: 7021

Answers (2)

Babar
Babar

Reputation: 1

print("Please enter your birthday")

month = int(input("month: "))

day = int(input("day: "))

if month == '12':

      print('Sagittarius are nice people')

if day < 22:

      print('Capricon are adventurous')

see if this actually works for you (Tell me if I got it all wrong please)

Upvotes: -1

idjaw
idjaw

Reputation: 26578

That is because you are introducing/creating your astro_sign variable inside your conditional if month == '12':. So, every time you enter something that is not in fact '12', you will end up getting this error.

Simply, create your astro_sign before the conditional, so it is at least available in the event you don't enter your condition:

astro_sign = ''
if month == '12':
    # rest of code here

Furthermore, you will never actually enter that condition with your current code, because you are casting your input for month as an int here:

month = int(input("month: "))

However, your condition is explicitly checking for a string per your single quotes: '12'.

So, instead of:

if month == '12':

You in fact should do:

if month == 12:

Remove the single quotes, so you are comparing int to int.

Upvotes: 3

Related Questions