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: '))
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm an absolute beginner at python and I am trying to make a little game where you can see in what year you'll be a certain age. The first section that calculates when you will be 100 years old works but when I come to the second part and I answer with yes it asks the questions until I fill in the current age, after that it just closes down.
This is my code:
import datetime
import time
name = input("What is your name: ") # name input
age = int(input("How old are you: ")) # age input
year1 = str((datetime.datetime.now().year - age)+100) # calculates in what year age will be 100
print(name + " will be 100 years old in the year " + year1)
answer = input("Do you want to know another age: ")
if answer == "yes":
age1 = int(input("What age do you want to know: ")) # asks for different age than 100 if answer was yes
age = int(input("How old are you: ")) # age input
year2 = str((datetime.datetime.now().year - age)+age1) # calculates in what year input age will be
print(name + " will be", age1, "years old in the year " + year2)
if answer == "no":
print("Have a nice day!")
time.sleep(5)
exit()
Can anyone tell me why it does this and how to fix it?
you can use while True and break when answer is no, like this:
import datetime
import time
name = input("What is your name: ") # name input
age = int(input("How old are you: ")) # age input
year1 = str((datetime.datetime.now().year - age)+100) # calculates in what year age will be 100
print(name + " will be 100 years old in the year " + year1)
while True:
answer = input("Do you want to know another age: ")
if answer == "yes":
age1 = int(input("What age do you want to know: ")) # asks for different age than 100 if answer was yes
age = int(input("How old are you: ")) # age input
year2 = str((datetime.datetime.now().year - age)+age1) # calculates in what year input age will be
print(name + " will be", age1, "years old in the year " + year2)
if answer == "no":
print("Have a nice day!")
break
output:
What is your name: sample
How old are you: 24
sample will be 100 years old in the year 2097
Do you want to know another age: yes
What age do you want to know: 200
How old are you: 24
sample will be 200 years old in the year 2197
Do you want to know another age: yes
What age do you want to know: 300
How old are you: 24
sample will be 300 years old in the year 2297
Do you want to know another age: no
Have a nice day!
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 : "
salary=0
salaryArray=[]
loop=0
noYears=int(input("How many years do you want to do salaries for? "))
for i in range(0,noYears):
while loop==0:
print()
print("You can add multiple sources of income, one at a time")
salaryType=input("Do you want to put in your salary hourly or yearly? (h/y) ")
if salaryType=="y":
salarySection=float(input("What is your salary? "))
salary=salarySection+salary
else:
salaryHourly=float(input("What are you payed per hour? "))
salaryWeekly=float(input("How many hours per week will you work? "))
salaryYearly=float(input("How many weeks per year will you work? "))
print()
salarySection=salaryHourly*salaryWeekly*salaryYearly
salary=salary+salarySection
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
loop=1
For some reason the for i in range(0,noYears) isn't working?
It just moves on to the next line of code after doing it through once - even though I put the answer to noYears as 3.
Anyone know why this might be as I cannot see what is wrong?
:)
The code isn't working because the while loop never executes. You could solve this two ways.
Use a break statement instead of setting loop to 1:
#previous code
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
break
Reset the variable loop to 0 inside of the for loop:
for i in range(0,noYears):
loop = 0
while loop==0:
# remaining code
I'm having trouble implementing a function into this program. The program I have currently works fine on its own without the function but I still need to find a way to put def finance(income, salesPrice): into it. I also need to invoke the function with this: print(finance(income, salesPrice)). I tried different ways but whenever I try to invoke the function, it says that income is not defined.
This is what I have to make:
The function will test whether a person is qualified to finance an expensive car. They are qualified if their annual income is greater than $100,000 and the sales price is less than $1,000,000. The function returns a message to the program stating whether the person is qualified or not. The program invokes the finance() function with this print statement: print (finance (income, salesPrice)) and the user input the income and sales price.
def finance(income,salesPrice):
income = float(input("Please enter annual income: "))
while (income <= 0):
income = float(input("Invalid input! Please enter positive value: "))
income += 1
salesPrice = float(input("Please enter sales price of car: "))
if (income>100000 and salesPrice<1000000):
print("You are qualified to purchase this car.")
else:
print("You are not qualified to purchase this car.")
result = print(finance(income,salesPrice))
The problem is indentation + You need to return a variable. EDIT: I edited the code based on your problem
def finance(income, sales_price):
if income > 100000 and sales_price < 1000000:
return "You are qualified to purchase this car."
else:
return "You are not qualified to purchase this car."
salesPrice = float(input("Please enter sales price of car: "))
income = float(input("Please enter annual income: "))
while income <= 0:
income = float(input("Invalid input! Please enter positive value: "))
income += 1
print (finance (income, salesPrice))
You make an indentation error, your line while (income <= 0) is outside of your function, you have to indent it.
More informations about indentation in python here.
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)