Just going through a Python 3.x self-study book. I've got a basic code, which allows user to enter a sequence of nonnegative int. When the user inputs a negative int, the sequence stops and a result is printed. It looks like that:
entry = 0
sum = 0
print("Enter numbers to sum, negative number ends list: ")
while entry >= 0:
entry = int(input())
if entry >= 0:
sum += entry
print("Sum =", sum)
Now I got to a exercise questions part of the book. It asks if the condition of the if statement could have used
>
instead of
>=
Also if the condition of the while loop could use
>
instead of
>=.
I have obviously tried both combinations and noticed that the > could be used in the if condition instead of >=, which would not affect the program. But if I would swap the >= for > in while statement the program would stop right after running it, showing Sum=0, not allowing the user to input any integers. Why swapping if condition doesn't change anything, but swapping while condition affects the program?
If you read each statement in sequence, you can probably see what happens:
entry = 0
Entry is zero ...
while entry > 0:
While entry is larger than zero, do this ..
But since entry isn't larger than zero, the while loop never runs. The statement is checked before the loop is invoked the first time, so your program continues with the next statement (print) instead.
When you have >=, you also allow the value 0 - so "While entry is larger than, or equal to, zero" allows the loop to run.
Changing
if entry >= 0:
sum += entry
into
if entry > 0:
sum += entry
won't change the behavior of the program since adding 0 to any number doesn't change the value.
Changing while entry >= 0 into while entry > 0 would break the program because the loop would never be entered with the intialization of entry = 0.
Related
I am trying to make code that can round numbers i am starting off small and don't know why but getting errors and am trying to state "if this number is less or equal to 4 change the value to zero and print it, otherwise if it is greater than or eqaul to 5 the change it to a 10"
import math
import random
def help(num):
if num <= 4 num = "0"
else:
if num >= 5 num = "10"
result = help(5)
print(result)
If you aren't already, try using an IDE (I use PyCharm). These will highlight errors in your code and give suggestions as to how you may fix or handle them.
First of all, python requires proper formatting of whitespace to run correctly. Here's a useful StackOverflow link to give you an idea of what I mean.
Secondly, when you want to refer to a real number value, (i.e The mathematical number 0 as opposed to the letter representing 0), don't use quotes. When you use quotes you tell python "this is a word made of letters" instead of a number made of digits.
Third, you are missing the colon : at the end of your if and else statements. These are just necessary syntax.
Fourth, you need a return statement in your help() function if you want it to return a value.
Lastly, ensure that the last two lines are not within the method help() if you want them to run when the .py file is run.
Here's your modified code:
import math
import random
def help(num):
if num <= 4 :
num = 0
elif num >= 5:
num = "10"
return num
result = help(5)
print(result)
You don't need to be checking for greater or equal to 5 in this case if you've got just two outcomes.
def help(num):
return 0 if num <=4 else 10
result = help(5)
print(result)
I have an if/else statement in my program, and the if statement checks 3 factors, one being if the input given from the user is a multiple of 5, and if it is not, it runs the program. I am currently using the modulus operator, but even when I input a multiple of 5 it still runs the program instead of moving on to the else statement.
Here is my code:
if(cost == 0) or (cost > 100) or (cost != 100%5):
To check if a number is a multiple of x, use the following code:
number % x == 0
To check if this is not the case, simply replace the "==" with "!=":
number % x != 0
For more information regarding the modulo operation visit the wikipedia
My code is a PYTHON program that identifies if a number is prime or not. When I entered 45 however, it said that 45 was a prime, even though 45 isn't a prime number. Also, every time I run the program, it prints 'Sorry, the number you have entered is not prime.' or 'The number is indeed prime!' multiple times, instead of once. How do I make it print the output statements once and how can fix the program so that it says 45 IS NOT a prime number.
n = eval(input("Enter a number to find if that number is prime: "))
a = 2
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break
else:
print('The number you have entered is indeed prime!')
Because you are printing it every time. If you want to break after finding/not finding the prime number, indent one more level for the break.
Also, this does not calculate prime numbers. It calculates if its even number.
Follow the solution here
Your code has some issues. To start with, you're never updating a, so you only ever check if the number n is even.
Once you fix that, you have two indentation problems. The first is that the break line needs to be inside the body of the if statement. Indent it more so that it's inside the if block.
The second indentation issue is more subtle. If you leave the else where it is, it will print out that the number is prime every time you test a potential factor that doesn't divide the number. That's both unhelpful (since it prints a lot) and wrong (since it says the number is prime even if it will later find a factor and say it's not prime). You can fix this by unindenting the else line so that it is lined up with the while statement. Using an else after a loop is an obscure bit of Python syntax. The body of the else only runs if the condition of the loop fails. It gets skipped if the loop exits due to a break statement.
Here's all of those necessary fixes together:
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break # indent this line more!
a += 1 # increment a, so you don't keep checking 2 over and over
else: # unindent this line (and the next line too)
print('The number you have entered is indeed prime!')
There are some other things that could be improved in your code, though they aren't causing it to run incorrectly. I'd recommend using int instead of eval to parse your number, and I'd use the logical-and operator and instead of the bitwise-and operator & in the if statement (though actually you don't need either, since the a != n check is redundant, as the loop would have already ended if it was true).
First, in my code i'm asked to enter a value from user and the program should place it in the correct orderly position without using the built-in python sort().
My completed code can do this without repetitively inserting the same element, only with the break command. Now i once i remove the break command the number i enter outputs in the list 3 times instead of 1.
Note: we aren't allowed to use the break statement in this Python course
Currently my code looks like this:
#List of numbers
myList = [1,9,16,24]
#Enter a number to be placed in the list
num = int(input("Enter a number: "))
#For loop to check the placement of entered number
#to compare it and see if it is less than or
#equal to the each and every element in myList
for x in range(0, len(myList)-1):
if num < myList[x]:
myList.insert(x,num)
#break
elif num > myList[x]:
myList.append(num)
#break
print(myList)
ex. output:
[-1,-1,-1,1,9,16,24]
Simple. Have an external condition that you can test at each insertion attempt. If you insert the item, set the condition to false. Then, outside of the loop, if the condition is still true you know the item goes at the end. No breaks involved.
myList = [1,9,16,24]
num = int(input("Enter a number: "))
condition = True
for index, x in enumerate(myList):
if condition and num < x:
myList.insert(index, num)
condition = False
if condition:
myList.append(num)
print(myList)
This is part of a tutorial. My goal was to take an input from user and then increment it while a condition is true.
inputNum = raw_input("What is max number?")
def incrementF(greatest):
i = 0
numbers = []
while i < greatest:
print "At the top of the list numbers is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers:"
for num in numbers:
print num
incrementF(inputNum)
When I run the script and type anything in for inputNum, rather than a few lines of output, I appear to run into an infinite loop.
For example, is the raw input prompt gave 10, I'd have expected to see something like:
At the top of the list numbers is 0,
Numbers now: 0,
0
At the top of the list numbers is 1,
Numbers now: 1,
1
I've read over my script several times and cannot see. I suspect it could have something to do with indenting? But I'm not sure.
As quoted in the docs for raw_input:
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that.
So, greatest will be a string because you used raw_input to get it.
Furthermore, in Python 2.x, strings are always evaluated as being greater than integers*:
>>> 1 < 'a'
True
>>> 100000000000 < 'a'
True
>>>
This means that the condition of your while-loop will always evaluate to True because greatest will always be evaluated as being greater than i. Thus, you get an infinite loop.
You can fix this problem simply by making greatest an integer like i:
inputNum = int(raw_input("What is max number?"))
*Note: If you would like some more information on this, see How does Python compare string and int?