Calling another function error - python

This is supposed to be a test program on which I can practice python. I defined main and built up the code. When the answer is right, I press 'Y' and it is supposed to jump to the next function which is the next code block after this one ends. The error is get is this:
NameError: name 'logic_ques' is not defined.
How do I start the next function after I press 'y' and not get an error? Is the problem the order?
def main():
pts = 0
numberStr = input("Please enter the sum of 251 and 516: \n ")
num = int(numberStr)
print ('You have entered: ', num)
if (num == 767):
pts += 1
print ('The answer is correct!')
print ('You currently have ', pts, 'point(s).')
continue1 = input('Press any key to see the next question.')
logic_ques()
else:
print ('The answer is not correct.')
restart = input('The answer is wrong, type Y if you want to restart, and N if you want to exit. \n')
if (restart == 'y'):
main()
else:
exit()
main()
def logic_ques():
logicStr = input("Which animal sleeps on legs, not lying down?")
print ('You have entered the following animal:', logicStr)
if (logicStr == 'horse'):
pts += 1
print ('The asnwer is correct!')
print ('You currently have ', pts, 'points.')
continue1 = input('Press any ket to see the next question.\n')
else:
print ('The asnwer is not correct!')
restart1 = input('The answer is wrong, type Y if you want to restart, and N if you want to exit. \n')
if (restart1 == 'y'):
logic_ques()
else:
exit()
logic_ques()

Move the definition of logic_ques() before the definition of main()

Yes, the problem is the order. You are calling the logic_ques() function in main() before you define it. Simply move definition of logic_ques() above the point where you call main()

Related

Python 3 Y/N Loop Issue

I'm very new to Python, and I'm just having a play with making some very simple little programs to get a feel for it, so probably best to keep any explanations really simple haha!
I'm currently making a little program that asks if you want to roll a dice, rolls it, gives you the answer and asks if you want to roll again.
The issue I'm having trouble figuring out is the following (copied from console):
What is your name: Nasicus
Greetings Nasicus!
Would you like to roll the dice? [Y/N]? : Y
Let's do this!
Rolling...
You rolled a 3!
Do you want to roll again? [Y/N]?: Y
Yahoo!
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Process finished with exit code 0
As you can see, it prompts twice when you select N before it closes.
I'm probably missing something incredibly simple, so could anyone advise how I can either A. Stop it prompting twice or (preferably for the sake of simplicity) B. Stop it asking if You want to roll the dice after you have already selected Y to roll again, and just go straight from the Let's do this! line.
Here is my code, any pointers on how to keep things tidier/more pythonic always appreciated too! I appreciated the time.sleep() probably look a little messy, but I do like the way it paces things when I run it:
import random
import time
def diceroll():
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Thank you for your time, and I look forward to learning more :D
The problem is in this section of code:
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
You're recursively calling the diceroll() function, so when that recursive call finally finishes, the iteration of the current call still continues.
You're already in a while True loop, so you don't even need the recursive call. Just take it out, and let the loop continue.
You are calling diceroll recursively.
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
So you call diceroll() and then whenever the user is asked
Do you want to roll again
You call diceroll() again.
Here is what is happening. You have a top level diceroll().
diceroll()
Then you have another diceroll() under it like this:
diceroll()
-- diceroll()
And then you have yet another diceroll() inside it.
diceroll()
-- diceroll()
---- diceroll()
When you call the break statement, all you are doing is breaking out of that inner diceroll() loop, not the loop where you called it.
A break in the third row sends you to
diceroll()
-- diceroll()
I would just break out your actual rolling into a separate function in your diceroll() function, that way you won't confuse the paths.
import random
import time
def diceroll():
def rollIt():
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
rollIt()
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
rollIt()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Here is the Object Oriented approach:
import random
import time
class Rolling_Dice_Game () :
def startup (self) :
prompt = ("Would you like to roll the dice? [Y/N]? : ")
if self.query_user (prompt) == 'Y' :
self.run_the_game ()
return True
else : return False
def run_the_game (self) :
print ("Let's do this")
print ('Rolling...')
time.sleep (1)
rand = random.randint (1, 6)
print ('You rolled a ', rand, '!')
time.sleep (0.5)
return True
def query_user (self, prompt) :
return input (prompt) [0].upper ()
def continue_the_game (self) :
prompt = ("Do you want to roll again? [Y/N]?: ")
if self.query_user (prompt) != 'Y' :
print ('Oh, Okay. Maybe next time.')
return False
else : return True
my_dice = Rolling_Dice_Game ()
if my_dice.startup () == True :
while my_dice.continue_the_game () == True :
my_dice.run_the_game ()

Check whether a number lies between two other numbers

For some reason my code won't return False EVER and I cant figure it out?
I think the issue is with how my between function is written but it makes sense to me. Also I am struggling to get my restart function to work. If somebody could help me with those 2 areas I would be extremely grateful.
def between(a,b,c):
if a>b and b<c:
Rnum =True
else:
Rnum=False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if
the second number lies betweenthe first and the third")
print()
while True:
numone=input('Please enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
sprint()
number =between(numone,numtwo,numthree)
print('The statement ' + str(numone) + ' lies between ' + str(numtwo) + ' and ' + str(numthree) + ' is True.'"\n")
#Restart question
while True:
restart = input('Would you like to play again (Y/N)? ')
if restart == 'Y' or restart == 'y':
print('Restarting!' + ('\n' * 2))
break
if restart == 'N' or restart == 'n':
print('Thank you for playing.' + ('\n' *2))
break
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if restart == 'N' or restart == 'n':
break
else:
continue
if __name__ == '__main__' :
main() #excucte main function
The logic of your between function was slightly wrong (I've rename the variables to make it slightly clearer). In addition, you were not returning the value of the function so it was basically doing nothing. You were also always printing "True".
I have modified your code to return the result of the between function. I have made the result of this function a variable called true_or_false which is then printed at the end of each game.
In order to get your code to loop, all you need is another while loop which you can break out of if the user does not want to continue.
def between(low,test,high):
if low < test < high:
return True
else:
return False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if\nthe second number lies betweenthe first and the third")
while True:
while True:
numone=input('\nPlease enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
true_or_false =between(numone,numtwo,numthree)
print('The statement ' + str(numtwo) + ' lies between ' + str(numone) + ' and ' + str(numthree) + ' is ' + str(true_or_false) + "\n")
restart = ""
while restart.upper() != "Y":
restart = input('Would you like to play again (Y/N)? ')
if restart.upper() == "Y":
print('Restarting!')
elif restart.upper() == "N":
print ('Thank you for playing.')
sys.exit()
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if __name__ == '__main__' :
main() #excucte main function
You have small mistake, either in the problem definition or in the example code. Anyways if you modify it a bit:
def between(a,b,c): if b>a and b<c: return 'True'
else: return 'False'
print('The statement ' + str(numtwo) + ' lies between '
+ str(numone) + ' and ' + str(numthree) + ' is ' +
between(a,b,c) +"\n")

Nest IF needed? in Python

This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.
You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()

How do I get a function inside of a while loop in a function to work properly?

I have looked and looked for an answer, but I am new to python and the answers I find seem to be over my head or not quite what I need. I am trying to take my code and turn it into multiple functions to complete the simple task of receiving some grades from the user and displaying the input back to the user as they want it. Hopefully this will be more clear when you see my code.
import sys
gradeList = []
def validate_input():
try:
gradeList.append(int(grades))
except:
return False
else:
return True
def average(count, total):
ave = total / count
return ave
def exit(gradeList):
if gradeList == []:
print "You must enter at least one grade for this program to work. Good Bye."
sys.exit()
#def get_info():
while True:
grades = raw_input("Please input your grades.(or Enter once you have entered all of your grades): ")
if not grades:
break
elif validate_input() == True:
continue
else:
print "Please enter a number."
continue
def give_answers(gradeList):
while True:
print "\n",
print "Please select what you would like to do with your grades."
print "Press 1 for the Highest grade."
print "Press 2 for the Lowest grade."
print "Press 3 for the Average of the grades you entered."
print "\n",
print "Or you can press 'q' to quit."
choice = raw_input("> ")
if choice == 'q':
break
elif choice == '1':
print "\n",
print "The highest grade that you entered was %d.\n" % highest,
elif choice == '2':
print "\n",
print "The lowest grade that you entered was %d.\n" % lowest,
elif choice == '3':
print "\n",
print "Your average grade was %d.\n" % average,
else:
print "Please enter 1, 2, 3 or 'q'."
#get_info()
exit(gradeList)
gradeList.sort()
highest = gradeList[-1]
lowest = gradeList[0]
count = len(gradeList)
total = sum(gradeList)
average = average( count, total)
give_answers(gradeList)
Everything works correctly as I have pasted the code, but when I try to define get_info the nested validate_input() function stops working. It no longer populates the list so exit() catches and ends the program. The loop seems to just pass over the validate_input()function altogether because the else statement trips after each time through. My question is how do I get the validate_input() function to work properly while continuing to accept input until the user presses enter?
Pass grade to your function validate_input so it could add the grade to list like:
def validate_input(grades):

Why does the 'break' in this Python code end the program?

I am trying to make a simple guessing game, but the program exits when the user answers, 'yes', that they know how to play. I don't understand why the 'break' makes the program exit rather than continue to the rest of the code. Extreme newbie, in case you can't tell :P
Thanks for all the help!
import random
import time
def calculat(times):
p = "."
for nums in range(times):
print p
time.sleep(.2)
print p * 2
time.sleep(.2)
print p * 3
time.sleep(.2)
print p * 2
time.sleep(.2)
print p
time.sleep(.6)
print "Welcome to Guess!"
print "Press [Enter] to continue!"
raw_input()
while True:
know = raw_input("Do you know how to play? Enter [yes] or [no]\n")
know = know.upper()
if know == "YES":
break
elif know == "NO":
print " "
print "-INSTRUCTIONS-"
print "Here's how the game works. A number 1 to 100"
print "is generated randomly. Your goal is to guess"
print "as many numbers as possible before you run"
print "out of guesses. You have 10 guesses.Good luck!"
print "Have fun!"
else:
print "Please enter [yes] or [no]!"
while True:
score = 0
number = randint(1,100)
newnum = 1
for tries in range(0,9):
if newnum == 1:
print "Okay, I have a number 1 to 100! What is it?"
else:
print "Guess again! What's the number?"
while True:
try:
guess = input()
if guess <= 100 and guess >= 1:
break
else:
print "You must guess an integer, 1 - 100!"
except:
print "You must guess an integer, 1 - 100!"
if guess == number:
print "Heyo! That's correct!"
score = score + 1
number = randint (1,100)
newnum = 1
if tries != 9:
print "Press [Enter]! Guess another number!"
raw_input()
elif guess < number:
if tries != 9:
print "Darn, that guess was less than the number! Try again!"
print "Press [Enter] to continue!"
raw_input()
elif guess > number:
if tries != 9:
print "Whoa, that guess is too big! Try again!"
print "Press [Enter] to continue!"
raw_input()
print "That's it! Let me calculate your final score! [Press Enter]"
raw_input()
calculate(4)
print "Final Score: " + score
print "Good job!"
raw_input()
print "Would you like to play again? [yes] or [no]?"
play = raw_input()
play = play.upper()
if play == "NO":
print "Okay then, press enter to exit!"
raw_input()
break
elif play == "YES":
print "Yey! Let me think of a new number!"
calculate(2)
else:
print "You couldn't even say yes or no. Get out."
raw_input()
break
Oh yeah, the rest of the code could be broken, too. I haven't gotten past the instructions part.
It ends the program because it immediately encounters an error after the instructions are finished. You've imported random but then tried to use randint, unqualified. You've got to qualify it as random.randint or use from random import randint.
I assume you mean the break statement to escape from the first infinite loop. When I run your code, that break statement works just fine and control proceeds to the second infinite while loop.
However, your program then crashes on the first call to randint() because you aren't importing it correctly. Since the randint() function is from outside of your program (it's in the random module), you need to qualify the calls to randint() as random.randint() - so for the first call, you could use number = random.randint(1, 100). Alternatively, you could import randint using from random import randint, rather than import randint. That way, you would be able to call randint() directly.

Categories

Resources