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
Related
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.
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!
When I run my code the output is correct, it's just printing out two of each value.
Can somebody enlighten me on what is going wrong?
number = int(input("Enter any number: "))
tfcheck = True
def reducer(number):
if (number % 2) == 0:
number = int(number/2)
else:
number = number * 3 + 1
print(number)
return number
while tfcheck:
if reducer(number) == 1:
tfcheck = False
break
else:
number = reducer(number)
reducer(number)
This code should divide a user inputted number down to 1 and display each step, this is a sample output of what I'm getting if I put in 3:
10
10
5
5
16
16
8
8
4
4
2
2
1
1
Cant see where I'm going wrong with it
reducer prints the number. In your while loop, you call reducer twice:
while tfcheck:
if reducer(number) == 1: # Call once
tfcheck = False
break
else:
number = reducer(number) # Call again
Thus, the number will get printed twice. To fix this, you can just call reducer once and store its result in a temporary variable.
while tfcheck:
reduced = reducer(number) # Call once
if reduced == 1:
tfcheck = False
# break # No need to break since you set tfcheck = False
else:
number = reduced # Do not call again
Iterative Approach:
Solution provided in the question prints the number inside the function and since in the while loop reducer is called twice with same value as it executes else statement unless the return value is 1.
Therefore solution to this problem would be simply printing the number in else statement of while loop.
number = int(input("Enter any number: "))
tfcheck = True
def reducer(number):
if (number % 2) == 0:
number = int(number/2)
else:
number = number * 3 + 1
return number
while tfcheck:
if reducer(number) == 1:
tfcheck = False
break
else:
number = reducer(number)
print(number)
print(reducer(number))
Recursive Approach:
A better approach would be using this method as it eliminates repetitive function call, while loop along with if-else statements can be eliminated. Also you will be able to understand the code better.
Yes it is true Python has recursion limit, if the use case is exceeding the limit then go for Iterative method. But for most cases the limit will not be crossed.
def reducer(number):
if number==1:
return 1
if (number % 2) == 0:
number = int(number/2)
else:
number = number * 3 + 1
print(number)
reducer(number)
reducer(int(input("Enter any number: ")))
I know there are a lot of posts on this assignment and they all have great information, however, I am trying to take my assignment to the next level. I have written the code for the sequence, I have written the try and except functions and have added the continues so the program will keep asking for a positive integer till it gets a number. now I would like the whole program to repeat indefinitely, and I will then write a (Q)uit option. I tried making the question ask into a global scope but that was wrong, can someone please give me a hint and I will keep working on it. here is my code;
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
return result
while True:
try:
n = int(input("Give me a positive number: "))
if n <= 0:
continue
break
except ValueError:
continue
while n != 1:
n = collatz(int(n))
An example of repeating indefinitely is as follows.
def collatz(number):
" No element of Collatz can be simplified to this one liner "
return 3 * number + 1 if number % 2 else number // 2
while True:
# Will loop indefinitely until q is entered
try:
n = input("Give me a positive number: ")
# String returned from input
if n.lower() == "q": # check for quit (i.e. q)
break
else:
n = int(n) # assume int, so convert (will jump to exception if not)
while n > 1: # loops and prints through collatz sequence
n = collatz(n)
print(n)
except ValueError:
continue
Pretty much all you need to do is move the second while loop into the first and add a "quit" option, though I've done some additional things here to simplify your code and give more feedback to the user.
def collatz(number):
if number % 2 == 0:
# Removed "print" here - should be done in the calling scope
return number // 2
else: # Removed "elif" - You already know "number" is not divisible by two
return 3 * number + 1
while True:
s = input("Give me a positive number, or 'q' to quit: ")
if s == 'q':
print('Quit')
break
try:
# Put as little code as possible in a "try" block
n = int(s)
except ValueError:
print("Invalid number, try again")
continue
if n <= 0:
print("Number must be greater than 0")
continue
print(n)
while n != 1:
n = collatz(n)
print(n)
Example run:
Give me a positive number, or 'q' to quit: a
Invalid number, try again
Give me a positive number, or 'q' to quit: 0
Number must be greater than 0
Give me a positive number, or 'q' to quit: 2
2
1
Give me a positive number, or 'q' to quit: 3
3
10
5
16
8
4
2
1
Give me a positive number, or 'q' to quit: q
Quit
Thank you the suggestions are great!! Here is my finished code;
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
else:
number = 3 * number + 1
print(number)
while True:
try:
n = input("Give me a positive number or (q)uit: ")
if n == "q":
print('Quit')
break
n = int(n)
except ValueError:
continue
collatz (n)
I saw a similar post, but it included functions, which mine does not.
Objective: Write a program that reads an unspecific number of integers, determines how many positive and negative values have read, and computes the total and average of the input values (not counting 0's) while the program will halt at 0.
ISSUE I AM HAVING: When using the following test values
1,
2,
-1,
3
I get the following:
The number of positives: 1
The number of negatives: 2
The total amount of numbers used: 3
The average is 1.33 which is 4 / 3
It should be:
The number of positives: 1
The number of negatives: 3
The total amount of numbers used: 4
The average is 1.25 which is 5 / 4
My Attempt below:
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
else:
while user_input != 0:
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input != 0 and user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
user_input != 0 and user_input < 0
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
What is causing such error? I can only assume that this is a minor fix?
I've fixed the problems in your code and refactored to trap error conditions and removed unnecessary complications:
positive_number = 0
negative_number = 0
average = 0
count = 0
total = 0
user_input = None
while user_input != 0:
try:
user_input = int(input("Enter enter as many intergers as you want, 0 will halt: "))
except ValueError:
user_input=0
if user_input > 0:
total += user_input
positive_number += 1
count += 1
elif user_input<0:
total += user_input
negative_number += 1
count += 1
if count==0:
print("You didn't enter any number, code ended")
else:
average = total / count
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(total), "/", str(count))
First, the first if statement is redundant as you test for user_input != 0 as the loop condition. Second, the reason it was going wrong was because on your first input you immediately overwrote the value of user_input, so I put the reprompt code at the end of the loop. Finally, I cleaned up the if elif else statement as this does the exact same with fewer characters. The print statement for the closing line is also executed once we pull out of the loop - sinc eby definition that means user_input == 0
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
while user_input != 0:
if user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
print("You didn't enter any number, code ended")
Like it was said in the comments, your first input is getting ignored. Here is an alternative that should work. I excluded a few redundant check statements.
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = 1
while user_input != 0:
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
There are a number of issues with your code. First of all, the first number that the user prompts is not being evaluated by the code; it's being overwritten once you get to the while loop. There are multiple ways to fix this, but the best would be along the lines:
cont = True
while cont is True:
user_input = int(input("Prompt user"))
if user_input == 0:
cont = False
You could do a break statement too, it doesn't matter.
So that takes care of why the first number isn't being read, and why the code thinks there were only 3 inputs (as well as your count being off). Now what about the two negatives? I don't know why you got that. When I inputted the numbers you listed, I got one negative and two positives. Try it again and see if it works now, I suspect you must've mistyped.