How do i not print it twice - python

I'm new to python and experimenting with functions. Here's the sample code that I'm working wtih
def menu():
print(" 1. Divide")
def test1(x,y):
if y == 0:
return "The result is undefined"
else:
return x/y
num1=int(input("First: "))
num2=int(input("Second: "))
menu()
answer=int(input("Choose: "))
while answer != 0:
if answer == 1:
print()
print(" The result is", test1(num1,num2))
print()
menu()
answer=int(input("Choose: "))
When I run the program and input a y value of 0, the result prints twice. How do I make it print once only then return to menu? Thank you

This is not a bug in your code,
you can simply Change your zero condition to this:
if y == 0:
return "undefined"

Related

Can't break a Palindrome loop in Python

I'm just a beginner using Python and have created code to print all the palindrome numbers in a range from 1-1000. However, after my print statement the code just keeps looping and printing the numbers over and over from 1-99. I've tried using break; after the print(i) statement, but it then causes the console to print 1 and *Palindromes in a loop instead of the palindrome numbers. Any suggestions to break out of the loop?`
pi = 3.14159
area = 0
def areaSquare(squareWidth):
return squareWidth * squareWidth
def areaCircle(radius):
return pi *(radius * radius)
def menu(): #Creat the menu for user to see
print("\nCalculations")
print("1. Calculate area of a square\n2. Calculate the area of a circle\n3. Display palindromes up to 1,000\n4. Exit programme.")
menu() # call the menu
option = int(input("Enter an option: "))
while option != 4: #create a loop
if option == 1:
print("***Area of a square***")
squareWidth = float(input("Enter width of square(cm): "))
print("The area of the square of width ",squareWidth, "cm = ", areaSquare(squareWidth), "cm squared")
menu()
option = int(input("Enter an option: "))
elif option == 2:
print("***Area of a circle***");
radius = float(input("Enter radius of circle(cm): "))
print("The area of a circle of " , radius , "cm = ", areaCircle(radius), " round")
menu()
option = int(input("Enter an option: "))
elif option == 3:
for i in range(1, 1000):
if str(i) == str(i)[::-1]:
print(i,)
else:
print("Invlid entry, please select a number between 1 and 4.")
menu()
option = int(input("Enter an option: "))
print("Goodbye!")
Python 3
print("**Palindromes***");
for i in range(1, 1000):
if str(i) == str(i)[::-1]:
print(i,)
Try it online!
This should do the trick. I think you have an outer loop that is causing the indent in your code, which is why your loop is not breaking.
Thanks everyone. I changed the while loop to an if statement, and was able to get the loop to break!

Completing a Startup Menu in Function - Python

I'm trying to finish writing this function that contains five different options and uses a While loop to allow the user to enter in their choice with the entry '5' exiting the loop. Below is the code I have so far, I'm having trouble completing the menu part within the def_main function. I keep getting an error after else:
break
Any input would be appreciated. Thank you for reading.
def main():
menuOption = 0
while 1 == 1:
print("1. Expanded Sum\n2. Reverse Expanded Sum\n3. Reverse Integer\n4. Product Table\n5. Exit\n")
menuOption = int(input("Enter correct menu option: "))
while menuOption<1 or menuOption>5:
print("Incorrect menu option!!")
menuOption = int(input("Enter correct menu option: "))
if menuOption == 5:
return
while 1 == 1:
num = int(input("Enter positive Integer: "))
if num <= 0:
print("You have entered negative integer or zero.")
continue
else:
break
if menuOption == 1:
printSum(num, int(False))
elif menuOption == 2:
printSum(num, int(True))
elif menuOption == 3:
print(str(reverseInt(num)))
elif menuOption == 4:
printProductTable(num)
if __name__ == "__main__": main()
def printSum(n, reverse):
s = sum(range(n+1))
if reverse:
print('+'.join(str(i) for i in range(1, n+1)) + ' = ' + str(s))
else:
print('+'.join(str(i) for i in range(n, 0, -1)) + ' = ' + str(s))
def reverse_int(n):
Reverse = 0
while(n > 0):
Reminder = n %10
Reverse = (Reverse *10) + Reminder
n = n //10
print(Reverse)
def printProductTable(n):
for row in range(1,n+1):
print(*("{:3}".format(row*col) for col in range(1, n+1)))
What is the error you are getting at the break?
It looks like your spacing might be off in the continue, I assume your else goes to the if at the top of the statement, but your continue does not match with it.
Rather than doing while 1==1 you can write while True. And also you have already checked while menuOption<1 or menuOption>5. So if your menuOption is a negative number it already falls into this condition as, say, -2 < 1.
And also seems like your code is not formatted. Means, continue is just above the else. It will generate the error. Re-formate your code. Give proper indentation.

basic python 3 module issue

Okay, so I'm trying to write a module for class to load up a basic prime number checker. We have samples to look from, and I'm going to copy what I have so far... But I'm pretty lost on how to write this, and then for the program to actually call the module (should be import xxxx.py right?)
Don't be too harsh, I'm not the only one in my class struggling with this. Youtube and my search results on here haven't really helped. Thanks in advance for yet, another basic question.
#!/usr/bin/env python3
#Program Name
print("Prime Number Checker")
def factor_count(num):
factor_count = 0
print("The factors are: ")
def main():
choice = "y"
while choice.lower() == "y":
#user input
num = int(input("Please enter a number: "))
if num <= 1:
print("please choose a value greater than 1. ")
print()
else:
for i in range(1, num+1):
if num%i == 0:
print(i)
if factor_count == 2:
print(num, "is prime")
else:
print(num, "is not prime!")
if __name__ == "__main__" :
main()
print()
print("goodbye")
Couple of points, here is how I would write the program :
Don't use the same name for variables and function names factor_count. So when you write if factor_count == 2 it is always false.
You aren't updating the value of variable choice after every run
the way of finding primes is also very inefficient.
def main():
choice = "y"
while choice.lower() == "y":
factor_count = 0
# user input
num = int(input("Please enter a number: "))
if num <= 1:
print("please choose a value greater than 1. ")
print()
else:
for i in range(2, num):
if num % i == 0:
print(i)
factor_count += 1
if factor_count == 0:
print(num, "is prime")
else:
print(num, "is not prime!")
choice = input('Do you want to continue?(y/n) : ')
if __name__ == "__main__":
print("Prime Number Checker")
main()
print()
print("goodbye")

Why does While loop return one variable but not another?

am trying to teach myself Python and am building myself a basic hangman game. I've got a little way but now I'm stuck.
I've tried to put the bulk of the 'counter' for guessing in one function and then reference another function to actually work out whether the guess is correct or not.
So here is my counter function:
def game(generated_word):
hangman_lst = []
guess_num = 0
for i in range(0, len(generated_word)):
hangman_lst.append("__")
print(" ".join(hangman_lst))
while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
guess(l, random_word_stripped, hangman_lst, guess_num)
if "__" not in hangman_lst:
print("**Ta-da!** You're a winner!")
and here is my function to work out whether the guess is correct or not:
def guess(ltr, word, lst, try_num):
upper_ltr = ltr.upper()
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
elif len(upper_ltr) < 1:
print("You didn't enter a letter, try again:")
print(" ".join(lst))
elif upper_ltr in lst:
print("You already guessed that letter, try again:")
print(" ".join(lst))
elif upper_ltr not in word:
print("Sorry, that's incorrect. Try again.")
print(" ".join(lst))
try_num += 1
return try_num
else:
for n in range(0, len(word)):
if word[n] == upper_ltr:
lst[n] = upper_ltr
print("Nice job. That's one. You get a bonus guess.")
print(" ".join(lst))
return lst
So it kind of works, in that the hangman word is updated with the letters as they are guessed. But I can't get the counter to work - guess_num seems to always stay on 0 and so it always loops through this part:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
But, it seems as if lst is returned ok from the guess function, so why isn't try_num?
Cheers!
You need to increment guess_num. Adding guess_num = guess_num + 1 at the end of the while loop would fix this, but you only want guess_num incremented on a bad guess, so you would do something like this. (I haven't tested this)
while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
if guess(l, random_word_stripped, hangman_lst, guess_num):
print("good guess")
else:
guess_num += 1
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
if guess(l, random_word_stripped, hangman_lst, guess_num):
print("good guess")
else:
guess_num += 1
And then in your guess function you need to add the line return True or return False to return the appropriate True/False value depending on if there guess was valid.
So the part of the guess function that goes
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
Will need to be changed to
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
return False
And then you will do this for each of the if conditions. As soon as python sees a return statement it will exit the function and will return whatever you tell it to return which in our case will be either True or False.
When you use the return keyword, that indicates that you're trying to a give a computed value back to the function's caller. Since with return you are giving the caller back a value, you would expect to assign that value to something once the function is completed...something you aren't doing.
In case you don't understand, here is an example...
Say I have my main function calling a function called add(), and say I want this function to compute the value of two integers being passed in. Then, I would have to return the computed value back to the caller for further use.
def main():
a = 5
b = 20
sum = add(a, b)
print(sum)
def add(num1, num2):
return num1 + num2
THEN, this code would print the value of a + b, or in this case, 25.

Python menu-driven programming

For menu-driven programming, how is the best way to write the Quit function, so that the Quit terminates the program only in one response.
Here is my code, please edit if possible:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
while choice!="q":
if choice=="v":
highScore()
main()
elif choice=="s":
setLimit()
main()
elif choice=="p":
game()
main()
else:
print("Invalid choice, please choose again")
print("\n")
print("Thank you for playing,",name,end="")
print(".")
When the program first execute and press "q", it quits. But after pressing another function, going back to main and press q, it repeats the main function.
Thanks for your help.
Put the menu and parsing in a loop. When the user wants to quit, use break to break out of the loop.
source
name = 'Studboy'
while True:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choice = raw_input(">>> ").lower().rstrip()
if choice=="q":
break
elif choice=="v":
highScore()
elif choice=="s":
setLimit()
elif choice=="p":
game()
else:
print("Invalid choice, please choose again\n")
print("Thank you for playing,",name)
print(".")
def Menu:
while True:
print("1. Create Record\n2. View Record\n3. Update Record\n4. Delete Record\n5. Search Record\n6. Exit")
MenuChoice=int(input("Enter your choice: "))
Menu=[CreateRecord,ViewRecord,UpdateRecord,DeleteRecord,SearchRecord,Exit]
Menu[MenuChoice-1]()
You're only getting input from the user once, before entering the loop. So if the first time they enter q, then it will quit. However, if they don't, it will keep following the case for whatever was entered, since it's not equal to q, and therefore won't break out of the loop.
You could factor out this code into a function:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
And then call it both before entering the loop and then as the last thing the loop does before looping back around.
Edit in response to comment from OP:
The following code below, which implements the factoring out I had mentioned, works as I would expect in terms of quitting when q is typed.
It's been tweaked a bit from your version to work in Python 2.7 (raw_input vs. input), and also the name and end references were removed from the print so it would compile (I'm assuming those were defined elsewhere in your code). I also defined dummy versions of functions like game so that it would compile and reflect the calling behavior, which is what is being examined here.
def getChoice():
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=raw_input(">>> ")
choice=choose.lower()
return choice
def game():
print "game"
def highScore():
print "highScore"
def main():
print "main"
def setLimit():
print "setLimit"
choice = getChoice()
while choice!="q":
if choice=="v":
highScore()
main()
elif choice=="s":
setLimit()
main()
elif choice=="p":
game()
main()
else:
print("Invalid choice, please choose again")
print("\n")
choice = getChoice()
print("Thank you for playing,")
This is a menu driven program for matrix addition and subtraction
def getchoice():
print('\n What do you want to perform:\n 1.Addition\n 2. Subtraction')
print('Choose between option 1,2 and 3')
cho = int(input('Enter your choice : '))
return cho
m = int(input('Enter the Number of row : '))
n = int(input('Enter the number of column : '))
matrix1 = []
matrix2 = []
print('Enter Value for 1st Matrix : ')
for i in range(m):
a = []
for j in range(n):
a.append(int(input()))
matrix1.append(a)
print('Enter Value for 2nd Matrix : ')
for i in range(m):
a = []
for j in range(n):
a.append(int(input()))
matrix2.append(a)
choice = getchoice()
while choice != 3:
matrix3 = []
if choice == 1:
for i in range(m):
a = []
for j in range(n):
a.append(matrix1[i][j] + matrix2[i][j])
matrix3.append(a)
for r in matrix3:
print(*r)
elif choice == 2:
for i in range(m):
a = []
for j in range(n):
a.append(matrix1[i][j] - matrix2[i][j])
matrix3.append(a)
for r in matrix3:
print(*r)
else:
print('Invalid Coice.Please Choose again.')
choice = getchoice()

Categories