Beginner question regard basic loop and totaling positive inputs [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 days ago.
Improve this question
print("Welcome to the number program")
number=input("Please give me a number \n")
number=int(number)
total_number=0
entries=0
while number>0:
total_number=total_number+number
print(total_number)
number=input("Please give me another number! \n")
number=int(number)
entries= int(entries)+1
if number < 0 :
print("Sorry, this value needs to be positive. Please enter a
different number.")
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
I'm in a beginners programming class, and the book is not very helpful at times. I'm trying to write a basic program that takes positive numbers, totals them, and averages them out at the end. Also rejects negative numbers, and asks if -999 is entered I print the average of all entries, amount of entries, and the value tally. Any advice or tips I can learn from to improve it would be helpful. Thanks!
The program runs ok, it just doesn't write out some things I wanted

From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as:
print("Welcome to the number program")
total_number = 0
entries = 0
while True:
number = input("Please give me a number \n")
number = int(number)
if number == -999:
break
if number <= 0:
print("Sorry, this value needs to be positive. Please enter a different number.")
continue
total_number = total_number + number
entries += 1
print(total_number)
print(total_number)
print(entries)
print(total_number / entries)
Also, you can increment numbers with entries += 1

In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first
Accept your first number inside your while loop and handle all of the logic in there as well.
Your while loop should continue to loop until the final condition is met which seems to be number == -999
Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries.
Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied.
Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this.
total_number += number
# is exactly the same as
total_number = total_number + number
# but way nicer to read and write :)
print("Welcome to the number program")
number = 0
total_number = 0
entries = 0
while number != -999:
number = input("Please enter a number! \n")
number = int(number)
if number >= 0
total_number += number
entries += 1
print("Current sum: " + total_number)
elif number == -999:
break
else
print("Sorry, this value needs to be positive.")
print("Sum of entries: "+str(total_number))
print("Number of entries: " + str(entries))
print("Average entry: " +str(total_number/entries))

I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input.
Also some things I have written more elegant.
print("Welcome to the number program")
number=int(input("Please give me a number \n"))
total_number=0
entries=0
while number > 0:
total_number += number
print(total_number)
number = int(input("Please give me another number! \n"))
entries += 1
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
break
elif number < 0:
number = input("Sorry, this value needs to be positive. Please enter a different number!")

Related

Python input control loop

Python beginner here. Practicing user input control.
Trying to make user input loop to the beginning if anything but a whole number between 1 and 10 is used. Been trying for hours, tried using Try and Except commands but couldn't do it correctly. What am i doing wrong? Thank you.
Edit:
Thank you very much for your help everyone, however the problem is still not solved (but very close!) I'm trying to figure out how to loop back to the beginning if anything BUT a whole number is typed. Agent Biscuit (above) gave a great answer for floating numbers, but any word or letter that is typed still produces an error. I´m trying to understand how to loop when anything random (except whole numbers between 1 and 10) is typed. None of the above examples produced corrcct results. Thank you for your help
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
else number != (> 0 and < 10):
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
I have identified some problems.
First, the input statement you are using would just raise an error if a float value is entered, because the int at the start requires all elements of the input to be a number, and . is not a number.
Second; your else statement. else is just left as else:, and takes no arguments or parameters afterwards.
Now, how to check if the number is not whole? Try this:
while True:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
This accepts a float value, but only accepts it if it is equal to a whole number, hence the (round(number)==number).
Hope that answers your question.
First of all, you can't use a condition in a else statement. Also, you need to use or operator instead of and if one of the conditions is acceptable.
So, your code needs to be like this
while True:
print("Enter a number between 1 and 10")
number = int(input())
if (number > 0) and (number < 10):
print("Thank you, the end.")
break
elif number < 0 or number >10:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
Thanks to ack (above) for pointing me to a useful link. By studying another thread, I found the solution. It may not be perfect code, but it works 100%:
while True:
try:
print("Enter a number between 1 and 10")
number = float(input())
if (number > 0) and (number < 10) and (round(number)==number):
print("Thank you, the end.")
break
else:
print("\n")
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")
continue
except ValueError:
print("It has to be a whole number between 1 and 10.")
print("Please try again:")
print("\n")

Issue with the code in finding even or odd number using for loop [duplicate]

This question already has answers here:
Check if a number is odd or even in Python [duplicate]
(6 answers)
Closed 1 year ago.
number = int(input("Type your number to check even or odd :"))
for number in range (1,100):
if(number%2) == 0:
print("This is even number")
elif number > 100:
print("Enter the valid number from 1 to 100")
else:
print("This is ODD number")
i am a beginner in python language , I have written code to read the number as EVEN or ODD in for loop condition between (1,100). correct me if making any mistakes in my code .
Why are you using for loop, just check the condition like if number > 100;the number is invalid.Check this example
nos=int(input())
if(nos>100):
print("Enter the valid number from 1 to 100 ")
else:
if(nos % 2 ==0):
print("Number is Even")
else:
print("Number is Odd")
There are mistakes in your code.
1.Indentation error at the 2nd line.(Remove whitespace before for loop.)
2.The name of the input variable and the iterator name in for loop is same. So your intended logic would run on the numbers from 1 ,2, 3 ..... 99. It never runs on the user entered value. So change the name of any variable. Both cant be 'number'.
3.Although you change the name of the variable, you initialised for loop with 100 iterations so you see output 100 times.
so if you want to check the numbers between given range which are even or odd you can try this..
num = int(input(" Please Enter the Maximum Number : "))
for number in range(1, num+1):
if(number % 2 == 0):
print("{0} is Even".format(number))
print("{0} is Odd".format(number))

Running into issues with looping the calculation of # of digits in a number

My assignment requires me to take in an input, determine how many digits are in said input, then spit it back out. we are not allowed to use string conversion in order to determine the length of the input. I've managed to get that to work properly. My issue is that I'm supposed to have it repeat in a loop until a sentinel is reached. Here's my code so far.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = 1
final = 0
num = int(input("Enter a number: "))
while num != 0:
num = num //10
count += 1
print("There are", count, "digits in", num)
I'm also seeming to have trouble with having my input integer print properly, but it might just be my ignorance there. I've cut out what my attempts at looping it were, as they all seemed to just break the code even more. Any help is welcome, even criticism! Thank you in advance!
Firstly, that is a strange way to get the digits in the number. There's no need to modify the actual number. Just cast the int back to a string and get the length (don't just keep the original string, it could have spaces or something in it which would throw off the count). That is the number of digits.
Secondly, you can do all the work in the loop. There's no need for setup variables, incrementing, a second loop, or anything like that. The key insight is the loop should run forever until you break out of it, so you can just use "while True:" for the loop, and break if the user inputs "0".
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
def find_digits(num):
count = 0
while num != 0:
num = num //10
count += 1
return count
count += 1
# loop forever
while True:
# hang onto the original input
text_input = input("Enter a number: ")
# cast to int - this will throw an exception if the input isn't int-able
# you may want to catch that
num = int(text_input)
# the number of digits is the length of the int as a string
num_digits = find_digits(num)
if num == 0:
print("Goodbye.")
# "break" manually ends the loop
break
# if we got to this point, they didn't input 0 and the input was a number, so
# print our response
print(f"There are {num_digits} digits in {num}.")
The problem with printing the input integer correctly is, that you first save it in the num variable and then constantly change it in your while loop. So the original input is lost of course and in the end it always prints the 0, that ends up in num after the while loop finishes.
You can easily fix it, by saving the input value to another variable, that you don't touch in the loop.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = int(input("Enter a number: "))
numcopy = num
while numcopy != 0:
numcopy = numcopy // 10
count += 1
print("There are", count, "digits in", num)
Counting is better done with Python builtin functions.
len(str(num))
will give you number of digits in your number.

Add all numbers (in a while loop) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
so Im practicing coding in python. My question is this "So I make program that add all the number that enter by a user but the output of the program is not the sum of all the numbers that the user enter.
first sum_num need a initial value
sum_num = 0
and, change sum_num in loop every time is needed:
sum_num = sum_num + num
all code based at yours:
i = 0
sum_num = 0
while 1 == 1:
num = int(input('enter a number :'))
sum_num = sum_num + num
i = i + 1
if i > 5:
print('Total number is :' + str(sum_num))
break
if it's helpful , pls accept it.
You can do the same job by another code
if you have the count of the numbers that user will enter you can use this code :
#create a variable that store the total value
sum_num = 0
#for loop take a the number in range to repeat the code by it
for i in range(5):
#take the number from user and store it
num = int(input("Enter a number: "))
#add the number to total variable
sum_num += num
#at the end of the loop print the total
print("Total Number Is " + str(sum_num))
If you don't have the count of number that user will enter Use This Way :
#create a variable that store the total value
sum_num = 0
#create flag that tell me if user won't enter any other numbers or he want to
#enter more numbers
flag = True
#while loop take a flag and will be in the loop while flag is true
while(flag):
#take the number from user and store it
num = int(input("Enter a number: "))
#add the number to total variable
sum_num += num
#ask user if he want to continue
ask = input("Do you want to continue : ")
if(ask.lower() == 'no' or ask.lower() == 'n') :
flag = False
#at the end of the loop print the total
print("Total Number Is " + str(sum_num))

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Categories