How to put a choice to try again to repeat the loop? - python

So after finishing the code, I would like to have an option where the user would like to try again by typing Y/n or N/n. How do I make it?
a=int(input('enter value of n: '))
i = 1
sum=0
while a < 1 or a > 300:
print(a, 'is not in the range 1-300')
exit()
for a in range(1,a+1):
print (a, end = ' ')
while i<=a:
if i%3==0 or i%5==0:
sum=sum+i
i=i+1
print('\nsum of all multiples of 3 and 5 is:',sum)
repeat=str(input('Would you like to try again? Y/N?'))

Here's a simple way to do it (keeping your code structure) without any functions or jargon (for beginners :]):
from sys import exit # Just something to exit your code
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
exit()
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Note that you don't need the exit() when checking if n is within 1 - 300, you could also just use break.
EDIT (WITH BREAK)
Program without from sys import exit below:
repeat = 'y' # So it starts the first time
while repeat.lower() == 'y': # repeat.lower() -> convert the string 'repeat' to lowercase, incase user inputs 'Y'. you could also use the or keyword here though
n = int(input("Enter value of n:\n>>> "))
if n < 1 or n > 300:
print("'n' must be between 1 - 300, not " + n) # You could use f-strings, check them out!
break # This will mean that "Thank you for running me!" gets printed even if your input is wrong
sum_of_multiples = 0
# I'm combining your for and while loop as shown below
for i in range(1, n + 1): # Don't name your 'i' and 'n' variables the same -> you did so with 'a'
print(i, end=', ') # There are cleaner ways to do this but I'm assuming this is what you want
if i % 3 == 0 or i % 5 == 0:
sum_of_multiples += i
# Printing output
print(f"\nSum of all multiples of 3 and 5 is: {sum_of_multiples}") # This is called an f-string
repeat = input("\nDo you want to go again?\n>>> ") # If you don't input Y/y, the outer while loop will break and terminate
print("Thank you for running me!") # Prints after the program finishes running
Hope this helped!

Related

Program must ask the user for an even integer max six times, if not it ends

The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.

How to exit while loop

I don't understand why I cannot go out from simple loop.
Here is the code:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
elif b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
Thanks for your help.
This should solve your problem:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
if b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
the following condition
if b == '0':
a = 0
should be in the same scope as the if b: condition.
You cant break out of the loop because. actually, there is nobreak. You need to putbreak` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.
Also, you could break out assigning a = 0 instead of the break.

Repeating a while loop after user input

I needed to create a program that sums the even numbers between 2 and 100. I have the part for this written:
def main():
num = 2
total = 0
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
main()
The next part is I'm supposed to add a while loop within the current while loop that asks for an input of Y/N and will repeat the program if the input is yes. I have spent a long time trying to put the following in different locations:
while again == "Y" or again == "y":
again = input("Would you like to run this again? (Y/N)")
But I haven't been able to get it to work or in best case I get it to print the total of the numbers and ask if I want to run it again but when I type yes it goes back to asking if I want to run it again.
Where do I put the other while statement?
If the while loop asking for running the program again does not have to be inside the loop computing the sum, then the following should answer your constraints:
def main():
again = 'y'
while again.lower() == 'y':
num = 2
total = 0
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
again = input("Do you want to run this program again[Y/n]?")
main()
Do note that if you answer N (no, or whatever else that is not Y or y) the program stops. It does not ask forever.
def sum_evens():
active = True
while active:
sum_of_evens = 0
for even in range(2, 101, 2):
sum_of_evens += even
print('Sum of the evens is:', sum_of_evens)
while True:
prompt = input('Type "Y" to start again or "N" to quit...\n')
if prompt.lower() == 'y': # doesn't matter if input is caps or not
break
elif prompt.lower() == 'n':
active = False
break
else:
print('You must input a valid option!')
continue
sum_evens()
It is always good to check if your summation has a closed form. This series being similar to the sum of positive integers, it has one so there is no reason to iterate over even numbers.
def sum_even(stop):
return (stop // 2) * (stop // 2 + 1)
print(sum_even(100)) # 2550
To put that in a while loop, ask for the user input after the function call and break if it is 'y'.
while True:
stop = int(input('Sum even up to... '))
print(sum_even(stop))
if input('Type Y/y to run again? ').lower() != 'y':
break
Output
Sum even up to... 100
2550
Type Y/y to run again? y
Sum even up to... 50
650
Type Y/y to run again? n
You should add the while loop at the beginning and ask the user at the end. Like this:
num = 2
total = 0
con_1 = True
while con_1:
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
ask = str(input("Do you want to run this program again(Y/n)?:"))
if ask == "Y" or ask == "y":
con_1 = True
elif ask == "N" or ask == "n":
con_1 = False
else:
print("Your input is out of bounds.")
break

How can I use a sys excepthook and then continue the code from a loop after the error message?

I am trying to create an average solver which can take a tuple and average the numbers. I want to use the except hook to give an error message and then continue from the beginning of the while loop. 'continue' does not work.
import sys
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z==1 :
def my_except_hook(exctype, value, traceback):
print('Please only use integers.')
continue
sys.excepthook = my_except_hook
print("Enter your set with commas between numbers.")
x=input()
i=len(x)
print('The number of numbers is:',i)
y=float(float(sum(x))/i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z=input()
print('Thank you for your time.')
As #PatrickHaugh noted, the keyword continue means nothing to my_except_hook. It is only relevant inside a while loop. I know this is what you are trying to do by having continue being called in the flow of a loop, but it's not really in the context of a loop, so it doesn't work.
Also, i is how many numbers you are, yet you set it as the length of the user input. However, this will include commas! If you want the real amount of numbers, set i = len (x.split (",")). This will find out how many numbers are in between the commas.
Never mind, I solved the problem. I just used a try-except clause...
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z == 1:
try:
print("Enter your set with commas between numbers.")
x = input()
i = len(x)
y = float(float(sum(x)) / i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z = input()
except:
print('Please use integers.')
x = []
continue
print('Thank you for your time.')

inconsistent string to int error and response

I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P

Categories

Resources