"If" statement gets ignored when function is recalled [closed] - python

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.')

Related

Error starting a function inside of an if statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a def running inside of an if function, but when it's supposed to start it doesn't. Below is a copy of the code I wrote. Before I had the if statement for the two games, it ran just fine just as a single def.
print("Please choose from one of the following: \n")
print("1. Tic-Tac-Toe. \n")
print("2. Number Guessing Game. \n")
playerQuestion = input("")
print("You have selected game " + playerQuestion + "! Starting the game up. . . ")
sleep(2)
if playerQuestion == 1:
print("1")
def guessingGame():
for i in range(5):
print("")
playerGuess = ()
computerNumber = (randrange(100))
playerGuess = int(input("I am thinking of a number... Please make your first guess! "))
tries = 1
while playerGuess != computerNumber:
tries += 1
if (playerGuess > computerNumber):
print("Lower! \n")
playerGuess = ()
playerGuess = int(input("I am thinking of a number... Please make your next guess! "))
elif (playerGuess < computerNumber):
print("Higher! \n")
playerGuess = ()
playerGuess = int(input("I am thinking of a number... Please make your next guess! "))
if playerGuess == computerNumber:
tries = str(tries)
print("You got it in " + tries + " tries! Congratulations! ")
again = str(input("Do you want to play again (type yes or no): "))
again = again.lower()
again = again[:1]
if again == "y":
guessingGame()
else:
sleep(1)
print("Thank you for playing! ")
guessingGame()
sleep(10)
else:
def TicTacToe():
board = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
for i in range(5):
print(board)
Change to
if playerQuestion == '1':

How to keep on calling from a infinite list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am making a chart that calls people from a list called readerlist. How do I call the 1st 2nd 3rd... from an infinite list without manually writing it all out.
def isNumber(s):
try:
int(s)
return True
except ValueError:
return False
readerlist = []
booklist = []
print ("welcome to the book club system".upper())
print()
while True :
print ("\n------------------------------------")
print ("|".ljust(12) + "OPTIONS MENU".ljust(23) + "|")
print ("|".ljust(35) + "|")
print ("| 1: Modify book total".ljust(35) + "|")
print ("| 2: Displays people and books out".ljust(35) + "|")
print ("| 3: Quit".ljust(35) + "|")
print ("------------------------------------")
while True :
choice = input("\nEnter your selection: ")
if choice == "1" or choice == "2" or choice =="3":
break
print ("Invalid option")
#3 - quit
if choice == "3" :
break
#2 - display totals so far
elif choice == "2" :
print ("\n\n")
print ("".ljust(10) + "BOOKS READ".center(30))
print ("NAME".ljust(15) + "BOOKS".ljust(15))
print (readerlist[0].ljust(15) + str(booklist[0]).ljust(15))
print (readerlist[1].ljust(15) + str(booklist[1]).ljust(15))
print (readerlist[2].ljust(15) + str(booklist[2]).ljust(15))
print (readerlist[3].ljust(15) + str(booklist[3]).ljust(15))
print (readerlist[4].ljust(15) + str(booklist[4]).ljust(15))
#1 - enter a new user, or update an existing user's total
elif choice == "1":
while True:
name = input("Enter your name: ")
if name != "<Empty>":
readerlist.append(name)
break
while True:
books = (input("Enter number of books read: "))
if isNumber (books):
books = int(books)
break
else:
print("Invalid number")
print ("")
print ("Thank you for using the Library program")
input ("<Hit ENTER to exit>")
Maybe this is what you want:
elif choice == "2" :
print ("\n\n")
print ("".ljust(10) + "BOOKS READ".center(30))
print ("NAME".ljust(15) + "BOOKS".ljust(15))
for i in readerlist:
print(readerlist[i].ljust(15) + str(booklist[i]).ljust(15))

'while' loop in Python

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

cant get a with a while loop inside a while loop to work

while loop == True: #creates loop, and uses previously defined 'loop'
try:
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
invtimer()
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
invtimer()
while loop == True:
showans = input('''Wrong answer.
Would you like to see the answer? (yes)(y)
or try again? (no)(n) ''')
if showans in ["yes", "y", "Yes", "Y"]:
invtimer()
print("The answer is " + str(num1 * num2) + "!")
break
elif showans in ["no", "n", "No", "N"]:
loop == False
else:
print("That is not an option! ")
loop == False
except ValueError:
print("That is not a number! ")
I need help with getting the second loop == False to link back the fist while loop. when I run it, it keeps going back to the second while loop.
You were using the == operator. This operator is only meant to be used in conditional statements and loops, not when assigning variables. When you assign False to a variable use = instead
while loop == True: #creates loop, and uses previously defined 'loop'
try:
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
invtimer()
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
invtimer()
while loop == True:
showans = input('''Wrong answer.
Would you like to see the answer? (yes)(y)
or try again? (no)(n) ''')
if showans in ["yes", "y", "Yes", "Y"]:
invtimer()
print("The answer is " + str(num1 * num2) + "!")
break
elif showans in ["no", "n", "No", "N"]:
loop = False
else:
print("That is not an option! ")
loop = False
except ValueError:
print("That is not a number! ")

Improving Code - Python [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
This code works but is not as efficent as possible. Can you tell me how to make it more efficent? I belevie there is away to not have so many functions but I have forgotten how. The script is a multi choose quiz. I have defined each question as a new function. Is this the best way to do this?
def firstq (): # 1st Question
global q1list,answer1
q1list = ["Wellington","Auckland","Motueka","Masterton"]
q1count = 0
print ("Question 1")
print ("From which of the following Towns is the suburb NEWLANDS located?")
while q1count < 4:
print (q1count," ",q1list[q1count])
q1count = q1count + 1
answer1 = int(input("What number answer do you choose?"))
if answer1 == 0: print ("Correct answer!")
elif answer1 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def secq (): #Second Question
global q2list,answer2 # Makes answer2 and q2list avalible anywhere on the page.
q2list = ["Wellington","Christchurch","Pairoa","Dunedin"] # List of answers to choose from.
q2count = 0 # defines what the q2 count is. SEE BELOW
print ("Question 2")# prints "question 2"
print ("What NZ town is known for L&P?") # Prints the question
while q2count < 4:
print (q2count," ",q2list[q2count]) # Whilst the number of answers (q2list) is below 4 it will print the next answer.
q2count = q2count + 1
answer2 = int(input("What number answer do you choose?")) # asks for answer
if answer2 == 2: print ("Correct answer!") # If answer is correct, prints "Correct answer"
elif answer2 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.") # If answer is correct, prints "Sorry! Incorrect Answer. Better luck with the next Question."
print("Next Question below:") # prints "Next Question
# these provide spacing!
print(" ")
print(" ")
def thrq ():
global q3list,answer3
q3list = ["Lewis Carroll","J.K. Rowling","Louis Carroll","Other"]
q3count = 0
print ("Question 3")
print ("Who wrote the book Alice In Wonderland?")
while q3count < 4:
print (q3count," ",q3list[q3count])
q3count = q3count + 1
answer3 = int(input("What number answer do you choose?"))
if answer3 == 0: print ("Correct answer!")
elif answer3 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fouq ():
global q4list,answer4
q4list = ["WA","DC","WD","WC"]
q4count = 0
print ("Question 4")
print ("What is the abbreviation for Washington?")
while q4count < 4:
print (q4count," ",q4list[q4count])
q4count = q4count + 1
answer4 = int(input("What number answer do you choose?"))
if answer4 == 1: print ("Correct answer!")
elif answer4 != 1: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fivq ():
global q5list,answer5
q5list = ["Yes","No, they're found around New Zealand","No","No, they're found around the UK"]
q5count = 0
print ("Question 5")
print ("Are walruses found in the South Pole?")
while q5count < 4:
print (q5count," ",q5list[q5count])
q5count = q5count + 1
answer5 = int(input("What number answer do you choose?"))
if answer5 == 2: print ("Correct answer!")
elif answer5 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sixq ():
global q6list,answer6
q6list = ["G.M.","General M's","G Motors","Grand Motors"]
q6count = 0
print ("Question 6")
print ("What is the other name for General Motors?")
while q6count < 4:
print (q6count," ",q6list[q6count])
q6count = q6count + 1
answer6 = int(input("What number answer do you choose?"))
if answer6 == 0: print ("Correct answer!")
elif answer6 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sevq ():
global q7list,answer7
q7list = ["Greece","USA","Egypt","Italy"]
q7count = 0
print ("Question 7")
print ("Which of the following countries were cats most honored in?")
while q7count < 4:
print (q7count," ",q7list[q7count])
q7count = q7count + 1
answer7 = int(input("What number answer do you choose?"))
if answer7 == 2: print ("Correct answer!")
elif answer7 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def eigq ():
global q8list,answer8
q8list = ["I find","I see","I presume","I am"]
q8count = 0
print ("Question 8")
print ("Complete this phrase-Dr. Livingstone,")
while q8count < 4:
print (q8count," ",q8list[q8count])
q8count = q8count + 1
answer8 = int(input("What number answer do you choose?"))
if answer8 == 2: print ("Correct answer!")
elif answer8 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print(" ")
print(" ")
def end():
if answer1 == 0 and answer2 == 2 and answer3 == 0 and answer4 ==1 and answer5 ==2 and answer6 ==0 and answer7 == 2 and answer8 == 2: print("YAY, all questions correct! You have won the 1 million!")
else: print("Sorry you have some incorrect questions! You have not won any money! :(") # If all answers are correct, this will display YAY, all questions correct! You have won the 1 million! If not it will print Sorry you have some incorrect questions! You have not won any money! :(.
def printorder ():
# Defines ther order that it will be printed in
firstq()
secq()
thrq()
fouq()
fivq()
sixq()
sevq()
eigq()
end()
name = l" " # while name is blank it will continue
while name != "quit": #While the name is not quit it will continue. If name is quit it will stop.
print ("The $1,000,000 Quiz! Can you win the 1 Million?")#Prints Welcome Message
name = input("Lets Get Started! What is your name: ")# asks for name
if name == "quit":
break # if the name is quit it will stop if not....
printorder()# ....prints printorder
This is just a pointer.
Instead of
def sixq():
global q6list, answer6
...
create a function
def question(qlist, qanswer):
...
and pass in qlist and qanswer as parameters, much of the code is duplicated and can be eliminated this way. And you also eliminate the use of globals at the same time. You can return whatever value(s) you need to the calling code at the end of this function using return. (note that Python allows you to return more than one value)
Adjust above as needed, ie if you need to supply another parameter etc. Essentially you want to factor out duplicate code into a single function, and provide the necessary parameters for what makes it unique.
Finally, using a single function in place of eight, will making maintaining your code much easier. If you find a problem with your code, or simply want to change something, you'll only have to correct it in one place, rather than in 8 different functions .. this is a major benefit.

Categories