adding 2 integers from a list in python - python

im doing this exercise basically to add the first 2 integers in a list in python, but my script shows it runs the for loop twice before it iterates to the next integer in a list.
my code is below, i added a print statement so i can see how it iterates the FOR loop inside a WHILE loop.
def add2(nums):
count = 0
ans = 0
while count <= 2:
count += 1
print(f'count: {count}')
for x in nums:
ans += x
print(f'ans: {ans}')
HOwever if i run my code, i get this result. Why is it adding the value of ans twice before it goes to the next iteration?
add2([2,3,5])
count: 1
ans: 2
ans: 5
ans: 10
count: 2
ans: 12
ans: 15
ans: 20
count: 3
ans: 22
ans: 25
ans: 30

You don't need to overcomplicate this. Just use slicing to return the first to elements of the list.
simpler code
listNums = [1,2,3,4]
print(float(listNums[0])+float(listNums[1]))
output
3.0
This is based on your explanation of the problem.
Now using your logic of solving this proble, I would consider removing the while loop altogether but keeping the for loop. Though keeping the plain for loop will not give us our desired output because it will find the sum of every number in the list. Instead we can cut the list of at two elements. The below code shows how to do that.
your logic code
def add2(nums):
count = 0
ans = 0
for x in nums[:2]:
ans += x
print(f'ans: {ans}')
add2([1,2,3,4])
output
ans: 3

It could be as simple as this:
ans=0
for i in range(len(nums)):
ans+=nums[i]
if i > 2:
break

Related

While loop keeps going back to end condition

I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:
def print_evens(numbers):
"""Prints all even numbers in the list
"""
length = len(numbers)
i = 0
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
print_evens([1, 2, 3, 4, 5, 6])
I'm not sure why but the loop doesn't go past the end condition and just keeps cycling back and forth. I feel I'm missing something very simple.
If I had to guess where the problem lies, I'd say it's with the if statement, though I'm not sure what would be wrong about it.
The problem is that when you start with 1 the variable i never get updated, because it's not even. So the solution is to increment the i every time without a condition:
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
If you don't want to bother with indexes you can loop directly on the list items.
def print_evens(numbers):
"""Prints all even numbers in the list
"""
for n in numbers:
if n % 2 == 0:
print(n)

(Beginner) Why is this not correct?

#Add the input number 4 times. Ex. 3+3+3+3
#If the input is 3, the output will be 12
num = int(input("Num: "))
for x in range(2):
num += num
print(num)
Using an app called "Easy Coder" and
for some reason, the code above is not correct.
Is there a better way to do this? so the actual process of the code is("3+3+3+3) and not(3+3) + (3+3)
Edit: Sorry, I forgot to mention, that this is an exercise related to
looping.
The task:
Write a program that uses a for loop to calculate any
number X 4.
Hint - Add the number to a variable 4 times.
To add 4 times, use a separate variable for the total and loop 4 times instead of twice
num = int(input("Num: "))
total = 0
for _ in range(4):
total += num
print(total)
You can always create another variable to store the total, or you could simply multiply the number initially by 4 instead of using a loop. Otherwise, like you said, your code is actually doing:
3 + 3 = 6
6 + 6 = 12
since you overwrite the initially supplied number.

Finding duplicates in an array using while loop, and add the sum of the duplicate elements

I used the for loop code found on the internet but my professor asked me to convert it to while loop. I also don't have any idea how to code the sum part. We can't use any advanced stuff like def. I only started to code for class using python and I've honestly been stuck and haven't been catching up on the lessons. Any help is appreciated, thank you.
import array as arr
a=arr.array('i', [])
x=0
#size of array
arrsize=int(input("\nPlease Enter the number of elements: "))
#elements
print("\nPlease Enter "+str(arrsize)+" elements")
while(x<arrsize):
num=int(input("Enter a number: "))
a.insert(x,num)
x+=1
print("The elements are: ",a)
#duplicate elements
for i in range (0, len(a)):
for j in range (i+1, len(a)):
if(a[i]==a[j]):
print("\nThe duplicate elements are: ",(a[j]))
The statement
for i in range(x, y):
# Code to loop through here
Is essentially saying that you will loop through the loop code one time for every number i between x and y, including x and excluding y.
We can write an equivalent statement with a "while" loop. But we'll need to manage the variable i separately (including initializing it and incrementing it manually)
i = x
while i < y:
# Code to loop through here
i += 1
Now that you know how these 2 loop types are equivalent, you can use this equivalency to translate your code from a for loop to a while loop. You will need to do it twice; once for each for-loop in your code. I definitely recommend doing this on your own as it's an important part of the learning process!
The concept is the same as for the for-loop ,only difference will be increasing the indexes manually since while is used for condition based loops.
sum = 0 #to add each duplicates value
dup=[] #store each duplicate if needed
# increase the values of i,j manually
i = 0
while(i< len(a)):
j=i+1
while(j<len(a)):
if(a[i]==a[j]):
#if duplicate found then add
sum = sum + a[i]
dup.append(a[i])
j=j+1
i=i+1
print("\nThe duplicate elements are: ",dup)
print("Sum of of the duplicates :" , sum)
You don't have to import any modules, Python's builtin list is sufficient for your application. Start with an empty duplicates list, dup_sum = 0, and go through all elements of your array; if some element is not in duplicates and its count is greater than 1, insert it into duplicates and add the sum of occurrences to dup_sum. Finally, print the info. you want.
a = []
x = 0
# size of array
arrsize = int(input('Please Enter the number of elements: '))
# elements
print(f'Please Enter {arrsize} elements')
while x < arrsize:
num = int(input('Enter a number: '))
a.append(num)
x += 1
print(f'The elements are: {a}')
# duplicate elements
duplicates = []
dup_sum = 0
i = 0
while i < len(a):
d = a[i]
if d not in duplicates:
dcount = a.count(d)
if dcount > 1:
dup_sum += d * dcount
duplicates.append(d)
i += 1
print(f'The duplicate elements are {duplicates}')
print(f'Sum of duplicates = {dup_sum}')
Here is a sample run of the program:
Please Enter the number of elements: 5
Please Enter 5 elements
Enter a number: 1
Enter a number: 2
Enter a number: 2
Enter a number: 3
Enter a number: 3
The elements are: [1, 2, 2, 3, 3]
The duplicate elements are [2, 3]
Sum of duplicates = 10

Using for/while loops and range() to list values

I am stuck with 2 ways of how to use for and while loops in listing values to empty lists.
Example 1.
Creating a function that takes in user's input and lists positive decimal values in a list UNTIL user inserts negative value. Then listing ends and the last value should be this negative value. How the output should look like:
Add a number to the list:
1.5
Add a number to the list:
5.2
Add a number to the list:
6
Add a number to the list:
-2
The list: [1.5, 5.2, 6.0, -2.0]
My tryout that didn't work out
list = []
positive = float(input("Add number to put it in list:"))
while positive > 0:
list.append(positive)
else:
print(list)
Example 2
Another problem about using for loop and range() together: How to list first 20 even numbers starting from number 2. At the end of function print out the list with 20 values.
My tryout that didn't work out
emptylist = []
for days in range(40):
if days % 2 == 0:
print(emptylist)
Thanks already in advance to help me solve these applications! :)
You need to ask for the user input inside the loop
numbers = []
num = 1
while num > 0:
num = float(input("Add number to put it in list:"))
numbers.append(num)
else:
print(numbers)
As a side note, don't use list as a variable, it's a built-in name.
You must replace your while with an if else
positive=1
list = []
while(positive):
positive = float(input("Add number to put it in list:"))
if positive > 0:
list.append(positive)
else:
print(list)
Answer for part-I:
output_list = []
isPositive=True
while(isPositive):
num = float(input())
if (num > 0):
output_list.append(num)
else:
isPositive=False
output_list.append(num)
break
print (output_list)
Answer for part-II:
>>> n=20
>>> for num in range(2,n*2+1,2):
... print(num)
...
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40

While Loops - Increment a List

I'm stuck trying to figure out this while loop. It seemed simple at first but I keep running into errors. I think I just haven't used python in a while so it's hard to get back into the gist of things.
Write a while loop that will add 100 numbers to a list, starting from the number 100 and incrementing by 2 each time. For example, start from 100, then the next number added will be 102, then 104 and so on.
I have this so far;
count = 0
while count < 99:
count += 1
numbers.append(len(numbers)+2)
for x in numbers:
print(x)
But that is simply giving me 0-100 printed out when I want it to be 2,4,6,8,10,...
numbers = []
index = 0
number = 100
while index < 100:
number += 2
index += 1
numbers.append(number)
for x in numbers:
print(x)
With a few modifications, and using a while loop as per your exercise:
numbers = []
count = 0
while count < 100:
numbers.append(100 + (2*count))
count += 1
for x in numbers:
print(x)
Or with a for loop:
numbers = []
for i in range(100):
numbers.append(100 + (2*i))
for x in numbers:
print(x)
Or as a list comprehension:
numbers.extend([(100 + (2*el)) for el in range(100)])
Or as a recursion:
numbers = []
def rec(num):
if num < 100:
numbers.append(100 + (2*num))
rec(num + 1)
rec(0)
Something like this:
numbers = []
while len(numbers) != 100:
if len(numbers) > 0:
numbers.append(numbers[-1] + 2)
else:
numbers.append(100)
Little explanation:
You loop until your list has 100 elements. If list is empty (which will be at the beginning), add first number (100, in our case). After that, just add last number in list increased by 2.
Try numbers.extend(range(100, 300, 2)). It's a much shorter way to do exactly what you're looking for.
Edit: For the people downvoting, can you at least leave a comment? My initial response was prior to the question being clarified (that a while loop was required). I'm giving the pythonic way of doing it, as I was unaware of the requirement.

Categories