Find the Number of even intergers in a sequence - python

enter an arbitrary sequence of integers at the keyboard, and then prints the number of positive even integers user enters.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (x > 0):
for num in x:
if (int(x) % 2 == 0):
count += 1
entry = raw_input("Enter a value, or q to quit: ")
return count
I have gotten this so far but it is not working any ideas?

If you are counting them as they are entered there is no need to iterate.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (x > 0):
if (int(x) % 2 == 0):
count += 1
x = raw_input("Enter a value, or q to quit: ")
return count
on the other hand if you had a sequence of numbers getting the number of evens is O(n) and can be written one pythonic line.
numberOfEvens = sum([1 if k%2==0 else 0 for k in sequence])

The problem is You are getting wrong input, in the Loop, You are Using different variable for second Input. Just change the Variable name inside the Loop as x there You Go.
def find_even_count():
count = 0
x = raw_input("Enter a value, or q to quit: ")
while (x != "q") and (int(x) > 0):
if (int(x) % 2 == 0):
count += 1
x = raw_input("Enter a value, or q to quit: ")
return count

In your code, the line entry = raw_input("Enter a value, or q to quit: ") might be causing issues. if you noticed, in kpie's code, the line is inline with the if statement. in your code it will only be executed if x is even. if x is odd, your code will loop forever. additionally, entry is never used, so, again, x won't change.

Related

Verify if two indices from a list add up to a target number

I am looking to see if any 2 indices add up to the inputed target number, and print the combination and index location of the respective pair. I honestly am not too sure how to approach this, my first reaction was using a for loop but due to inexperience i couldn't quite figure it out.
def length():
global lst_length
break_loop = False
while break_loop == False:
lst_length = int(input("Enter the length: "))
if lst_length >= 10 or lst_length <= 2:
print("Invalid list")
elif lst_length >= 2 and lst_length <= 10:
print('This list contains', lst_length, 'entries')
break_loop == True
break
def entries():
i = 0
x = 0
global lst
lst = []
while i < lst_length:
number = float(input("Enter the entry at index {0}:".format(x)))
if i < 0:
print('Invalid entry')
else:
lst = []
lst.append(number)
i += 1
x += 1
def target():
target_num = int(input("Enter the target number: "))
length()
entries()
target()
If I understand your question correctly, you want the user to insert numbers, and when finally two numbers match the wanted result, print them?
well, my code is pretty basic, and it gets the job done, please let me know if you meant something else.
for indices, I suppose you can fill in the gaps.
def check(wanted):
numbers_saved = []
checking = True
while checking:
x = float(input("enter a number: "))
if x < 0:
print("only numbers bigger than 0")
else:
for num in numbers_saved:
if num + x == wanted:
print(num, x)
checking = False
return
numbers_saved.append(x)

Automate the Boring Stuff with Python The Collatz Sequence assignment repet

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)

Python expected an indented blockkkk

im relatively new to python and im not really sure how does the indentation for if else works.
Write a Python program that calculates the sum of all the numbers from x to y, where x and y are numbers entered by the user.
print("This program prints the sum of range from x to y. ")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers from 10 to 50. ")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
if type(x) == int and type(y) == int:
if x > 0 and y > 0:
if y > x:
sum_of_numbers = []
for counter in range(x , y):
sum_of_numbers.append(x)
x += 1
print("The sum of numbers from {} to {} is {}".format(x,y,sum(sum_of_numbers)))
else:
print("You did not enter a value of y greater than x")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not greater than zero")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not numeric!")
print("Unable to continue.Program terminated.")
exit()
if type(x) == int and type(y) == int:
if x > 0 and y > 0: # indented 1
if y > x: # indented 3
sum_of_numbers = [] # indented 4
You need to have consistent indentation, preferably four spaces for each indent, as per PEP8.
Without that, the Python compiler (or you as well, really) can't tell how your code is meant to be structured.

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 to keep repeating a program until a specific input?

I want to write a program to compute the average of a group of numbers entered (one at a time) by the user. Each group should end when the user enters the sentinel value '' (ENTER without input). Two consecutive sentinel values should quit the program. The number of each group should be displayed along side with their average:
This is my code :
x = eval(input('Enter a number: '))
lis = []
while x != '':
lis.append(x)
if x == '':
avg = sum(lis) / len(lis)
print(avg)
Just move the input into the loop:
x = None
lis = []
while x != '':
x = input('Enter a number: ')
if x != '':
lis.append(int(x))
avg = sum(lis) / len(lis)
print(avg)
Also you don't need the if statement as x must be equal to '' anyway so that the while loop terminates.

Categories

Resources