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!
Related
I'm writing this script for an assignment so I'd appriciate being talked through it rather than simply being handed an answer. Basically I'm trying to convert feet to meters, meters to feet, and provide a sum of the total converted distance in both at the end. Without the [] indexes, It was working perfectly. The new part I've only just added and am struggling with is the [] indexes, and to be honest I'm having a hell of a time groking how they work. Anyways heres the code:
MAX = 256
switch = ""
feet = [0.0] * MAX
meters = [0.0] * MAX
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
def main():
selector()
def selector():
while True:
print("Is your measurement in meters or feet?")
switch = input("Or would you like to quit?")
if (switch == "feet" or switch == "Feet"):
ftm()
elif (switch == "meters" or switch == "Meters"):
mtf()
elif (switch == "quit" or switch == "Quit"):
end()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
def mtf():
try:
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
feet[sum_feet] = float(input("Enter the number of feet. "))
meters[sum_meters] = feet * metersperfoot
print("That is", meters, "meters.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
ftm()
def end():
while True:
switch2 = input("Are you sure you want to quit(y/n)?")
if (switch2 == "y" or switch2 == "Y"):
print("you converted a total of ", sum(feet), "feet")
print("And", sum(meters), "meters.")
print("Bye!")
exit()
elif (switch2 == "n" or switch2 == "N"):
print("Ok, let's try that again.")
main()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
main()
I did try having sum_feet + 1 and sum_meters + 1 after each result but that hadnt worked either.
You are not using the indexing in a proper way. For instance , look at the comments on your existing code:
def mtf():
try:
# Error 1. You stored all the inputs to index 0, as sum_meters is 0 always and its not incremented
# So, all the inputs are not recorded, only last one gets in index 0
meters[sum_meters] = float(input("Enter the number of meters. "))
# Error 2: You multiplied the whole list against the conversion parameter.
# Instead, you should multiply the value at current index
feet[sum_feet] = meters * feetpermeter
# This will print the whole list. Again use the current index here
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
A fixed version of your function will be like:
def mtf():
try:
# For modifying global variables in a function scope
global sum_meters
global sum_feet
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters[sum_meters] * feetpermeter
print(f"That is {feet[sum_feet]} feet.")
sum_meters += 1
sum_feet += 1
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
This fixes stands true for your other functions as well.
I also thought to give you another piece of advice, that you can use a good object oriented approach for such problems, which makes it simpler to implement. You can learn a lot about that, then you will feel more confident.
As an example, see the below code - which does almost same, but in a more crisp way.
class Converter:
FEET_PER_METER = 3.28084
METERS_PER_FOOT = 0.3048
def __init__(self):
self.feet_store = []
self.meter_store = []
self.curr_index = 0
self.menu_handlers = {
"feet": self.feet_to_meter,
"meters": self.meter_to_feet,
"quit": self.summary
}
def run_selection(self, selected):
#
selected = str.lower(selected)
if selected in self.menu_handlers:
# call the relevant function
return self.menu_handlers.get(selected)()
return False
def meter_to_feet(self):
meters_in = float(input("Enter the number of meters."))
to_feet = meters_in * self.FEET_PER_METER
self.meter_store.append(meters_in)
self.feet_store.append(to_feet)
print(f"In Feet : {to_feet}")
return to_feet
def feet_to_meter(self):
feet_in = float(input("Enter the number of feet."))
to_meters = feet_in * self.METERS_PER_FOOT
self.feet_store.append(feet_in)
self.meter_store.append(to_meters)
print(f"In Meters : {to_meters}")
return to_meters
def summary(self):
confirm = input("Are you sure you want to quit(y/n)?")
if confirm in ["y", "Y"]:
print("you converted a total of ", sum(self.feet_store), "feet")
print("And", sum(self.meter_store), "meters.")
print("Bye!")
exit()
else:
return False
def main():
converter = Converter()
while True:
choice = input("Is your measurement in meters or feet (meters/feet/quit)?")
converter.run_selection(choice)
I hope this gives you better insights.
So theres two problems with what you've tried to do here, in the lines:
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter
meters * feetpermeter is multiplying an array by a number, you need to do meters[sum_meters] to get the number you want. Secondly as you said, you need to increment sum_meters each time, but because you're inside a function you will need to declare the variable as a global before you change it. Also since sum_meters and sum_feet are always going to be equal, you can just use a single variable to keep track of this:
def mtf():
try:
global index
meters[index] = float(input("Enter the number of meters. "))
feet[index] = meters[index] * feetpermeter
index += 1
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
global index
feet[index] = float(input("Enter the number of feet. "))
meters[index] = feet * metersperfoot
index += 1
print("That is", meters, "meters.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
ftm()
I would also go a little further and say that the use of lists is unnecessary for this problem, you could simply have two numbers, total_meters and total_feet and add the values as you go. This would take less memory and also remove the arbitrary limit of 256 goes that has been imposed. So I would do:
import sys
MAX = 256
switch = ""
total_feet = 0
total_meters = 0
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
index = 0
def main():
selector()
def selector():
while True:
print("Is your measurement in meters or feet?")
switch = input("Or would you like to quit?")
if switch == "feet" or switch == "Feet":
ftm()
elif switch == "meters" or switch == "Meters":
mtf()
elif switch == "quit" or switch == "Quit":
end()
sys.exit(0)
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
def mtf():
try:
global total_feet
global total_meters
meters = float(input("Enter the number of meters. "))
feet = meters * feetpermeter
total_meters += meters
total_feet += feet
print("That is", feet, "feet.")
main()
except Exception as e:
print(e)
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
global total_feet
global total_meters
feet = float(input("Enter the number of feet. "))
meters = feet * metersperfoot
total_meters += meters
total_feet += feet
print("That is", meters, "meters.")
main()
except Exception as e:
print(e)
print("Sorry, I didn't quite get that, lets try again.")
ftm()
def end():
while True:
switch2 = input("Are you sure you want to quit(y/n)?")
if switch2 == "y" or switch2 == "Y":
print("you converted a total of ", total_feet, "feet")
print("And", total_meters, "meters.")
print("Bye!")
exit()
elif switch2 == "n" or switch2 == "N":
print("Ok, let's try that again.")
main()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
main()
history = []
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
def main():
def summation():
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
first_num = str(input(":ype the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
print("The Previous result is: " + str(history()))
def exits():
print("Exiting...")
while True:
x = str(input("Type your option: "))
if x == "1" or x == "2" or x == "3" or x == "4":
break
if x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
else:
exits()
main()
The indentation of your while is wrong. It should be inside of your main function.
Try removing the main function and just let your script run the while loop.
Also break only during the input that you want to exit the loop. If nothing is after the loop, it exits the script; with your current logic, the while loop exits for every option, nothing is printed beyond your first line and your input prompt, then the main function gets ran, but nothing runs because the main function is actually empty (only defines other functions)
history = []
def summation():
global history
first_num = int(input("Type the first integer: "))
second_num = int(input("Type the second integer: "))
total_0 = first_num + second_num
print("Sum of two integers is: ",total_0)
history.append(total_0)
def string():
global history
first_num = str(input("Type the first string: "))
second_num = str(input("Type the second string: "))
total_1 = first_num + second_num
history.append(total_1)
print("Concatenation of two strings is: ",total_1)
def last():
global history
print("The Previous result is: " + str(history))
def exits():
print("Exiting...")
while True:
print("Options: 1) Integer Summation, 2) String concatenation, 3) Last Display, 4)Exit...")
x = str(input("Type your option: "))
if x == "4":
exits()
break
elif x == "1":
summation()
elif x == "2":
string()
elif x == "3":
last()
Note: input() always returns a str type, so there's no reason to cast it
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"
I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")
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.