I wanted to take two numbers as an input 5 times and then print out all their sum. it would look like
enter two numbers:3 4
enter two numbers:3 5
enter two numbers:7 8
enter two numbers:7 1
enter two numbers:7 4
and an out put
7
8
15
8
11
Here is what i tried.
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
print(a+b)
My code prints out the sum for the last two inputs only.
The issue is that you are reassigning a and b during each iteration of the loop. Since you aren't storing the sum of a and b anywhere and when you move to the next iteration these values are updated to the latest inputs, there's no way to print them out. One easy fix is to append the sums to a list as you go and then print out the sums:
sums = []
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
sums.append(a+b)
for sum in sums:
print(sum)
Had you put the print(a+b) statement within the loop, this would simply print the sums after each pair of inputs is entered and before the next inputs can be entered. In case you're wondering, the reason the final sum is actually printed is that Python continues to store the values of a and b even after the loop is over. This is not necessarily expected behavior, but it allows you to print a and b even when the loop has finished as Python still remembers the last values that were assigned to them.
Put the print statement inside of the scope of the for loop like so:
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
print(a+b)
for i in range(5):
a,b = input("enter two numbers:").split()
print(int(a)+int(b))
I think that code can help you what you need.split method converts a and b to string.So you need to convert them to integer value when you sum them.
Related
Edit: Fixed the screwed up brackets, sorry. Should have caught this. Let's see if this clarifies what I'm trying to do.
I want to do a basic program that takes the variable "run" and runs the following code that number of times by using a For loop.
run = 3
def program(run):
for i in range(5):
print("The number is",i)
program(run)
What I want is to get is:
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
i.e. the "program" loops however many times I set "run" to equal.
Let's break the code and the error message down a bit:
for i in range[5]:
TypeError: 'type' object is not subscriptable
"Subscripting" is the way you access a particular element in a container, like a list or a dict. For example, to get the first (0th) element of a list called foo, you'd say foo[0], and to get the value associated with the key "bar" in a dictionary called foo, you'd say foo["bar"].
Note that when you just use the [] symbols by themselves (instead of putting them after some other identifier), they serve a different purpose: they construct a list. The expression [5] is a list that contains a single element (the number 5). To represent more elements, you comma-separate them, e.g. [0, 1, 2, 3, 4].
So what the error is telling you is that a type object can't be subscripted. Does that mean that range is a type? Yes! In Python, a range is a type of iterable object that represents a range of numbers. On its own, the word range in a Python program refers to the entire class of range objects (that is, a type of object), not a particular range object.
You construct a range the same way you construct most objects, by calling the type as a constructor function, with parameters in parentheses. For example, to construct a range with 5 numbers in it (0 to 4, similar to the list [0, 1, 2, 3, 4]) you can simply say range(5).
So to print all the numbers from 0 to 4 you can do:
for i in range(5):
print("The number is", i)
In your code, the run variable serves no purpose and can be removed completely.
Functions can take any number of parameters, or none at all, and since in this case your function doesn't do anything with the parameter you pass in, it can be simply:
def program():
for i in range(5):
print("The number is", i)
program()
If you wanted to make the length of the range variable, that would make sense as a parameter -- you just need to pass the parameter along to your range construction:
def program(num):
for i in range(num):
print("The number is", i)
runs = 3
for _ in range(runs):
program(5)
You'd use range, but you would use parenthesis to call the function instead of braces. I.e. range(5) instead of range[5]. Or you could use your run variable like range(run)
In short you are seeing the error because you are using square brackets and not parentheses range() is a function. Change it to
def program(run):
for i in range(5):
print("The number is",i)
program(run)
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
and it works fine.
If you want to the program to loop the same number of times as specified in run then you can do this:
run = 5
def program(run):
for i in range(run):
print("the number is",i)
program(run)
def program(n):
for i in range(0,n+1):
print("The number is",i)
program(5)
ouput
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Give this a try. Hopefully understood the assignment:
run = 3
def program(run):
nums = [f'The number is: {n}' for r in range(run) for n in range(5)]
print('\n'.join(nums))
program(run)
This uses list comprehension to loop twice which translates to:
run = 3
def program(run):
for r in range(run):
for n in range(5):
print(f'The number is: {n}')
program(run)
Or:
run = 3
def program():
for n in range(5):
print(f'The number is: {n}')
for r in range(run):
program()
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
Whelp, I finally figured it out - the reason I couldn't seem to find a solution anywhere to "could this be done and how would I go about it" is that in Python at least, a For statement cannot do this kind of loop, only a While can.
So my experiment of trying to do this via a For is a moot point, it's not something that can be coded without using While.
Thanks for the help.
I'm still a beginner so please bear with me. So I'm trying to get a list of factorial numbers from 1 to 5.
factorial=[]
for i in range(1,5):
for x in range(1,5):
while(i>x):
factorial.append(i*x)
When I switch out the factorial.append for print it just continously spits out 2s, does anyone know why, and if so what to do to fix this and what other viable method is there to get a list of factorial numbers?
I this case, I recommend you to use a recursive function:
def factorial(x):
if x == 1:
return 1
else:
return x*factorial(x-1)
Ex:
>>>factorial(5)
120
>>>factorial(10)
3628800
you can do something like :
>>> f=[1] # initialized your list
>>> for i in range(5): # take each value in the list [0,1,2,3,4]
... f.append(f[i]*(i+1)) #to create a next point multiply with the last value
...
>>> f=f[1:] #don't keep the first (repeated) point
>>> f #you have your list !
[1, 2, 6, 24, 120]
You're getting stuck in your while loop.
If you go step by step through your code, you'll see what is going on:
In the first loop, i value will be 1, and x values from 1 to 5, so i will never be > than x, thus you won't enter the while loop.
At the start of the second loop, i value will be 2 and x value will be 1, so you will enter the while loop.
You will stay in stay in the while loop until i becomes lower or equal to x, but this will never happen because to continue with the for loop you'll need to exit the while loop first.
Despite the error, i do not understand the reasoning that brought you there.
The common way to handle factorials is with recursion, as #Julio CamPlaz's answer shows, but it may simplier to understand the following:
# in each for loop, you multiply your n variable for the i value
# and you store the result of the moltiplication in your n variable
n=1
for i in range(1,6): # if you want the numbers from 1 to 5, you have to increase by one your maximum value
n = n*i
print n
I need to create an algorithm which would read user input of lists A and B and determine whether elements from list B occur in list A (if they occur, program needs to print 'Yes', and 'No' otherwise').
I have come up with the following code which should can be a starting point:
n=int(input('Enter the length of list A '))
A=[]
for i in range (0,n):
InpEl=int(input('Enter the elements '))
A.append(InpEl)
print(A)
n=int(input('Enter the length of list B '))
B=[]
for i in range (0,n):
InpEl2=int(input('Enter the elements '))
B.append(InpEl2)
print(B)
checklist=B
for each in A:
if each in checklist:
print('YES')
else:
print('NO')
Although in any case, I get 'No'. What is the mistake here?
Also, later I may need to modify the list so the program could determine if elements of B occur in A in the order they appear in B, but not necessarily consecutively.
For example, let M be the length of B and N be the length of A.
Then the program should return yes if there are indices i0, i1...im+1 such that 0<= i0 < i1...< im-1 < N such that A[i0] = B[0];A[i1] = B[1]...A[im-1] =
B[m-1].
Is there a simpler way to build the loop which would satisfy this kind of request?
P.S.: is it possible to make user input read not only integers, but strings? I am not sure if raw_input would be useful in Python 3.5.
P.S.S:
sorry, I made a minor mistake inputting the code here, I fixed it now.
Another question: I get the output of multiple yes' and no's for each element:
Enter the length of list A 3
Enter the elements 1
Enter the elements 2
Enter the elements 3
[1, 2, 3]
Enter the length of list B 3
Enter the elements 5
Enter the elements 4
Enter the elements 3
[5, 4, 3]
NO
NO
YES
How can I modify the code so it would print only one yes and no only once in case of any occurencies happen?
Here's one solution. Keep in mind there are many that have asked this type of question before and that best practice is to search around before asking.
a = input('enter list A with comma between each element: ')
b = input('enter list B with comma between each element: ')
a = a.split(',')
b = b.split(',')
contained_in_b = [element in b for element in a]
for i, in_b in enumerate(contained_in_b):
print('element {} contained in list B: {}'.format(a[i], in_b))
Better to take the raw input all together and use Python to split it into lists. This way, no need for the user to give the length of the list beforehand. Also, no need to convert to int - string comparisons work fine.
contained_in_b uses a list comprehension - a handy feature of Python that applies the boolean element in b to each element in a. Now you have a list of True/False values that you can enumerate through to print out the desired output.
One weapon you get is the all operator, which just checks that all of the items in the iterable are True:
A = [1, 4, 6, 8, 13]
B = [4, 6, 13, 8]
C = [3, 8, 25]
master = [i for i in range(20)]
print all(i in master for i in A)
print all(i in master for i in B)
print all(i in master for i in C)
Output:
True
True
False
To get the order as well, you'll need to drop back to an iterative method, stepping through the first list with a loop, while you maintain an index to know where you are in the second. For each value in the first list, go through the rest of the second list, until you either find the item (temporary success) or hit the end (failure).
Reading in number names and converting them to integers is a separate problem, and longer code.
So I'm a freshman comp sci major. I'm taking a class that teaches Python. This is my assignment:
Create a function that takes a string and a list as parameters. The string should contain the first ten letters of the alphabet and the list should contain the corresponding numbers for each letter. Zip the string and list into a list of tuples that pair each letter and number. The function should then print the number and corresponding letter respectively on separate lines. Hint: Use the zip function and a loop!
This is what I have so far:
def alpha(letter, number):
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
return zip(letter, number)
print alpha(letter, number)
The problem I have is an error on line 5 that says 'letter' is not defined. I feel like there should be a for loop but, I don't know how to incorporate it. Please help me.
zip works on iterables (strings and lists are both iterables), so you don't need a for loop to generate the pairs as zip is essentially doing that for loop for you. It looks like you want a for loop to print the pairs however.
Your code is a little bit confused, you'd generally want to define your variables outside of the function and make the function as generic as possible:
def alpha(letter, number):
for pair in zip(letter, number):
print pair[0], pair[1]
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
alpha(letter, number)
The error you are having is due to the scope of the variables. You are defining letter and number inside of the function, so when you call alpha(letter,number) they have not been defined.
For printing the result you could iterate the result of zip, as in the following example:
def alpha(letters, numbers):
for c,n in zip(letters,numbers):
print c,n
letters = "abcdefghij"
numbers = range(1,11)
alpha(letters, numbers)
Output:
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
I want to know if is it possible to change the value of the iterator in its for-loop?
For example I want to write a program to calculate prime factor of a number in the below way :
def primeFactors(number):
for i in range(2,number+1):
if (number%i==0)
print(i,end=',')
number=number/i
i=i-1 #to check that factor again!
My question : Is it possible to change the last two line in a way that when I change i and number in the if block, their value change in the for loop!
Update: Defining the iterator as a global variable, could help me? Why?
Short answer (like Daniel Roseman's): No
Long answer: No, but this does what you want:
def redo_range(start, end):
while start < end:
start += 1
redo = (yield start)
if redo:
start -= 2
redone_5 = False
r = redo_range(2, 10)
for i in r:
print(i)
if i == 5 and not redone_5:
r.send(True)
redone_5 = True
Output:
3
4
5
5
6
7
8
9
10
As you can see, 5 gets repeated. It used a generator function which allows the last value of the index variable to be repeated. There are simpler methods (while loops, list of values to check, etc.) but this one matches you code the closest.
No.
Python's for loop is like other languages' foreach loops. Your i variable is not a counter, it is the value of each element in a list, in this case the list of numbers between 2 and number+1. Even if you changed the value, that would not change what was the next element in that list.
The standard way of dealing with this is to completely exhaust the divisions by i in the body of the for loop itself:
def primeFactors(number):
for i in range(2,number+1):
while number % i == 0:
print(i, end=',')
number /= i
It's slightly more efficient to do the division and remainder in one step:
def primeFactors(number):
for i in range(2, number+1):
while True:
q, r = divmod(number, i)
if r != 0:
break
print(i, end=',')
number = q
The only way to change the next value yielded is to somehow tell the iterable what the next value to yield should be. With a lot of standard iterables, this isn't possible. however, you can do it with a specially coded generator:
def crazy_iter(iterable):
iterable = iter(iterable)
for item in iterable:
sent = yield item
if sent is not None:
yield None # Return value of `iterable.send(...)`
yield sent
num = 10
iterable = crazy_iter(range(2, 11))
for i in iterable:
if not num%i:
print i
num /= i
if i > 2:
iterable.send(i-1)
I would definitely not argue that this is easier to read than the equivalent while loop, but it does demonstrate sending stuff to a generator which may gain your team points at your next local programming trivia night.
It is not possible the way you are doing it. The for loop variable can be changed inside each loop iteration, like this:
for a in range (1, 6):
print a
a = a + 1
print a
print
The resulting output is:
1
2
2
3
3
4
4
5
5
6
It does get modified inside each for loop iteration.
The reason for the behavior displayed by Python's for loop is that, at the beginning of each iteration, the for loop variable is assinged the next unused value from the specified iterator. Therefore, whatever changes you make to the for loop variable get effectively destroyed at the beginning of each iteration.
To achieve what I think you may be needing, you should probably use a while loop, providing your own counter variable, your own increment code and any special case modifications for it you may need inside your loop. Example:
a = 1
while a <= 5:
print a
if a == 3:
a = a + 1
a = a + 1
print a
print
The resulting output is:
1
2
2
3
3
5
5
6
Yes, we can only if we dont change the reference of the object that we are using. If we can edit the number by accessing the reference of number variable, then what you asked is possible.
A simple example:
a=[1,2,3]
a=a+[4]==>here, a new object is created which plots to different address.
a+=[4]==>here , the same object is getting updated which give us the desired result.
number=10
list1=list(range(2,number+1))
# list1
for i in list1:
print(list1,i)
if (number%i==0):
print(i,end=',')
number=number//i #we can simply replace it with number//=i to edit the number without changing the reference or without creating a new object.
try:
[list1.pop() for i in range(10,0,-1) if(i>number)]
#here pop() method is working on the same object which list created by number refers. so, we can able to change the iterable in the forloop.
except:
continue
i=i-1 #to check that factor again!