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

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?

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.

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)

Related

Test user input until conditions are met

In python, I need the input of a user to be between a range of years.
Using if statement returns the error (if he's out of range) to the user and invite him to make another choice of year.
The second time he chooses a year need to be tested again with the same conditions. Which doesn't happen yet.
What would be the best solution to have his input tested all over again, until conditions are met ?
Here's some piece of the actual code
year = input("Enter a year between 1900 and 2099 : ")
if year >= "1900" or year <= "2099":
year = (input("The year you entered is out of range, please try again : "))
year = int(year)
Thanks in advance
Explanation:
You can use a while loop. A while loop will run until a certain condition is False. In this case it will run until the break keyword is used, because the condition will always be True. You can also use try and except do make sure the input it an integer. And use continue to start the loop again if it is not an integer.
Code:
prompt = "Enter a year between 1900 and 2099: "
while True:
year = input(prompt)
try:
year = int(year)
except ValueError:
prompt = "The year you entered is out of range, please try again : "
continue
if year >= 1900 or year <= 2099:
break
else:
prompt = "The year you entered is out of range, please try again : "

Returning dates in different format in python

I have made a function in the format: day/month/year. I would like to make another function that asks the user for example: "When do you want to come?" and depending on what month the user say I want to print out a answer.
The problem: I don't know how to make the function that asks the user for the format: day/month/year without limit the years, I would like the user to enter any year and still be able to get the same answers as another any year (but different month).
enter code here
import datetime
def dateformat(date):
return datetime.datetime.strptime(datumet, "%d/%m/%Y")
def ask_user():
winter = dateformat('1/1/2020') <= dateformat('31/3/2020')
spring = dateformat('1/4/2020') <= dateformat('31/5/2021')
summer = dateformat('1/6/2020') <= dateformat('31/9/2021')
autumn = dateformat('1/10/2020') <= dateformat('31/12/2021')
a = dateformat(input("When do you want to come"))
if a == winter:
print("Hi")
if a == spring:
print("bye")
if a == summer:
print("ok")
if a == autumn:
print("no")
My question: How can I make this code work for any year? I would like to be able to type any year but inside the month and get the same output. If I only return %d/%m in the dateformat-function the user will not be able to type: day/month/year. Is there maybe a better way of returning the format?
I don't think your code does what you expect it to do. For one, 31/9/2021 is not an actual date so dateformat would throw an error. Second, dateformat('1/1/2020') <= dateformat('31/3/2020') checks if the first date is less than or equal to the second, so winter, spring, etc. are booleans (and all True). With a == winter, you're comparing a date to a boolean, so they'll never be equal and you won't get any output.
What you actually want to do is read in the date, and see if its month attribute is between certain limits, because the value of a.year doesn't affect the season. So:
datumet = input("When do you want to come? ")
a = datetime.datetime.strptime(datumet, "%d/%m/%Y")
if a.month <= 3:
print("Hi, you're coming in winter")
elif a.month <= 5:
print("Spring")
elif a.month <= 9:
print("Summer")
else:
print("Autumn")
The same applies when your ranges don't end at the end of the year. For example, if winter lasted the start of November through the end of February,
if a.month >= 11 or a.month <= 2:
print("Hi, you're coming in winter")
elif a.month <= 5:
print("Spring")
elif a.month <= 9:
print("Summer")
else:
print("Autumn")

Need to have prompts for input in Python

I am new to Python, my second week doing it. I have a code I wrote where one enters year a car was made and it outputs price.
When I enter 1961, I get what I want. When I enter 1962 I get my result.
How can I structure the code such that if I enter any given year period it gives a correct price? Outside the range, it gives an error message. After entering a year and getting a result the user has the option to enter another year or to exit.
year = int(input('Enter year:\n'))
if year < 1962:
print('Car did not exist yet!')
print('Please enter a valid year from 1962'),int(input('Please enter another year:\n'))
if year <= 1964:
print('$', 18500), int(input('Please enter another year:\n'))
if year >= 1965 <=1968:
print('$', 6000), int(input('Please enter another year:\n'))
if year >=1969 <=1971:
print ('$', 12000), int(input('Please enter another year:\n'))
Thank you for any feedback. I tried if/elif to no avail.
You could use a while loop to overcome this issue.
An example of this could include:
year = int(input('Enter year: '))
while year: # this line forces the program to continue until the user enters no data
if year < 1962:
print('Car did not exist yet!')
print('Please enter a valid year after 1962')
elif year <= 1964:
print('$18500')
elif year >= 1965 <= 1968:
print('$6000')
elif year >= 1969 <= 1971:
print('$12000')
else:
print('Error Message') # You can change the error message to display if the year entered is after 1971
year = int(input('Please enter another year: '))

making an input into a variable in python

I am very new to python and need some help, I am trying to make a simple if/else script.
my previous version worked as it should and I have have to make the only change of a user entering a variable rather than a pre-determined variable. But I get a syntax error on the final line, can anybody show me where I am going wrong.
my code is
hour = input('enter an hour')
if hour >= 0 and hour < 12:
clock = hour, 'pm' # assigning the variable here as necessary
elif hour >= 12 and hour < 23:
clock = hour, 'pm' # assigning the variable here as necessary
else:
clock = 'That is not a time on the clock.'
print(clock)
thanks in advance for your help.
Multiple problems here:
In Python indentation (the spaces from a line or tabs if you wish) are important to distinguish different scopes of the code like functions, if statements etc. Your first line has such invalid indentation.
input('enter an hour') This function reads an input from the user and returns it as a string, regardless if you provide a numeric value. You need to use int() to convert it into an actual numeric value, so that you can then do range checks like "if is greater than 0 and less than 10" for example. Obviously, if you don't convert it to integer and you are working with strings you cannot do such range checks as the value is not treated as a numeric value.
Here is a working copy:
hour = int(input('Enter an hour: '))
if hour >= 0 and hour < 12:
clock = "{}am".format(hour)
elif hour >= 12 and hour < 23:
clock = "{}pm".format(hour)
else:
clock = 'That is not a time on the clock.'
print(clock)
There are 3 errors:
Your first line should not be indented.
Convert your input to numeric type, e.g. float or int.
Hours between 0 and 12 should be "am" rather than "pm".
This will work:
hour = float(input('enter an hour'))
if hour >= 0 and hour < 12:
clock = hour, 'am' # assigning the variable here as necessary
elif hour >= 12 and hour < 23:
clock = hour, 'pm' # assigning the variable here as necessary
else:
clock = 'That is not a time on the clock.'
print(clock)
The error is IndentationError: unexpected indent This means you write the line of code indented. that's incorrect. To solve it remove the spaces before first line.
You also have to specify the type of input.
hour = int(input('enter an hour'))

Python how to convert the second value in a list to int

I am presently building a simple program that will determine a person's horoscope sign depending on the month and date they assign.
I am running into issues checking the 2nd value in a list, I have to convert only the second value to an int.
Here is what I have so far:
user_day_month = input("Enter your birth month and day").lower().split(' ')
print(user_day_month)
user_sign = ""
if (user_day_month[0]=="january" and user_day_month[1]>=20) or (user_day_month[0]=="february" and user_day_month[1]<=18):
user_sign = "Aquarius"
print(user_sign)
elif (user_day_month[0]=="february" and user_day_month[1]>=19) or (user_day_month[0]=="march" and user_day_month[1]<=20):
user_sign = "Pisces"
Unpack the user's input into two separate named variables, and then convert one of them to an integer:
month, day = input("Enter your birth month and day").lower().split(' ')
day = int(day)
You can then refer to each of these variables directly:
if (month=='january' and day>=20) or...
The messier, more repetitive alternative would be to convert the day to an integer within the if statement:
if (user_day_month[0]=='january' and int(user_day_month[1]>=20)) or...
That's not the best option, as you end up casting with int multiple times. The first option is much cleaner.
As an intermediate possibility, you could access the list of user input and convert that value:
user_day_month = input("Enter your birth month and day").lower().split(' ')
user_day_month[1] = int(user_day_month[1])
And then use your original if statements:
if (user_day_month[0]=="january" and user_day_month[1]>=20) or...
But the first option is best.
I've tried to use the solution above but the line
month, day = input("Enter your birth month and day").lower().split(' ')
really confused me. I don't know what type of input console expects from me. I tried different tactics like putting space between or putting nothing or putting a comma... Didn't work for me.
What I recommend is separate your inputs into two different variables line that:
day = int(input("Input the day when you were born: ")) # this will be an integer
mon = input("Input the month when you were born: ").lower() # this will be a string
If it is essential for you to have those in an array, you can do this:
dateofbirth = [ int(input("Input the day when you were born: ")), input("Input the month when you were born: ").lower() ]
Now you could easily acces those using [ ].
>>> Input the day when you were born: 23
>>> Input the month when you were born: December
>>> dateofbirth[0]
23
>>> dateofbirth[1]
'december'
Some advice about the months below
As we have total of 12 signs and your if statement consists of comparing the date and month of birth with some key values to determine the sign of a person you'll have to type in approximately 22 different months in your if else statements.
That's what I mean:
if (user_day_month[0]=="january" and user_day_month[1]>=20) or (user_day_month[0]=="february" and user_day_month[1]<=18):
user_sign = "Aquarius"
print(user_sign)
elif (user_day_month[0]=="february" and user_day_month[1]>=19) or (user_day_month[0]=="march" and user_day_month[1]<=20):
user_sign = "Pisces"
That's from your example and here at some point you've already typed in "january", "february" and "february" again. I can predict that you'll continue doing this which is long, boring and inefficient.
Better create an array of months like that:
months = [ None, "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" ]
Adding None as the first item will allow you to call months normally, according to their numbers in the calendar. January, for instance will be months[1] as always.
Using this construct will allow you to shorten your conditional statements and illuminate spelling errors.
if (month == months[1] and day >= 19) or (month == months[2] and day <= 20):
sign = "Pisces"
print(sign)

Categories