I have written a prime number program and I'm having a trouble with printing out the message "Neither prime nor a composite" as below. I think my code is fine as it is. I'd highly appreciate any comment on this issue. Thank you, in advance
def prime_number():
a = input("Please enter a number:")
x = True
s = 0
for i in range(2, a):
while x:
if a%i == 0:
x = False
elif s:
print s,"Neither a prime nor a composite"
else:
x = True
if x:
print a,"is a prime number."
elif s:
print s,"Neither a prime nor a composite"
else:
print a,"is not a prime number."
prime_number()
Your variable s will stay equall to 0 which is equall to False forever, so there is no way that Your code is going to print "Neither a prime nor a composite"
Just like Chantwaffle said, you'll never get s equal to anything else than 0, because there's no code changing it to anything else. Also, if a <= 2 you'll never enter this for loop, and elif s is always False, since s is defined as 0 at the beginning. Rewrite that code thinking of what you want to achieve and what should be done to get it. Repair logic of this code.
Related
#code
testcases=int(input())
while testcases!=0:
s=input()
lower,upper,numeric=0,0,0
for i in s:
if ord(i)>=49 and ord(i)<=57:
numeric+=1
elif ord(i)>=65 and ord(i)<=90:
upper+=1
elif ord(i)>=97 and ord(i)<=122:
lower+=1
if(upper>=1 and lower>=1 and numeric>=1):
print("YES")
else:
print("NO")
testcases-=1
The Question is : Given a string i have to Say if the String is a Valid Paswword or not.
For a String to be a valid password following needs to be fullfilled:
1.Atleast one uppercase letter
2.Atleast one lower case letter
3.Atleast one numeric.
if its a valid pasword print "YES" orelse print "NO"
I am not able to figure out why i am getting "wrong answer" on submission in GFG. When i run against custom test cases i get the desired result , but on submission it shows "wrong answer". Can someone please help, what wrong with my code?
I would be able to figure out but the ide of gfg does not tell the reason behind wrong number it just says wrong answer..how will i be able to figure out then?
Constraints:
1<=T<=10^4
1<=|S|<=4*10^5
Sum of S over all tc's does not exceed 4*10^5
You are not checking for zero. To avoid this kind of error use the chars, so it is clearer what the code is doing.
The cause of the error is the antipattern "magic numbers". Programmers should avoid writing numbers directly in the code, because is harder for humans to understand the code, and is prone to error, like this one.
testcases = int(input())
while testcases != 0:
s = input()
lower, upper, numeric = 0, 0, 0
for i in s:
if ord(i) >= ord("0") and ord(i) <= ord("9"):
numeric += 1
elif ord(i) >= ord("A") and ord(i) <= ord("Z"):
upper += 1
elif ord(i) >= ord("a") and ord(i) <= ord("z"):
lower += 1
if upper >= 1 and lower >= 1 and numeric >= 1:
print("YES")
else:
print("NO")
testcases -= 1
Edit:
I misread the testcases part and see that you want to test multiple... still leaving this code here for anyone that finds it useful:
You can do a while True loop and then break the loop when the desired result occurs. This will stop your double input() so you don't have to enter the password twice (as you do in your code). Also, if you use isnumeric(), isupper(), and islower() it looks cleaner:
while True:
s=input()
lower,upper,numeric=0,0,0
for i in s:
if i.isnumeric():
numeric+=1
elif i.isupper():
upper+=1
elif i.islower():
lower+=1
if(upper>=1 and lower>=1 and numeric>=1):
print("YES")
break
else:
print("NO")
so pretty straight forward, I had to write a code to check if a number if Prime or not. Code tested on Jupyter Notebook and works PERFECTLY. But whenever I put it in CodeWars, it passes the initial tests but later on when I submit the attempt, it times out, saying that the code may be "inefficient". Does anyone have an insight as to why this might be happening? Here is the code:
def is_prime(num):
mylist = []
if num != 1 and num > 0:
for number in range(1,num+1):
if num % number == 0:
mylist.append(number)
else:
pass
if len(mylist)>2:
return False
else:
return True
else:
return False
For large numbers, your time to compute will take too long.
I suggest looking more into the properties of prime numbers and reevaluating your code.
Ex: Properties of Prime Numbers!
can you try this and see how it works in CodeWars.
for num in range(1,7):
if all(num%i!=0 for i in range(2,num)):
print('Prime' , num)
I need to create a program that will convert Base 10 numbers in Base 2.
Next is the code, it can not run as expected even if it has no error:
E = input('Please enter a number')
Eint= int(E)
for N in range(100,0):
while 2**N > Eint:
N = N-1
print(0)
if B**N <= Eint:
Eint = Eint - 2**N
print(1)
Print('finished')
When I'm running it it will ask me the number but that's all, thank you for your help guys.
From a quick inspection, range(100,0), B, and Print() are three culprits here! If you want to pass through numbers from 0 to 99, then range(100) is what you need. Now, what is B? Print should be written in lower case: print.
After we fix these syntax errors, let us try to revisit the program and understand what it is supposed to do. Have fun :-)
EDIT to fix the code in the question:
E = input('Please enter a number: ')
Eint = int(E)
for N in range(8,-1,-1):
if 2**N > Eint:
print(0, end='')
else:
Eint = Eint - 2**N
print(1, end='')
print()
print('finished')
Please note that Python is a language that uses indentations to denote code blocks. This code will convert a decimal to binary. Now, note that the range start of 8 gives you a hint about the upper bound of the number that the code can translate. Therefore, an if condition must be added after the second statement to ensure we are not attempting to convert a number that is too large. Enjoy!
If it helps check my solution too. Because I guess you don't want to see the result on separate lines, so I create a list for you to see the result in one line.
E = int(input('Please enter a number\n'))
Eint = E
base_two=[]
while E > 0:
a = int(float(E%2))
base_two.append(a)
E = (E-a)/2
base_two.append(0)
string = ""
for j in base_two[::-1]:
string = string+str(j)
print("Binary for", Eint, "is", string)
print('finished')
I was late a little bit :)
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
noob programmer here. I am trying to build a small program in 2.7 which generates a prime number, asks the user to continue or not, and then continues generating primes until the user tells it to stop. Unfortunately my program isn't outputting anything at all, and I can't figure out why.
Here is my code:
First, the part which checks for primes. I know that this part is functioning properly, because the exact same code works properly for my prime factor finder.
def isprime(num): #this checks the numbers to see if they're prime
prime = True
for i in range(2,num):
if num/i == (num*1.0)/i:
prime = False
return False
break
else:
prime = True
if prime == True:
return True
And second, the part which iterates through all the numbers, prints result, and asks to continue or not. The error must be in here somewhere:
def primegen():
n = 1
while True:
if isprime(n) == True:
print n
cont = raw_input("continue? Enter Y/N")
if cont == 'N':
break
n+=1
primegen()
n should be incremented unconditionally. If it isn't the program gets stuck in an infinite loop the first time it encounters a non-prime.
def primegen():
n = 1
while True:
if isprime(n):
print n
cont = raw_input("continue? Enter Y/N")
if cont == 'N':
break
n += 1
Your code is a bit chaotic, I would rewrite it like this:
def isPrime(num):
if num % 2 == 0:
return True
return False
n=1
while True:
if isPrime(n):
print n
cont = raw_input("Do you want to continue? (1,0) ")
if not bool(int(cont)):
break
n += 1