Trying to understand Python loop using underscore and input

One more tip - if someone is learning Python on HackerRank, he knows that this is very important to get started.

I am trying to understand this code:

    stamps = set()
    for _ in range(int(input())):
        print('underscore is', _)
        stamps.add(raw_input().strip())
        print(stamps)

Output:

    >>>2 
    underscore is 0
    >>>first
    set(['first'])
    underscore is 1
    >>>second
    set(['second', 'first'])
  1. I set 2 as the first raw input. How does a function know that I loop only twice? This is confusing to me because it is not typical ... for i in the xrange (0,2) structure.

  2. At first, I thought the underline repeated the last command in the shell. So I added print statements to the code to see the underscore value ... but the values ​​just show 0 and 1 as a typical loop structure.

I already read this post and still can’t figure out which of these three uses of underlining is used.

What is the purpose of a single underscore "_"? variable in python?

Python, !

+6
4

ncoghlan answer 3 _ Python:

  • . CPython .
  • i18n ( C , ), :

    raise forms.ValidationError(_("Please enter a correct username"))`
    
  • "throwaway", , , :

     label, has_label, _ = text.partition(':')
    

, . , (case 3), .

Python _ , - . , :

 for _ in range(10):
     print("Hello world")

_ , , 10 .

,

 for i in range(10):
     do_something(i)

, , i, j _.

+14

.

+1

, , - - , , .

    for _ in range(int(raw_input())):
        print raw_input()

:

    2
    Dog
    Cat

:

    # no output despite entering 2, but 2 is set as range - loops 2 times
    Dog
    Cat

- , int() for?

2, int() . , , "Dog" int() . .

+1

stamps = set()
for _ in range(int(raw_input())):
    print 'underscore is', _
    stamps.add(raw_input().strip())
    print stamps

:

how_many_loops = int(raw_input()) # asked only once.
stamps = set()
for i in range(how_many_loops):
    print 'loop count is', i
    stamps.add(raw_input().strip())
    print stamps

Because everything that you enter in range()must be calculated before the start of the cycle, so the first one is int(raw_input())requested only once. If you use something like for i in range(very_expensive_list)this, it will take a long time, then start the loop.

0
source

Source: https://habr.com/ru/post/1652741/


All Articles