002-3. Iteration statement focusing on "for" with randomly generated numbers
@ # I use random module import random # starting, ending, inc and dec print(random.randrange(10)) print(random.randrange(10, 20)) # Make one random number out of even numbers between 10 and 20 print(random.randrange(10, 20, 2)) # Random number is much used in sampling for i in range(5): print(random.randrange(10), end=' ') # i can be removed because it's not used # But it makes error for in range(5): print(random.randrange(10), end=' ') # But since I still don't need i, I can make meaning of i weak # "_" is called "placeholder" for _ in range(5): print(random.randrange(10), end=' ') for _ in range(5): # placeholder is variable or not? Just check it out print(_) # It turns out no error, so it's variable, you can use _ as variable # But you don't need to use _ as variable # _ is used not to use useless variable i print(random.randrange(10), end=' ') # When you do programming with random value, # you can have cases when you don't want created random value to change # To fix random value, you can use seed() which is much used # But don't put seed() into inside of "for" random.seed(1) for _ in range(5): print(random.randrange(10), end=' ') print() # Random number generating method # This is used as global variable next = 1 def rand(): # If you want to use global variable inside of method, you use global keyword # Even if this syntax doesn't make error but this syntax must not be used global next # Following way to generate random value is called pseudo(fake) random number # Following code generates different random values next = next * 1103515245 + 12345 return int((next//65536) % 32768) # Quiz # Make method which can find the largest number out of 10 random numbers # which are all smaller than 100 def maxNumber(): # Since I should find the largest number, # I should create variable space to hold found number # with initializing by 0 m = 0 # Since quize specified 10 numbers, we can loop 10 times for _ in range(10): # I generate 100 random numbers n = random.randrange(100) print(n, end=' ') # And I compare generated random number to m if m < n: m = n return m # I refactor this method to make it general def maxNumber(): m = -random.randrange(100) print(m, end=' ') for _ in range(10-1): n = -random.randrange(100) print(n, end=' ') if m < n: m = n return m print(maxNumber()) print('-'*50) s1, s2 = sumOfOddEven() print(s1, s2) sum = sumOfOddEven() print(sum)