+ 1

Python list

b = 5 list=“” while b<11: b = b + 2; if b%2 == 1 list=str(b)+” “ + list print (list) Please show me how to get to the output in steps. Thank you.

9th Dec 2018, 6:50 PM
Khk Gigi
Khk Gigi - avatar
13 odpowiedzi
+ 1
b = 5 # Sets Value of b to Integer 5 list=“” # Creates an emty String while b < 11: # This Loop will continue as long as the value b is smaller than 11 b = b + 2 # Adds 2 to b. With the first Iteration b is 7 if b % 2 == 1 # Checks if b is an odd Number list = str(b) + ” “ + list # Adds the current Value of b to the List if the Condition of the if-Statement is True print (list) # Output of the final List ---- By the Way this Program makes not much sence. It starts with an odd number and adds 2 - it is logical that this must be an odd Number, too.
9th Dec 2018, 8:47 PM
Sebastian Keßler
Sebastian Keßler - avatar
+ 1
Because you add str(b) + list. If you want an ascending Order write list = list + " " + str(b)
9th Dec 2018, 9:55 PM
Sebastian Keßler
Sebastian Keßler - avatar
+ 1
You can do it with a list comprehension print([b for b in range(7, 13, 2) if b%2])
10th Dec 2018, 3:15 AM
David Ashton
David Ashton - avatar
+ 1
Python will execute your Code exactly in the Order you write it down: list = list + str(b) means that 'b' will be appended to the existing 'list'. The result is a 'list' in ascending Order. list = str(b) + list means that the existing 'list' will be appended to 'b'. The Result is a List in descending Order.
10th Dec 2018, 3:28 AM
Sebastian Keßler
Sebastian Keßler - avatar
+ 1
list is the Name of the Stirng you defined in Line 2.
10th Dec 2018, 7:23 AM
Sebastian Keßler
Sebastian Keßler - avatar
9th Dec 2018, 8:03 PM
Sebastian Keßler
Sebastian Keßler - avatar
0
I know the answer. I just need to know the steps to it.
9th Dec 2018, 8:24 PM
Khk Gigi
Khk Gigi - avatar
0
Because I don’t understand how the output is the output
9th Dec 2018, 8:24 PM
Khk Gigi
Khk Gigi - avatar
0
Please show me steps to it.
9th Dec 2018, 8:24 PM
Khk Gigi
Khk Gigi - avatar
0
@Sebastian KeBler Thank you so much. But I’m confused about how it’s 11 9 7 and not 7 9 11. Why is it in reverse?
9th Dec 2018, 9:45 PM
Khk Gigi
Khk Gigi - avatar
0
So does it mean that “list” is nothing?
9th Dec 2018, 10:30 PM
Khk Gigi
Khk Gigi - avatar
0
What is list? I don’t know the value for list.
10th Dec 2018, 6:15 AM
Khk Gigi
Khk Gigi - avatar