Incrementing from within for loop - python

I am trying to generate 5 unique random numbers and I have written a for loop for it:
for i in range(5):
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
If x is not in a, only then i should be incremented. I can do this with while loop but want to know if we can do this with a for loop.

You can do this by converting a range into list.
Please follow the given example code.
a = list()
n = 2
myrange = list(range(n)) # converting your range into list
for i in myrange:
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
else :
# add current i again in the rangelist at starting position
myrange.insert(0,i)

You can't change how many times for i in range() loop runs. Changing i in the loop has no effect on the range() object.
You can use a nested loop that keeps asking until it gets a number that's not found.
for _ in range(5):
while True:
print("enter a no")
x = int(input())
if x not in a:
a.append(x)
break

Here are some approaches:
Option 1 :
Using an infinite value in the range function :
def to_infinity():
index = 0
while True:
yield index
index += 1
for i in to_infinity():
print("enter a no")
x = int(input())
if len(a) > 5:
break
if x not in a:
a.append(x)
Option 2 :
Using itertools.count:
import itertools
for i in itertools.count(start=1):
print("enter a no")
x = int(input())
if len(a) > 5:
break
if x not in a:
a.append(x)

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")

Create an odd number list

i want to make an odd number list by using 'while' and 'for'
a = []
x = 1
while x < 101:
if x % 2 != 0:
a.append(x)
x = x + 1
print(a)
but nothing happened... and other unrelated codes which is in another sentence are also not executed.
what is my problem?
You should increase the value of x in each iteration and not only if the value is an odd number:
a = []
x = 1
while x < 101:
if x % 2 != 0:
a.append(x)
x += 1
print(a)
Though this is probably for learning purposes note that you could achieve this using the range function as follows: list(range(1,101, 2)).
When you increment x, it should be out of 'if' condition. increment should happen under while
a = list()
x = 1
while x <101:
if x%2 != 0:
a.append(x)
x += 1
print(a)
You can use the range function as well (for for loop) which handles the increment part in the loop as below:
FOR LOOP:
odd=[]
for i in range(101):
if (i%2!=0):
odd.append(i)
print (odd)
WHILE LOOP:
odd=[]
i = 1
while i<101:
if i%2 != 0:
odd.append(i)
i+=1
print (odd)
odd = [i for i in range(101) if i%2 != 0]
print(odd)

How do you mulitply via addition?

I'm having trouble trying to
compute x * y using only addition, printing the intermediate result for each loop iteration, and
printing the final number. This is my
teacher's example of what the output should look like
I could really use some help figuring it out,, I don't really understand how to yet.
Edit: I am a first time coder so I'm not very skilled, I do know the basics though (Also very new to this website) Here's what my code looks like so far:
x = int(input("Input positive x: "))
y = int(input("Input positive y: "))
z = 0
w = 0
if x < 0:
exit("Please input a positive number for x")
if y < 0:
exit("Please input a positive number for y")
def multiplier(number, iterations):
for i in range(1, iterations):
number = number + 3
print(number) # 12
multiplier(number=3, iterations=4)
My answer. Little shorter than the others.
Ok, try thinking of multiplication as adding a number with itself by x times. Hence, 3*4 = 3+3+3+3 = 12, which is adding 3 by itself 4 times
Replicating this with a for loop:
#inputs
x = 3
y = 4
#output
iteration = 1
result = 0
for num in range(4):
result += x
print(f'Sum after iteration {iteration}: {result}')
iteration += 1 #iteration counter
The resulting output will be:
Sum after iteration 1: 3 Sum after iteration 2: 6 Sum after iteration
3: 9 Sum after iteration 4: 12
The code is simple and straightforward,Check which number is bigger and iterate according to that number.
x = 3
y = 4
out = 0
if x > y:
for v in range(0,x):
out += y
print("after iteration",v+1, ":", out)
if y > x:
for v in range(0,y):
out += x
print("after iteration",v+1, ":", out)
print(x,"*", y, "=", out)
Use print to print inside the loop to show each number after adding and the number of iteration occurs.
Here is a start. This assume both arguments are integers 0 or more:
def m(n1, n1a):
n1b = 0
while n1a > 0:
n1b += n1
n1a -= 1
return n1b
n = m(9, 8)
print(n == 72)

REMOVING REPEATED NUMBER FROM LIST, not working

I have written this code to remove repeating numbers from the list and output the max number. However, it is not removing the number which is repeated on the 4th index value. please help.
array = input()
nums = (array.split())
num = [int(i) for i in nums]
n = 0
for j in num:
for q in num:
if q == j:
n += 1
if n > 1:
while j in num:
num.remove(j)
n = 0
print(num)
print(max(num))
pythons build in function set() does this for you.
_list = [1,2,3,4,5,6,7,8,9,1,2]
print(set(_list))
outputs:
[1,2,3,4,5,6,7,8,9]

Creating Python Factorial

Evening,
I'm an intro to python student having some trouble.
I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)
The 'classic' factorial function in school is a recursive definition:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
If you just want a way to fix yours:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
If you want a test for numbers less than 1:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Or, test n after input:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Here is a functional way using reduce:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800
You are actually very close. Just update the value of n with each iteration:
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
# Update n
n -= 1
print(num)
I am new to python and this is my factorial program.
def factorial(n):
x = []
for i in range(n):
x.append(n)
n = n-1
print(x)
y = len(x)
j = 0
m = 1
while j != y:
m = m *(x[j])
j = j+1
print(m)
factorial(5)
You could do something like this.
def Factorial(y):
x = len(y)
number = 1
for i in range(x):
number = number * (i + 1)
print(number)
#Factorial using list
fact=list()
fact1=input("Enter Factorial Number:")
for i in range(1,int(fact1)+1):
fact.append(i)
print(fact)
sum=fact[0]
for j in range(0,len(fact)):
sum*=fact[j]
print(sum)
i=1
f = 1
n = int(input("Enter n: "))
if n>=0:
while n >= i:
f=i*f
i+=1
print(f)
I am using this code in order to calculate factorial and it works.(Python 3.8)

Categories

Resources