Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
If / loops help
#1
Hi

I am going through the Python Crash Course book, and answering the questions in each chapter.

I'm stuck at one.

The question is:

1. Create a list of numbers from 1 - 9
2. Loop through the list and using if-elif-else the output should read "1st 2nd 3rd" etc with each result on the new line.

So I did this:

numbers_list = list(range(1,10))
print(numbers_list)

for number in numbers_list:
    if number == '1':
        print(f"{number}st")
I printed the list as soon as I created it to make sure that was ok, which it was.

I then created a for loop to go through each number. I tested '1' but that doesn't seem to work.

Any ideas?
Reply
#2
1, not '1'. '1' is a string, not a number. list(range(1,10)) makes a list of numbers.
Reply
#3
Also, you haven't handled 2nd, 3rd, and 4th-9th
Reply
#4
As you are trying to read the integer values stored on your "numbers_list" by a string value of "1" , so the if loop will fail always.

You can try , with 2 ways :

#One way
numbers = list(range(1,11))
#range(1,10) or range(1,11) based on your requirement
print(numbers)

for num in numbers:
    if(num==1):
        print(num)
    elif(num==2):
        print(num)
    else:
        if(num==3):
            print(num)
        else:
            continue


#Second way 
for num in numbers:
    if(num<=3):
        print(num)
    else:
        continue
buran write Dec-03-2020, 09:00 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#5
Just to mention that there is no need to add brackets around the condition (unless it's really necessary for precedence). if num <= 3: is just fine. Also no need to add redundant else: continue
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020