How to print only once in loop? - python

b = input().split(' ')
c = list(map(int,b))
y = 0
for i in range(len(b)):
if c[i] %2 == 0:
print(c[i])
y = 1
elif i == len(c) - 1 & y == 0:
print('No number that is divisible by 2')
Code takes a list of numbers as input, then it prints all values divisible by 2, but if there are no such values it should print about this only once. My code works properly only in certain cases. I know another implementation but i need solution within 1 loop

Add break:
b = input().split(' ')
c = list(map(int,b))
y = 0
for i in range(len(b)):
if c[i] %2 == 0:
print(c[i])
y = 1
elif i == len(c) - 1 & y == 0:
print('No number that is divisible by 2')
break

You may want to simplify by calculating the numbers divisible by 2 first, then deciding what to print:
nums = map(int, input().split(' '))
div2 = [i for i in nums if not i % 2]
if div2:
for i in div2:
print(i)
else:
print('No number that is divisible by 2')

Related

Trouble with making python rearrange code to my wanted format. (Python 3.6)

So basically I want python to first wait and let me input stuff and then do whatever it has to for every pair of inputs.
t = int(input())
E = 0
for i in range(0, t):
M, N = [int(M) for M in input(" ").split()]
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The terminal looks somewhat like this,
13 100
X
2 0
Y
I want the 2 0 to be before X but at the same time I want the code to calculate for 13 100 and output X but just after I input the 2nd pair of X, Y.
I also want to know how to remove the spaces before the '2 0' and the 'Y'.
Thanks.
Firstly, the reason you have spaces before 2 0 is because in the line:
M, N = [int(M) for M in input(" ").split()]
your input function has a space within the quotes, so you must remove it and just have an empty string:
M, N = [int(M) for M in input("").split()]
Next, the reason your code is asking for input then generating an output and so on is because the logical operators are within the for loop you have. To fix this you should have your loop to first gather the inputs then, have another loop to perform the logical operators on those inputs as so:
t = 2
E = 0
numList = []
for i in range(0, t):
M, N = [int(M) for M in input("").split()]
numList.append([M, N])
for val in numList:
if E in range(0, t):
if val[0] > 0 and val[1] > 0:
print("X")
if val[0] > 0 and val[1] == 0:
print("Y")
if val[0] == 0 and val[1] > 0:
print("Z")
To simplify things I set t = 2 since we are only talking about 2 pairs of numbers. Furthermore, I created a list to hold each pair of inputs (numList), in which the first for loop appends the values to it as an list. The next for loop looks at each item in numList and since numList is a list of lists I changed M and N to val[0] and val[1] which refer to the first number you inputed (M) and the second one you inputed (N).
Finally,
for i in range(0, t):
should look like:
for i in range(t):
Since the range function automatically just counts from 0 to t and "i += 1" at the end of the loop is also unnecessary and redundant.
My final output:
[1]: https://i.stack.imgur.com/1Bo9U.png
Put all the inputs in a 2-dimensional list before the loop that processes them.
t = int(input())
E = 0
all_inputs = [[int(M) for M in input(" ").split()] for _ in range(t)]
for M, N in all_inputs:
if E in range(0, t):
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")
i += 1
The space before the 2 0 is the prompt " " in your input(" ") call. If you don't want that, use input() with no prompt.
I don't see any reason for the space before Y.
Hope this help. Its a little cleaned up:
iterations = int(input("How many times? "))
values = []
for i in range(iterations):
values.append([int(M) for M in input(f"{i+1}. Enter two numbers: ").split()])
for M, N in values:
print(M, N, end=' -> ')
if M > 0 and N > 0:
print("X")
if M > 0 and N == 0:
print("Y")
if M == 0 and N > 0:
print("Z")

is there a way to make the x odd

I have been trying to make a simple code with python in which it takes an input 'n' and outputs the numbers from 1 to n
for each multiple of 3, print Solo instead of the number
for each multiple of 5, print Learn instead of the number
for numbers which are multiples of both 3 and 5, output SoloLearn
I want to code it in a way that the logic will skip the even numbers and can only be applied to odd numbers in the range
this is my code below
n = int(input())
for x in range(1, n):
if x % 3 == 0 and x % 5 == 0:
print("SoloLearn")
elif x % 3 == 0:
print("Solo")
elif x % 5 == 0:
print("Learn")
else:
print(x)
Add a continue clause at the top of your loop:
if x % 2 == 0:
continue
For more details, read the docs.
The simplest/fastest/smallest amount of changes you need to make is to just alter the range function to give you exactly what you want.
n = int(input())
for x in range(1, n + 1 , 2):
if x % 3 == 0 and x % 5 == 0:
print("SoloLearn")
elif x % 3 == 0:
print("Solo")
elif x % 5 == 0:
print("Learn")
else:
print(x)
I added n+1 not to satisfy your question, but because I think as written your code was not correct -> for example run these two snippets and see what I mean. If you didn't want n to be part of the range than your code is correct without the n+1.
print("no +1")
for i in range(1,11,2):
print(i)
print("\n\nwith + 1"
for i in range(1,11+1,1):
print(i)
Convert the 'for' loop to 'while' loop . Since we are starting with 1 , adding 2 in each iteration , makes the loop run only for odd numbers.
n = int(input())
x=1
while x<n:
if x % 3 == 0 and x % 5 == 0:
print(x ,"SoloLearn")
elif x % 3 == 0:
print(x, "Solo")
elif x % 5 == 0:
print(x, "Learn")
else:
print(x)
x=x+2

How to print x amount of answer instead of printing x amount of value?

I found this code on stackoverflow and everything works but I want to change the way it is printed. In this code, it prints everything where the value(n) is prime and up to 100. What I want to do is print the first hundred prime numbers. How do I do this? I have tried some kind of "(primes * 100)" because I thought multiplying it might work but it didn't. Thank you in advance.
def primes(n):
primeslist = [2]
for i in range (2,n):
p = 1
for j in primeslist:
if (i%j) == 0:
p = 0
break
if p == 1:
primeslist.append(i)
return primeslist
primeslist = primes(100)
print(primeslist)
You can print a slice of your list:
print(primeslist[:100])
If you want them in seperate lines:
print("\n".join([str(i) for i in primeslist[:100]]))
If you want to PRODUCE first 100 primes instead of primes up to value of 100 you must change:
for i in range (2,n):
to
while len(primeslist)<100:
If you want to print first n number of primes, this is one way of doing it.
i = 1
while True:
i += 1
p = 1
for j in primeslist:
if (i%j) == 0:
p = 0
break
if p == 1:
primeslist.append(i)
if len(primeslist) == n:
return primeslist
or this is another way of doing.
i = 1
while len(primeslist) == n:
i += 1
p = 1
for j in primeslist:
if (i%j) == 0:
p = 0
break
if p == 1:
primeslist.append(i)
return primeslist

Python code for finding the 1001st prime number

I recently started programming Python and was stuck at this particular Project Euler problem for finding the 1001st prime number.
My code:
L = [2]
def is_prime(x,L):
for el in L:
if x%el != 0:
flag = 1
else:
flag = 0
break
if flag == 1:
return True
elif flag == 0:
return False
a = 3
for k in range(1,1002):
if is_prime(a,L) is True:
L.append(a)
a += 1
k += 1
else:
a += 1
print(L)
print(len(L))
This prints the list of prime numbers upto 997 which is the 168th prime number. Can you tell me what am I doing wrong?
Your increment of k is pointless, because you're iterating a fixed range of numbers (k is replaced when the loop loops, the range can't be changed dynamically).
You want a while loop with a manually managed k:
a = 3
k = 1
while k < 1002:
if is_prime(a,L):
L.append(a)
a += 1
k += 1
else:
a += 1
Note: There may be some off-by-one logic errors here, but it expresses what I assume was your intent in the original code, fixing only the issue with managing k.
k += 1
That's where the problem is. Try this code:
for k in range(1, 1002):
print(k)
and then:
for k in range(1, 1002):
k += 1
print(k)
Your Mistake is that you are finding numbers that are prime UP to 1001 and Also variables of a loop cannot increase By the user
to fix that use a while loop
A Program To Find Up Prime's To Any Number would be:
import sys
def prime_num_finder():
i = 2
while True:
try:
p = int(input("Please enter up to what number the prime numbers should be: "))
break
except ValueError:
sys.stderr.write('ERROR\n')
sys.stderr.write(' Try again...\n')
while i != (p + 1):
x = i
if x % 2 and x % 3 and x % 5 and x % 7 > 0.1: # Checks if the remainder is greater than 0.1 to see if it has an remainder
r1 = True
else:
if i == 2 or i == 3 or i == 5 or i == 7:
r1 = True
else:
r1 = False
if r1 == True:
print(i, " is a prime number!")
else:
pass
i = i + 1
prime_num_finder()
quit()
That is a simple program to check if it is divisible by 2 ,3, 5, or 7

How to find first n number of prime numbers in python?unable to follow the scope of a variable?

f=0
c=1
n=raw_input("Enter the value of n")
while c<n:
for i in range(2,100):
for j in range(1,i):
if i%j == 0:
f =f+1
if f == 1:
print i
c = c+1
f = 0
If n is 5 then the output should print the first 5 prime numbers.
2,3,5,7,11
You have a few mistakes. You do not parse n as integer, you have an unnecessary loop, you inistailise c with a wrong value.
Here is a corrected version
c = 0
n=int(raw_input("Enter the value of n"))
i = 2
while True:
for j in range(2,i):
if i % j == 0:
break
else:
print i
c = c + 1
if c == n:
break
i += 1
Copy of answer to this question.
You're only checking the value of count at the end of the for loop so you will always end up with the full range of 1-100 being tested. Why is the range limited to 100?
You don't need a for loop at all. Use the while loop to keep finding primes until you have num of them.
Try something like:
import math
def isPrime(num):#this function courtesy of #JinnyCho
if num == 1:
return False
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num % i == 0:
return False
return True
def getPrimes(num):
count = 0
i = 1
highPrime = None
while count < num:
if isPrime(i):
count += 1
yield i
i += 1
n = int(raw_input("Enter the value of n: "))
list(getPrimes(n))

Categories

Resources