Nested loop in python3 - python-3.x

How does a nested loop work?
I tried to make a triangle this is my code:
x = 0
string = ""
while x <= 5:
y = x
while y > 0:
string = string + "*"
y = y - 1
string = string + "\n"
x = x + 1
print(string)
But it came out like this And this is the output:
*
**
***
****
*****
How does a nested loop work in python?

You must debug your code to understand how the nested loop works
for your code, the nested loop will work as following,
for each x where x= 5 the while loop of y will run for 5 times,
then again,
when x=4 the while loop of y will run for 4 times,
and as per this the while loop of x will have 5 iterations and the while loop of y will have about 15 iterations equivalent to number of stars in your pyramid or pattern.

Related

While Loop doesn't seem to iterate throug the whole list

Code is supposed to sum all numbers given by user input until only a single digit number remains.
Input 19991229 should result in 6, but I'm getting 33 instead, as if the two remaining numbers
aren't summed.
Here's the code:
b_d = input("enter birthdate")
digits = []
for d in b_d:
digits.append(int(d))
print(digits)
life = 0
while (sum(digits)) >= 10 :
for x in digits:
life += x
digits.remove(x)
print(life)
this resolves the issue, but it's too ad hoc and doesn't work on all cases:
r = 0
for y in str(life):
r += int(y)
print(y)

What is the meaning of "range( i + 1 )"?

I have a question ,what is the meaning of "range( i + 1 )" below ,if I want to show the output which has xyyzzz?
a = ("x", "y", "z")
for i in range(len(a)):
for j in range( i + 1):
print(a[i])
output: x
y
y
z
z
z
I tried to explain this to you with values
i = 0 ---> j = range(1) = 0 : a[0] = x
--------------------------------
i = 1 ----> j =range(2) = (0,1) : a[1] = y
: a[1] = y
-----------------------------------------
i = 2 ----> j = range(3) = (0,1,2) : a[2] = z
: a[2] = z
: a[2] = z
range(n) gives you values from 0 to n-1.
If you are unfamiliar with Python currently, this can be represented in different ways:
In mathematical interval notation, you can represent this as [0,n) . The left value is included, and the right one is excluded.
Taking len(a) to be 3, the above for loops would be written in C as:
for (int i = 0 ; i < 3 ; ++i){
for (int j = 0 ; j <= i ; ++j){ // note the <= . We can also do j < (i+1)
...
}
}
Your code first calculates len(a), which is 3, since this is a container with 3 elements (this specific container is called a tuple). The first for loop goes from 0 to 2, while the second for loop goes from 0 to wherever the counter of the outer for loop is at (less than or equal to). This causes the first value to be printed just once, next twice, and the last one thrice.
(If you want to test your understanding further, try to figure out what would be printed if we had print(a[j]) inside the loops rather than a[i].)
range() is a versatile and powerful thing in Python, it can do much more than just give you values from 0 to n-1. Do read about it if you intend to use Python.

Why isn't my for loop working, but my while loop is?

[Sorry in advance, I'm very new to programming.]
This is for project euler problem #2. The goal is to calculate the sum of all even fibonacci numbers that do not exceed 4 million. For anyone not familiar with fibonacci numbers, a fibonacci number is simply a number that is the sum of the two previous numbers in the sequence. For example, the first few fibonacci numbers are 1,2,3,5,8,13,21,34 ...
My code is below beginning with some variables, then my while loop, and finally my for loop.
n = 0
n2 = 1
fibsum = 0
fibrange = range(1,4000001)
while (n2 <= 4000000):
n2 = n2 + n
n = n2 - n
if n2 % 2 == 0:
fibsum += n2
print (fibsum)
# for n2 in fibrange:
# n2 = n2 + n
# n = n2 - n
# if n2 % 2 == 0:
# fibsum += n2
# print(fibsum)
As I said, my while loop works like a charm, but when I run the for loop the output of fibsum is 0. So the value is not changing at all.
I've tried range (1, 4000001) in place of fibrange. I really have no idea what else to try. This is like my 4th or 5th program ever.
Using for loop in range function, The Value of the variable n2 changes according only to range function.You cannot manually change the variable in for loop while using range function.
for and while and are different types of loops.
while: Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
for: Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
With while you can do something like this:
a = 0
b = 1
target = 4000000
result = 0
while a <= target:
if a % 2 == 0:
result +=a
a, b = b, a + b
print(result)
With for:
a, b = 0, 1
result = 0
target = 4000000
fib_sequence = 35 # -> the length of fibonacci sequence
for _ in range(fib_sequence):
if a % 2 == 0:
result +=a
a, b = b, a + b
if a >= target: break
print(result)

Visual Basic create loop for counting even numbers

The program requires input of positive numbers, and counts each even number using a loop function that doesn't count odds and ends if a O is input.
I'm not sure how to go about creating a loop or if I can use an if function within the loop.
Dim Count = 0
While (number mod 2 = 0) do
Count + 1 = Count
I actually didn't understand the question very well but as far as concerned, if you dont want odd numbers to be included I suggest on count add 2 not one , since the count variable starts with zero do:
Dim Count+2
Btw when do you want the count to stop? At 2 And goes back to 0?
If so then use the if statement
var Dim_count = 0;
if(Dim_count == 0){Dim_count+2}
else if(Dim_count ==2){Dim_Count =0;}
It would help if you provide a sample input so we can work with actual code and guide you to the right solution.
If you receive the input as, let's say, array of numbers, you can simply loop trough it using for or foreach and add additional condition to check for 0 if you want to preliminary exit:
For Each number As Integer In numbers
If (number mod 2 = 0) Then
Count = Count + 1
End If
If (number = 0) Then
Exit For
End If
Next
If you have existing code in which somehow number is reinitialized/redefined on each iteration already, then what you have is pretty close to what you need:
While (number <> 0)
If (number mod 2 = 0) Then
Count = Count + 1
End If
End While
Function counts even numbers:
REM function gets input, exits at 0 and adds positive even numbers.
DO
INPUT X
IF X = 0 THEN PRINT Y; " even numbers": END
IF X > 0 THEN
IF X / 2 = X \ 2 THEN Y = Y + 1
END IF
LOOP
I am completely unsure about this. just a guess...
Dim j as Integer
Dim i As integer
j = 0
i = 2
For i = 1 to 100
j = j+i
Print j
Loop
End Sub
Assuming you are getting numbers from some input, this is how you can do it. Have an infinite loop with While True, then for every number given from your input, check if its even using number mod 2 = 0. This will go on forever so you need to add some condition (another if statement) for it to stop the while loop. More information about while loops here: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/while-end-while-statement
Dim Count = 0
While True do
If (number mod 2 = 0) Then
Count + 1 = Count
End If
End While

Using a combination of IF, And in excel VBA

Im trying make a condition in excel VBA where there are two posible condition of variable x and y,
Say for example
Sub Test()
X = 6
Y = 11
If X < 3 Or X > 5 And Y < 10 Then
X = 10
Else
X = 11
End If
MsgBox X
End Sub
For the X term, when X<3 or X>5 seems work well however when i change the Y to any value greater than 10 say 11 then the result is 10 but supposed to be it should be 11. Can you please let me know if i missing something in my code so that when X<3 or X>5 and (y=11)>10 the result must be 11.
Regards,
Kenneth
This is an issue of operator precedence. In VB the order in Logical and Bitwise Operators is as follows:
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor)
The result is that and is executed before or in your condition, leading to the right side of the or being the whole expression X > 5 And Y < 10.
Your condition is executed like:
If X < 3 Or (X > 5 And Y < 10) Then
I believe what you actually want is the following (this should solve your issue):
If (X < 3 Or X > 5) And Y < 10 Then
Sources:
MSDN: Operator Precedence in Visual Basic
Consider:
Sub Test()
X = 6
Y = 11
If (X < 3 Or X > 5) And Y < 10 Then
X = 10
Else
X = 11
End If
MsgBox X
End Sub

Resources