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'm new to Python and testing myself with some questions. One that came up was to test whether a user inputted number was prime or not. Easy enough, but one person came up with a single line of code as a solution.
import math
num = int(input("Enter a number greater than 2 "))
if sum([True if num%factor == 0 else False for factor in ([2] + list(range(3,int(math.sqrt(num)),2)))]):
print("Number is composite")
else:
print("Number is prime")
I understand part of it: the if statement is True if (number/iterations) gives a remainder of 0, else False, where the only iterations that need to be checked are 2 -> sqrt(number) skipping all even numbers.
However, I can't work out how to sum operator at the start of the if statement works. I assume it operates on the True(1)/False(0) statements, but how does this interaction play out and how does it affect the if/else statements?
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.
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).
This question already has answers here:
error while passing the value in python
(2 answers)
Closed 8 years ago.
def row_minimum(x,L):
L=L
if x=='1':
row_minimum1=min(L[0],L[1],L[2],L[3],L[4])
return row_minimum1
elif x=='2':
row_minimum2=min(L[5],L[6],L[7],L[8],L[9])
return row_minimum2
elif x=='3':
row_minimum3=min(L[10],L[11],L[12],L[13],L[14])
return row_minimum3
table(L)
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
elif y !=['1','2','3','A','B','C','D','E']:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
user_input(x)
print (user_input(x))
if user_input(x) in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
i am getting the value of user_input(x) to none instead i want it to take the value from the user and compare in the if statement and do the minimum.
You have a nested definition for user_input and the first one doesn't return anything, resulting in None being returned. Take out the first or second def.
Note that this is far from the only thing wrong with this program.
Looks like you have a logic issue in user_input() function. If I understood it right, you are trying to check if y is one of the row/column names and set condition to False in this case. Otherwise (if it is not in your list of allowed characters), you want to set the condition to True and re-prompt the user for correct input until she gives you the value you want.
If it is so, you better be checking y if it is NOT in the list. Your code, though, checks if y is not the LIST itself: y !=['1','2','3','A','B','C','D','E']. Even if the user gives you a good value, say 'B' it is still not equal to the list of strings ['1','2','3','A','B','C','D','E'], it is IN this list (thats what you should be checking for). I think, itll help if you rewrite the function to make it something like:
def user_input(y):
if y in ['1','2','3','A','B','C','D','E']:
condition = False
else:
condition = True
while condition == True:
z=input("Enter a row (as a number) or a column (as and uppercase letter):")
if z in ['1','2','3','A','B','C','D','E']:
condition = False
return z
You may also want to experiment with Python style guide and make this code look nicer ;)
Your user_input() function seems like a bad idea. As far as I can tell it is meant to check for bad input, and keeps asking for input until it gets good input. The problem is, it only returns if the initial input was bad, if the initial input was good, then the function does not return.
You can just get rid of this function altogether, since you end up checking the input anyway. you can just do:
def menu(a,L):
if a==1:
display_table(L)
elif a==2:
while True:
x=input("Enter a row (as a number) or a column (as and uppercase letter):")
print x
if x in ['1','2','3']:
mini = row_minimum(x,l)
print ("2")
print("Minimum is:",row_minimum(x,L))
break
elif x in ['A','B','C','D','E']:
whatever you want to do here
break