I'm starting to learn Python by throwing myself in the deep end and trying a bunch of exercises.
In this particular exercise, I'm trying to make a program to ask the name and age of the user and tell the user the year they're going to turn 100.
I tried putting in a yes/no input to ask if the user's birthday has passed this year, and give the correct year they will turn 100, based on that.
I wanted to incorporate a while loop so that if the user enters an answer that isn't "yes" or "no", I ask them to answer either "yes" or "no". I also wanted to make the answer case insensitive.
print("What is your name?")
userName = input("Enter name: ")
print("Hello, " + userName + ", how old are you?")
userAge = input("Enter age: ")
print("Did you celebrate your birthday this year?")
while answer.lower() not in ('yes', 'no'):
answer = input ("Yes/No: ")
if answer.lower() == 'yes':
print ("You are " + userAge + " years old! That means you'll be turning 100 years old in the year " + str(2019 - int(userAge) + 100))
elif answer.lower() == 'no':
print ("You'll be turning " + str(int(userAge) + 1) + " this year! That means you'll be turning 100 years old in the year " + str(2019 - int(userAge) + 99))
else:
print ('Please type "Yes" or "No"')
print ("Have a good life")
You should addd the input before trying to access the answer.lower method, so it will be something like:
answer = input('Yes/No: ')
while answer.lower() not in ('yes','no'):
answer = input('Yes/No: ')
Check geckos response in the comments: just initialize answer with an empty string
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 2 years ago.
Improve this question
I am trying to create a simple program which will ask the user to input an age and then will ask the user to input another age to find the difference.
The problem in my program arrives when I ask the user to confirm their age.
When I ask the user to confirm the age, if the user answers confirms their choice, I want the program to keep running. But currently, I am stuck in a cycle which even if the user inputs a confirmation, the program skips my if statement and always runs my else: statement.
#This program will prompt you to state your age and then will proceed to
#calculate how long till __ age
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" and yourWish == "yes" and yourWish == "y" and yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if desiredAge == 'yes' and desiredAge == 'Yes':
print(Yes())
else:
No()
choose()
print('Goodbye.')
There were some indentation errors and you used and keyword instead of or keyword
here is a working code
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" or yourWish == "yes" or yourWish == "y" or yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if yourWish == 'yes' or yourWish == 'Yes':
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
choose()
choose()
print('Goodbye.')
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
I have recently started learning Python, and the experience has been great, however, last night, I tried to make a simple program, and it is acting very strange
I have tried to change the locations of variables, and what they store/handle, and nothing I try seems to be working
def RF():
user_type = input("Are you a new user? ")
if user_type is "Yes" or "yes":
ID = random.randrange(1, 999999)
print("Your new ID Number is: " + str(ID))
name = input("Please enter your name: ")
password = input("Password: ")
ID = input("Account ID: ")
writtingID = open('Acc info.txt', 'w')
writtingID.write("ID: " + str(ID) + " | NAME: " + name + " | PASS: " + password)
writtingID.close()
elif user_type is "No" or "no":
name = input("Please enter your name: ")
password = input("Password: ")
ID = input("Account ID: ")
RF()
When the code is ran, I expect it to jump straight to asking for a name, but when I type "No" or "no", it for some reason runs the print("Your new ID Number is: " + str(ID)) from a different if statement
The statement if user_type is "Yes" or "yes": will always return true.
The reason for this is that the statement evaluates the same way as:
if (user_type is "Yes") or ("yes"):
The second parantheses ("yes") will always return true. And as #Error-SyntacticalRemorse pointed out, you want to use == instead of is (see Is there a difference between "==" and "is"?).
Solution 1:
if user_type in ["Yes", "yes"]:
Solution 2:
if user_type.lower() in ["yes", "y"]:
user_type = input("Are you a new user? ")
if user_type in ("Yes", "yes"):
ID = random.randrange(1, 999999)
print("Your new ID Number is: " + str(ID))
name = input("Please enter your name: ")
password = input("Password: ")
ID = input("Account ID: ")
writtingID = open('Acc info.txt', 'w')
writtingID.write("ID: " + str(ID) + " | NAME: " + name + " | PASS: " + password)
writtingID.close()
elif user_type in ("No", "no"):
name = input("Please enter your name: ")
password = input("Password: ")
ID = input("Account ID: ")
RF()
Check if the word is in a tuple. For an easier approach, just use the str.lower() method to get rid of the extra complexity.
AKA:
if user_type.lower() == "yes":
code
See how to test multiple variables against a value
I'm stuck with a problem that asks 5 questions. If any of them has the answer no It should print ALIEN! or else Cool.
This is what I have got so far:
human = input("Are you human? ")
human = input("Are you living on planet Earth? ")
human = input("Do you live on land? ")
human = input("Have you eaten in the last year? ")
human = input("Is 2 + 2 = 4? ")
if human == "yes":
print("Cool")
elif human == "no":
print("ALIEN!")`
You could use any() to check if any of the answers to questions is 'no' and print message accordingly:
human = [input("Are you human? "), input("Are you living on planet Earth? "),
input("Do you live on land? "), input("Have you eaten in the last year? "), input("Is 2 + 2 = 4? ")]
if any(x.lower() == 'no' for x in human):
print('ALIEN!')
else:
print('Cool')
You have the variable human that is changed every time and given a new value using input() Try and make multiple variables instead of just using human.
human = input("Are you human? ")
var1 = input("Are you living on planet Earth? ")
var2 = input("Do you live on land? ")
var3 = input("Have you eaten in the last year? ")
var4 = input("Is 2 + 2 = 4? ")
if(human == "yes"):
print("Cool")
elif(human == "no"):
print("ALIEN!")
If you're not worried about storing the variables and only care if one of the questions comes up as "no" or "n":
x=["human?","on earth?", "on land?","someone who eats food?","sure that 2+2=4?"]
for i in x:
if input("Are you {}".format(i)).lower() in ['no','n']:
print("Alien!")
break
else:
print("Cool")
Just a side note: Here you can see a great case for using a for loop since there is code that is repeated many times. Personally, I would do the following to solve this problem.
Create a list of questions
Iterate through the list of questions
If any answer is no, break and print Alien.
Now for the code:
# Initialize our list
lst = ["Are you human? ", "Are you living on planet Earth? ","Do you live on
land? ","Have you eaten in the last year? ","Is 2 + 2 = 4? "]
#Create a flag for Alien
flag = False
#Iterate through the list
for question in lst:
answer = input(question)
if answer == 'no':
#Print alien
print('Alien')
#Change Flag
flag = True
#Break out of the loop
break
#Check to see if our flag was thrown during the loop
if flag == False:
print('cool')
If you want more help on solving coding challenges like this one, check out this intro to python course: https://exlskills.com/learn-en/courses/learn-python-essentials-for-data-science-intro_to_python/content
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
I am in spyder trying to run a fairly simple python code (python 3.6.4), but when I run the code and use the input statements, it says the names are not defined, even though they should be.
#Module 4 project
#4/25/18
#Henry Degner
#This project is meant to determine whether or not certain people are qualified to go to an exclusive concert
#create function askAge, which will use an input statement and comparison operators to see if the user is old enough
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
#create function askHearing, yes or no question to do you have sensitive hearing
def askHearing():
hearing = str(input("Do you have sensitive hearing? "))
if( str(hearing) == "yes","y" ):
hearingReq = "do"
elif( str(hearing) == "no","n"):
hearingReq = "don't"
else:
print("Please type yes, or y, if you have sensitivehearing. If not, type no or n.")
hearing = str(input("Do you have sensitive hearing? "))
#create function askTicket, yes or no question to do you have a ticket
def askTicket():
ticket = str(input("Do you have a ticket for the concert? "))
if( str(ticket) == "yes","y" ):
ticketReq = "do"
elif( str(ticket) == "no","n"):
ticketReq = "don't"
else:
print("Please type yes if you have a ticket, or no if you don't.")
ticketReq = str(input("Do you have a ticket for the concert"))
#create function askFun, yes or no question to are you willing to have an awesome time
def askFun():
fun = str(input("Are you willing to have a great time?"))
if( str(fun) == "yes","y"):
funReq = "do"
elif( str(fun) == "no","n" ):
funReq = "don't"
else:
print("Please type 'yes' or 'no'")
fun = str(input("Are you willing to have a great time?"))
#use def main():
def main():
#print situation, will ask some questions to see if you can attend concert
print("Welcome to the Henry Degner Concert Venue! We have to ask you a few questions before we let you into the venue.")
#use askAge
askAge()
#use askHearing
askHearing()
#use askTicket
askTicket()
#use askFun
askFun()
#print user's answers
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
#use if-else statement, if all three conditions match requirements, print you can attend concert. If not, print you can't attend
#use main()
main()
the error outputs as
File "C:/Users/henry/Documents/Current Classes/Foundations of Programming/Module 4 project/Module 4 project script.py", line 60, in main
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
NameError: name 'age' is not defined
It also says that all of the other names in line 60 aren't defined. Thanks in advance!
You are getting NameError: name 'age' is not defined because variables from different functions are not shared until you declare them global or you return them from one method to another.
Read more about Python Scopes and Namespaces
Just return value from function to main method.
Returning value from method
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
return age
def main():
...
age = askAge()
.....
Same you need to do it for all methods,
askHearing()
askTicket()
askFun()
Hi i wrote some code for a maths program and wanted some help to validate user input. I want the program to, when the user ignores a question and simply presses the enter key for the next question, to show them the exact same question again and notify them saying every question must be attempted. Heres the code i have so far
import time
import random
msg=0
questionsAsked=0
score=0
op = ["-","*","+"]
username= input("What is your name? ")
print("Okay "+username+ " lets begin the test. Good luck!")
praise= ["Well done!","Great job!", "Spot on!", "Perfect!"]
wrong = ["Unlucky!", "Not quite", "Incorrect"]
def actual(num1,num2,operation):
actual=eval(str(num1) + operation + (str(num2)))
return actual
def useranswer(num1,num2,operation):
useranswer=int(input(str(num1)+operation+str(num2)+"= "))
return useranswer
while questionsAsked <10:
num1 = random.randint(0,12)
num2 = random.randint(0,12)
operation = random.choice(op)
praiseMsg= random.choice(praise)
wrongMsg= random.choice(wrong)
if useranswer(num1,num2,operation) != actual(num1,num2,operation):
print(wrongMsg)
else:
print(praiseMsg)
score= score+1
questionsAsked=questionsAsked+1
else:
if score>5:
msg= str("Well done "+username+"! You scored over 50%")
else:
msg=str("Better luck next time " + username)
print("You scored " +str(score)+ " out of 10. \n" +msg )
time.sleep(3)
username = raw_input("What is your name? ")
while not username:
username = raw_input("Not understood. What is your name?")
You could wrap this in a function:
def insist_upon_answer(prompt):
answer = raw_input(prompt)
while not answer:
answer = raw_input("All questions must be answered. {}".format(prompt)
return answer
and call it:
name = insist_upon_answer("What is your name?")
Like triphook's answer, for Python 3:
username = input("Input: ")
while username=="":
username = input("Input (again): ")