Python/Python Crash Course

Python Crash Course: 챕터 2

1june 2024. 6. 23. 17:36

Python Crash Course, 3rd Edition

 

  • Variables

Every variable is connected to a value, which is the information associated
with that variable

message = "Hello Python world!"
print(message)

In this case the value is the "Hello Python world!" text.

Variables in Python are commonly likened to boxes for storing values, which can be a useful analogy initially. However, a more accurate representation is to view variables as labels that are assigned to values or as references to specific values. 

 

 

  • String 

A string is a sequence of characters enclosed in single (' ') or double (" ") quotes. It is used to classify the data. / 's'

Changing a case in strings:

name = "cucumber olsen"
print(name.title())
print(name.upper())
print(name.lower())
Cucumber Olsen
CUCUMBER OLSEN
cucumber olsen

A method is an action applied to data, indicated by a dot (.) after the variable name, such as name.title() Methods are followed by parentheses, which can contain additional information needed for their operation; for instance, title() here requires no additional information, hence its empty parentheses.

 

  • f- string:

f-string is used to insert one or more variables within string:

Fruit = "Apple"
Color = "Green"

print(f'{Fruit} is {Color}')
Apple is Green

Start with f to use f-string, { } braces are needed to enclose the variable 

 

  • Whitespace 

Whitespace refers to any nonprinting characters, such as spacestabs, and end-of-line symbols. It is used to organize and write clean code

Examples:

tab: \t 
tab gives 4 spaces to the right
new line: \n 

to remove whitespaces
left space removal: .lstrip()
right space removal: .rstrip()
strip all spaces: .strip()

 

  • Miscellaneous 

Use underscore to write numbers with multiple digits. For example 300,000 is written as 300_000

You can remove prefix and suffix, its parentheses specified, using: .removeprefix() / .removesuffix() 

Multiple assignment to variables can be given in a single line of code using commas:

x, y, z = 1, 2, 3
x, y, z = 'a', 'b', 'c'

value 1 is given to variable x, 2 to y and 3 to z respectively.