How to separate for loop from if - python

ok = 1
while ok==1:
sum = 0
count = 0
a = int(input("Ievadiet, cik skaitļu būs virknē: "))
for i in range( 0, a):
N = int(input("Ievadiet veselu skaitli: "))
if N%2 == 1:
count+= 1
sum += N
if count != 0:
average = sum / count
print("Virknes nepāra skaitļu vidējā artimētiskā vērtība ir: ", average)
else:
print("Nevar aprēķināt nepāra skaitļu vidējo aritmētisko.")
ok = int(input(" Vai turpināt (1) vai beigt (0)?"))
This program should ask to type how many numbers will be in chain and then calculate the existing between these numbers the arithmetic mean of the odd numbers. How to separate "if count != 0" from "if N%2 == 1" so the programm will stop calculating arithmetic mean of every number but will calculated only when all numbers of the chain will be written.

Please check this code and see if that if what you want to reach. I just de-indented the last if...else block so no it first gets all the numbers and then shows the mean.
ok = 1
while ok == 1:
sum = 0
count = 0
a = int(input("Ievadiet, cik skaitļu būs virknē: "))
for i in range(0, a):
N = int(input("Ievadiet veselu skaitli: "))
if N % 2 == 1:
count += 1
sum += N
if count != 0:
average = sum / count
print("Virknes nepāra skaitļu vidējā artimētiskā vērtība ir: ", average)
else:
print("Nevar aprēķināt nepāra skaitļu vidējo aritmētisko.")
ok = int(input(" Vai turpināt (1) vai beigt (0)?"))
Have Fun :)

Related

How to debug my Python program, which sums positive numbers based on their evenness

I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and does the same thing as before, till the user type 0/negative number.
After that the software should print the number with the maximal sum. Sometimes it works and sometimes not.
Code:
def sum_Digits(n):
sum = 0
if n % 2 == 0: #For even numbers
while n>0:
if (n%10)%2 == 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
elif n % 2 != 0 : #For odd numbers
while n>0:
if (n%10)%2 != 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
def read_Numbers(N):
maX = 0
while N > 0: #while askNum Positive continue summing
suM = sum_Digits(N)
if suM > maX:
maX = N
N = int(input("Please eneter a Natural number: "))
if N <= 0:
return maX
def main():
num = int(input("Please enter a Natural number: ")) #asking the user to enter number
sum_Digits(num)
askNum = int(input("Please eneter a Natural number: "))
maxSum = read_Numbers(askNum)
print("Number with maximal sum: " , maxSum)
main()
Bug:
if user enter a negative number it will continue the loop and print the last entered number
because the program doesn't check for negative numbers
Fix:
I have added a condition if N <= 0:
return maX
this will return the last entered positive number
Bug:
sum_Digits(num)
I have removed this line because it is not needed
because we already call the function sum_Digits in the main function

Find dominant number(number that repeat at least n /2 times)

Homework:
Write a program that asks a user to type number n then the program asks the user to input n numbers.The program needs to find a dominant number in a list.The dominant number is one who is repeating at least n/2 times in the list.
My idea is to create a counter that at the start is 0.If a counter is = or > n//2 we add that number to the list.But this idea doesn't work as I thought.
Code:
numbers = []
n = int(input("Type number: "))
for i in range(n):
numbers.append(int(input("Type number: ")))
print(numbers)
counter = 0
dominant = []
for e in numbers:
for i in range(n):
if i == e:
counter += 1
if counter >= n // 2:
dominant.append(i)
print(dominant)
P.S. There is nothing said if there is no dominant number so we will skip that part.
Solution:
brojevi = []
n = int(input("Koliko brojeva zelite da unesete? "))
for i in range(n):
brojevi.append(int(input(f"Unesite {i+1}. broj: ")))
print(brojevi)
for e in brojevi:
brojac = 0
for j in brojevi:
if e == j:
brojac += 1
if brojac >= n//2:
print(e)
break

Getting the minimum value from user input in a while loop

I am writing a Python program that continuously asks a user for a number from 1 to 100, then once the user inputs the number 0, the program print out the smallest number and largest number provided, as well as the average of all the numbers.
My only problem: I keep getting 0 as the smallest value of the input when I want to exclude 0.
I have already tried doing the following:
count = 0
total = 0
number = 1
smallest = 0
largest = 0
while number != 0:
number = int(input("Please input a value from 1 to 100: "))
if number < 0 or number > 100:
print("Why you give me value outside of range :(\n")
count -= 1
continue
count += 1
total = total + number
if number > largest:
largest = number
if number == 0:
count -= 1
average = total / count
if number < smallest:
smallest = number
print("The results are: ")
print('Smallest: {}'.format(smallest))
print('Largest: {}'.format(largest))
print('Average: {}'.format(average))
print("\nThank you!")
You need to track both the largest and the smallest as the numbers are being input.
Also I have checked for the out of range numbers before any processing takes place:
count = 0
total = 0
number = 0
smallest = 101 # starts bigger than any input number
largest = 0 # starts smaller than any input number
while True:
number = int(input("Please input a value from 1 to 100: "))
if number == 0:
break
if number < 0 or number > 100:
print("Why you give me value outside of range :(\n")
continue
count += 1
total = total + number
if number > largest:
largest = number
if number < smallest:
smallest = number
if number == 0:
average = total / count
print("The results are: ")
print('Smallest: {}'.format(smallest))
print('Largest: {}'.format(largest))
print('Average: {}'.format(average))
print("\nThank you!")
Just add smallest = 101 in the beginning, and
if number < smallest:
smallest = number
to your while block, and remove the same code in the end.
Also, your count is off, you should just remove the two decrements count -= 1 to fix that.
You can also remove the if number == 0:, since you already have while number != 0: in the while condition, so you know it is zero.
Here is another version, this time using a list to hold the valid numbers:
numbers = []
while True:
number = int(input("Please input a value from 1 to 100: "))
if number == 0:
break
if number < 0 or number > 100:
print("Why you give me value outside of range :(\n")
continue
numbers.append(number)
if numbers:
average = sum(numbers) / len(numbers)
print("The results are: ")
print('Smallest: {}'.format(min(numbers)))
print('Largest: {}'.format(max(numbers)))
print('Average: {}'.format(average))
print("\nThank you!")

How to not count negative input

is there a way to keep the counter going without counting the negatives and only to stop when the input is zero?
count = 0
total = 0
n = input()
while n != '0':
count = count + 1
total = total + int(n) ** 2
n = input()
print(total)
Here is an example of execution result.
Input: -1 10 8 4 2 0
Output: 184
Since you want only number to enter the loop you can use isnumeric() built in function to check that.
You need if() : break here.
num = input()
...
while(isnumeric(num)):
...
if(num == "0"):
break;
The response you wait for is:
ignore negative number
count positive numbers
stop when input is 0
count = 0
total = 0
n = int(input())
while (n != 0):
count += 1
if (n > 0):
total = total + n**2
num = int(input())
print(total)
Your code was already OK except that you did not cast the number n into int and you did not test n to take away negative values.
Execution:
When you enter -1 10 8 4 2 0, it should show 184
You can parse your Input to an integer (number) and check if it's larger than zero:
count = 0
total = 0
num = int(input())
while number != 0:
if number < 0:
continue
count += 1
total = total + num**2
num = int(input())
print(total)
The difference between pass, continue, break and return are:
pass = ignore me an just go on, usefull when you create a function that has no purpose yet
continue = ignore everything else in the loop and start a new loop
break = break the loop
return = end of a function - a return statement can be used to give an output to a function but also as a way to break out of the function like the break statement does in loops.

How to generate a series using While loop

n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
sum = sum +1
i = i+1
print("The sum is" , sum)
I tried the above code but didn't got my answer.
The question is to generate a series that is: 1,4,7,10,13,16,19,22 using while loop.
To generate series you need to do two things:
Put the print inside the loop to output accumulator variable's value every iteration
Add 3 to sum every iteration and not 1 since it's the difference between series members
n = int(input("Enter n: ")) # n=8 should work
sum = 1
i = 1
while i <= n:
print(str(sum)+",")
sum = sum +3
i = i+1
I see two errors:
You should add i to sum,not 1 (this assumes you are interested in the sum as implied by the code)
You should be incrementing i by 3 not by 1
If I understand you correctly, you want this:
i = 1
while i <= 22:
print(i)
i += 3
n = int(input("Enter n: "))
count = 0
i = 1
sum = 0
while count <= n-1:
print(i)
sum += i
i += 3
count += 1
print("Sum is", sum)
You are going to want to increase the count by three every time with i += 3.
def createList():
user_input = input()
i = 1
list_of_vals = []
while i < int(user_input): # The max value:
list_of_vals.append(i)
i += 3
return list_of_vals
print (createList())
I think you want something like this:
n = int(input("Enter n: "))
series_sum = 0
i = 1
series = []
add = 3
while i <= n:
series.append(i)
series_sum = series_sum + i
i = i + add
print("series: ", series)
print("The sum is" , series_sum)
This would get you a series (and sum of elements) with the last element less than n, starting from i = 1 and increment add = 3

Categories