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 1 year ago.
Improve this question
number = int(input(" guess the number: "))
for number in range(0,20):
if number < 13:
print("number is smaller")
elif number > 13:
print("number is greater")
else:
print("Correct guess!!")
Why does not the code give me correct output as expected
I think you have used the variable 'number' to take input and you are using it to iterate in the for loop too. That is why it is causing error, use some other variable in the for loop.
Hope this is helpful.
Don't use the for loop, instead use a while loop.
number = int()
def check_num():
try:
number = int(input('Enter the number: '))
while number != 13:
if number < 13:
print("number is smaller")
elif number > 13:
print("number is greater")
else:
print("Correct guess!!")
number = int(input('Enter the number: '))
except ValueError:
print('Only type numbers!')
check_num()
check_num()
Output:-
Enter the number: avengers
Only type numbers!
Enter the number: 2
number is smaller
Enter the number: 23
number is greater
Enter the number: 13
First of all, you are not supposed to be using a for loop for what you want because it just changes the input number. Here is the easy fix with random numbers:
import random
start_of_range = 0 # Number will be random number between these
end_of_range = 100
number_to_guess = random.randint(start_of_range, end_of_range)
while True:
try:
number = int(input("Guess the number: "))
except:
print("Enter a valid number")
continue
if number == number_to_guess:
print("Correct Guess")
break
elif number < number_to_guess:
print("Number is less")
else:
print("Number is more")
Related
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!")
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 2 years ago.
Improve this question
Question is: Use procedure with parameter. Ask the user to input numbers until they say “no”. Output if each number is greater than or less than or equal to 5.
def output(number):
if number > 5:
print("Greater than 5")
elif number < 5:
print("Less than 5")
else:
print("It is equal to 5")
userInput = "yes"
print(userInput.lower() != "no")
num = input("Enter a number \n")
output(userInput)
userInput = input("Would you like to try again?")
You're trying to compare a str with an int. The following will fix it:
def output(number):
if number > 5:
print("Greater than 5")
elif number < 5:
print("Less than 5")
else:
print("It is equal to 5")
userInput = "yes"
print(userInput.lower() != "no")
num = int(input("Enter a number \n"))
output(userInput)
userInput = input("Would you like to try again?")
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 2 years ago.
Improve this question
I am trying to make it so that the user can input as many positive numbers as they want but when a negative is inputted it ends the loop and outputs the largest number inputted.
This is what I have so far
num = int(input("Enter a number: "))
while (num >= 0):
num = int(input("Enter a number: "))
if (num < 0):
print("Largest number entered: " + str(num))
Like that i guess
maxnum = int(input("Enter a number: "))
while True:
num = int(input("Enter a number: "))
if num < 0: break
maxnum = num if num > maxnum else num
if (num < 0):
print("Largest number entered: " + str(maxnum))
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 5 years ago.
Improve this question
I am a Python newbie and stuck with the following question:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
My solution:
largest = None
smallest = None
store=[]
while True:
num = input("Enter a number: ")
try:
if num == "done" : break
else:
store.append(num)
except:
print("U have an invalid entry")
largest=max(store)
smallest=min(store)
print ("Invalid input")
print ("Maximum is",largest)
print ("Minimum is",smallest)
None of the print statement are being printed out.
input returns a string; if the string is not "done", you should try to convert it to an integer with int().
If that fails, it will throw ValueError; you should catch only that exception. Using a bare except: catches ALL exceptions, which is usually a bad idea.
You don't need to keep all the numbers in store; you only need to keep the lowest and highest so far.
I've made a couple more changes:
You got rid of input in num = input("Enter a number: "); I put it back.
When comparing to None, use is instead of ==
n < smallest would throw a TypeError if smallest is None; we guard against this by checking for smallest is None first. or is lazy, so a or b -> if a is True, b never gets evaluated, so we never cause an error.
Result:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
if smallest is None or n < smallest:
smallest = n
if largest is None or n > largest:
largest = n
except ValueError:
# num cannot be converted to an int
print ("Invalid input")
print("Smallest is", smallest)
print("Largest is", largest)
which runs like
Enter a number: 7
Enter a number: 2
Enter a number: bob
Invalid input
Enter a number: 10
Enter a number: 4
Enter a number: done
Smallest is 2
Largest is 10
Your try-except block cannot raise any exception. It's always correct.
You should convert your input to int and this operation can cause an error.
# largest = None
# smallest = None
store=[]
while True:
s = input("Enter a number: ")
if s == "done":
break
try:
store.append(int(s))
except:
print("U have an invalid entry")
largest = max(store)
smallest = min(store)
# print("Invalid input")
print("Maximum is ", largest)
print("Minimum is ", smallest)
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 6 years ago.
Improve this question
Instructions: Program needs to ask the user for a number. For example "5". The program outputs the number 15, as 1+2+3+4+5=15.
I am a novice and am stuck at the beginning:
n = (input("Insert a number: "))
while n != 0:
Please guide me what to do further
You can do it like this:
num = int(input("Choose a number: "))
total = sum(range(num + 1))
If you HAVE to do it using a while loop, you can do it this way:
total = 0
counter = 0
max = int(input("Choose a number: "))
while counter <= max:
total += counter
counter += 1
print(total)
n = int(input("Insert a number: "))
nums = range(1,n+1)
print sum(nums)
if you want to do the same thing with while loop:
n = int(input("Insert a number: "))
sum =0
while n>0:
sum+=n
n-=1
print sum
Maybe you can use something like this code:
try:
nr_in = int(input("Enter some number: "))
nr_out = 0
tmp = 0
while tmp < nr_in:
tmp += 1
nr_out += tmp
print(nr_out)
except:
print("This is not a number!")
This isn't the shortest and most pythonic way, but I think it might be easier to understand for you.
Hope this helps!
Do you use python 3 or 2? In python2, raw_input is recommended.
Basically all you need is to convert the string to numeric value ...
inp = input("number: ")
try:
n = int(inp)
except ValueError:
print("Please give me a number")
sys.exit(1)