take input until the condition is completed in python - python-3.x

I want to take two input. The program must accept only valid scores (a score must fit in the range [0 to 10]). Each score must be validated separately. If the input is not valid, I want to print "Wrong input".
After taking two valid input, I want to print sum of the values.
count = 0
count2 = 0
while True:
a = float(input())
if 0 <= a <= 10:
count2 += a
count2 += 1
b = float(input())
if 0 <= b <= 10:
count2 += b
count += 1
else:
print('Wrong input')
if count == 2:
break
print('Sum = {}'.format(count2))
Sample input:
-3.5
3.5
11.0
10.0
Output:
Wrong input
Wrong input
sum = 13.5

By taking two while loops you can easily verify each input individually till you get the expected value.
while True:
a = float(input())
if 0<=a<=10:
break
else:
print('Wrong Input')
while True:
b = float(input())
if 0<=b<=10:
break
else:
print('Wrong Input')
print("sum =", a+b)

Related

Python 3 for beginners Control Flow, While Loops and Break Statements

I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.

Find average of given numbers in input

I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")

Iterating through a tuple list and somehow the 'a' is always treated as even number in the tuple (a,b)

I am able to get the code work good when the compound statement is changed to
if a % 2 == 0 and b % 2 == 0:
But as I am in learning phase could someone please guide me in explaining the error in the original code.
exm_list = [(4,8),(1,2),(4,5),(6,7),(10,20),(3,5),(3,2)]
for a,b in exm_list:
if a and b % 2 == 0:
print(f'{a,b} are the even numbers')
else:
print(f'one of {a,b} is the odd number')
enter image description here
The issue is that you are not asking anything for the condition for 'a'. What you should state is the following:
exm_list = [(4,8),(1,2),(4,5),(6,7),(10,20),(3,5),(3,2)]
for a,b in exm_list:
if a % 2 == 0 and b % 2 == 0:
print(f'{a,b} are the even numbers')
else:
print(f'one of {a,b} is the odd number')
Let me know.
In you case
if a and b % 2 == 0:
is equivalent to
if bool(a) and bool(b % 2 == 0):
a is an integer so bool(a) is True if a is not 0

A function to manipulate strings ad numbers

I need the solution for a function that prints numbers from 1 to 100. For multiples of three print “Foo”
instead of the number and for the multiples of five print “Bar”. For numbers which are multiples of both three and five print “FooBar”. For the remaining numbers just print this number.
i = 0
while I < 100:
i += 1
print(i)
if i == 3:
print("Foo")
You will have to use mod (%) to check the remainder of a division.
See if i % 3 is equal to 0. If this is true, then print FOO.
If i % 5 equal 0, print Bar; and so on.
I would recommend using an if else statement in your while loop after the index counter. Something like...
i = 0
while i <= 100:
i += 1
if i % 15 == 0:
print("foobar")
elif i % 3 == 0;
print("foo")
elif i % 5 == 0:
print("bar")
else:
print(i)
Using % returns the remainder and if that returns a remainder of 0 then you know that it is evenly divisible by that number.
i = 0
while i < 100:
i += 1
if i%15 == 0:
print('FooBar')
elif i%3 == 0:
print('Foo')
elif i%5 == 0:
print('Bar')
else:
print(i)
Apply if and else statement to decide which is the situation during the while loop.
Also, % could return the remainder. 3 and 5 both are prime numbers, so a number which % (3*5) == 0 indicates itself is a multiples of 3 and 5.

What is wrong with my function? Giving me a blank output

def get_nearest_multiple(minnum, factor):
"""
function get_nearest_multiple will calculate the nearest multiple that is greater than the min. value,
Parameters are the minimum value and factor,
Will return the ans - the nearest multiple
"""
ans = 0
x = 1
while ans < minnum:
if minnum == 0:
ans = 0
else:
ans = x * factor
x += 1
return ans
get_nearest_multiple(0, 1)
if __name__ == '__main__':
get_nearest_multiple(0, 1)
Can't seem to figure out why my function doesn't print out anything. The output doesn't even show up as an error. Just blank.
Nowhere in your code do you have a print() statement which is required to produce an output in the console

Resources