Python/Python Crash Course

Python Crash Course: 챕터 4

1june 2024. 6. 26. 15:09

Python Crash Course, 3rd Edition

 

  • Using a Loop 
  •  
  • Starts with for and indentation is followed with a tab for PEP 8. Don't forget the colon.
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
	print(f'They are all unqualified {magician}')
They are all unqualified alice
They are all unqualified david
They are all unqualified carolina

 

  • Making numerical lists
  • range() function generates a series of numbers
for value in range(1, 5):
 print(value)
1
2
3
4

Notice how the output never contains the end value, which would have been 5 in this case.

You can make a list of numbers using range() function and list() function.

numbers = list(range(1, 6))
print(numbers)
[1, 2, 3, 4, 5]

You can skip numbers in a given range by adding third arguement in range() function

numbers = list(range(2, 11, 2))
print(numbers)
[2, 4, 6, 8, 10]

 

  • Simple Statistics with a list of numbers
  • min() function - finds the smallest number
  • max() function - finds the largest number
  • sum() function - total sum of all numbers

 

  • List Comprehension using Loop
  • To use this syntax,
  • 1. Begin with a descriptive name for the list
  • 2. Define the expression for the values
  • 3. Write a loop to generate the numbers you want to feed into the expression
    *The colon is not needed for the loop in List Comprehension
squares = [value**2 for value in range(1, 11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  •  

 

  • Slicing a list
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
  • [1:4] can be interpreted as 'slice at index 1 and end it at index 4'
  • Because Python stops one item before the second index 
  •  
  • you would get  1,2,3
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:3])

[-3:3] can be interpreted as 'slice at negative index 3 and end it at index 3'

you would get 2

 

You can also add 'step' in slice to skip values in the list.

[:] is used to copy a list, enabling variables to have separate lists but values identical to each other.

 

  • Tuples
  • Tuples are immutable unlike lists.
  • Closed by ( ) brackets not  [ ] square brackets

 

    •  

'Python > Python Crash Course' 카테고리의 다른 글

Python Crash Course: 챕터 6  (0) 2024.06.28
Python Crash Course: 챕터 5  (0) 2024.06.27
Python Crash Course: 챕터 3  (0) 2024.06.25
Python Crash Course: 챕터 2  (0) 2024.06.23
Python Crash Course: 챕터 1  (0) 2024.06.19