Creating an exclusion in Python - python

I'm writing a program that should add all positive values that a user enters, and the program should loop until he/she enter a negative number. The program loops smoothly but it includes the negative number in the sum. Any help is appreciated!
def main ():
X=0
Y=0
print("I can add the sum of all positive numbers")
X = int (input ("Please enter a positve number between 0 and infinity: "))
if X > 0:
while Y >= 0:
print("I can add the sum of all positive numbers")
Y = int(input("Please enter a positive number between 0 and infinity: "))
X = X + Y
print("The sum of the numbers you entered is: ", X)
else:
print("Sorry I can only add positive numbers")
main()

Make the addition X = X + Y before you input the number (but inside the while). You initialized both variables so the "extra" addition before entering a number is just X = 0 + 0 and has no negative effect.
Otherwise it will execute the addition one more time (even if you entered a negative number) before the while loop exits. The condition of the while loop is only tested when first trying to enter it and each time the code inside it is finished and the program checks if it should perform another "loop".

Related

Fixing While Loops Python

We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')

Stuck with this

I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.

Factorial using two functions Python 3.x

Hello everyone I have a homework assignment that I am supposed to do in python 3.x
I am struggling to figure out how to do this so I'm hoping you can explain to me how to about this.
Problem
The factorial of a positive integer n (written n!) is the product 1 x 2 x 3 x ... x n. Write a program that asks the user to input a positive integer and then calculates and displays the factorial of the number. The program should include two functions: getN to which the input is sent, and which guarantees that the input is a positive integer. The function fact should calculate the factorial value. The program (main) should then display the factorial value.
So far I have a rough sketch of how I want to go about this
#This program will show the answer to a factorial after the user inputs a value.
def getN(n):
try:
n = int(input("Please enter a non-negative integer: "))
except n < 1:
print("You did not enter a value of 1 or greater.")
def fact(n):
count = 1
while n > 0:
count *= n
n -= 1
if n == 0:
break
def main(n):
n = int(input("Please enter a non-negative integer: "))
getN(n)
main(n)
I believe its supposed to look something like this. If you can give me some feedback about what I should do that what be greatly appreciated. Thanks!
Please see inline comments
def getN():
try:
n = int(input("Please enter a non-negative integer: "))
if n < 1:
raise ValueError # it will be thrown also if input is not a valid int
except ValueError: # n < 1 is not an Exception type
print("You did not enter a value of 1 or greater.")
else:
return n
def fact(n):
count = 1
for i in range(1, n+1): # you see how simple it is with for loop?
count *= i
return count
def main():
n = getN() # before you were just asking n twice, never using fact()
print(fact(n))
main()
Seems reasonable to me. It looks like you never return or print the actual factorial calculation. Maybe your function 'fact' should "return count"? In addition, you don't need to check "if n==0" in your fact function, since if it is 0 it will end the while loop due to the condition of the while loop.

Returning a value under if statement for Python 2.7

I am trying to calculate factorial of a number. If the user enters a negative number, I want the loop to rerun. However, when I use the return function under if statement for negative values, it gives me an error of
"SyntaxError: 'return' outside function"
How can I rerun the loop if the user enters a negative number.
# Calculating the Factorial of a Number
number = input ("Please enter a positive number: ")
factorial = 1
if number > 0:
for n in range (1, number):
factorial = factorial * (n+1)
print ("You entered the number of " + str(number) + ". The factorial of that number is " + str (factorial))
else:
number = input ("You entered a negative number. Please enter a positive number: ")
return number
You do have a return statement outside of a function.
How can I rerun the loop if the user enters a negative number?
Use a while loop:
number = -1
while number < 0:
try:
# since factorial applies to integers only
number = int(input("Please enter a positive number: "))
except ValueError: # so we don't crash if the user enters a string or a float
pass
# here number is guaranteed to be a positive integer
factorial = 1
for n in range (1, number):
factorial = factorial * (n+1)
print 'The factorial of {number} is {factorial}'.format(number=number,
factorial=factorial)

Python I need to write a loop that creates two seperate running totals, and I don't understand my error

I have a homework problem that I cant figure out, can someone help
--Create a function called sums that will prompt the user to enter integer values (either positive or negative). The function should keep separate running totals of the positive values and the negative values. The user should be allowed to continue entering values until he/she enters a zero to stop.
Here's what I got and it doesn't work
number = int(raw_input("Enter and a positive or negative integer: "))
def sums(number):
while (number > 0):
posnumber = int(raw_input("Enter another number or 0 to quit: " ))
number = number + posnumber
print "The positive total is", number
while (number < 0):
negnumber = int(raw_input("Enter another number or 0 to quit: " ))
number = number + negnumber
print "The negative total is", number
it just runs the loop under the first iteration, I'm confused as to what to do to correct it
Because they're separate while loops - the first one is executed, then the second one is executed. You don't want that at all. Here's a layout of what you should do:
take a number from input, store it as inputnum
while inputnum isn't 0
determine whether inputnum is positive or negative
add inputnum to the either posnumber or negnumber
print the total
get a new inputnum
That is, you should have an if inside a while, not two whiles.

Categories