Skip to content

Chapter 2

Jarlin Almanzar edited this page Oct 25, 2019 · 16 revisions

String commands

whitespace: \t creates a tab

newline: \n adds a new line in the string

Naming and Using Variables

Contain

  • Only letters
  • Only numbers
  • Only underscores
  • Can start with an underscore or letters, not numbers

Can't Contain

  • spaces
  • keywords
  • function names

Variables and Simple Data Types

Variables are labels for values variable_name = variable_value

Data Types

Strings

A series of characters

Anything inside "this" or 'this' is considered a string

" " allow for for quotes and apostrophes , while '' does not

f" " Allows us to insert a variable into a string, called f-strings

f being for format, b/c Python formats the string by replacing the name of any variable in brace

reverse a string name_of_str[::-1]

Variable String Example

#variable
message = "Hello World"
print(message)

Changing Case

# title() => changes each word to title case, where each word begins with a capital letter
message = "hello world"
print(message.title())
# upper() => changes each character to be capitalized 
# lower() => changes each character to be lower case
message = "hello world"
print(message.upper())
print(message.lower())

Variables in String

first_name = "Ava"
last_name = "Montecristo"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")

Remove White Space

favorite_language = 'Python ' 
print(favorite_language)
#strip spaces
#rstrip() => strips white spaces from right side
#lstrip() => strips white spaces from left side
#strip()  => strips white space from both sides
print(favorite_language.rstrip())

Numbers

Order of operation matters

  • add: 2+3
  • subtract: 3-2
  • multiply: 2*3
  • divide: 3/2
  • Exponential: 3**2 is the same as 3^2

Floats

.1 * .1 = .2
3 * .2 = 9.0

Underscore in numbers

Python ignores underscore when storing
universe_age = 14_000_000_000

Multiple Assignments

x, y, z = 0, 0, 0

Constants

A constant is a variable who values stay the same throughout the title and thus programmers treat all capitals letters as constants

Comments

The hash mark '#' indicates a comment, anything after the hash mark is ignored by the Python interpreter

The Zen of Python

import this