In this lesson, we will learn about...
Assignment: Giving a variable a value
a = 100
b = 1000.5
c = "Python"
These are words with special meaning in Python, and cannot be used as identifiers. They usually change color in your IDE / editor.
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help. False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass
Python allows you to assign values to multiple variables simulaneously.
d = e = 1
f,g,h = 2,3,"Programming"
Python has many built-in data types. We typically divide them into "primitives" and "non-primitives".
These data types are the fundamental building blocks of a language. Python's primitives include...
str
int
, float
, complex
bool
We'll learn about non-primitive data types in a later lesson.
this_is_a_string = "A String"
this_is_an_int = 5
this_is_a_float = 5.203
this_is_a_scientific_float = 1.5e6
this_is_complex = 5 + 3j
this_is_a_bool = True #(or False)
print(type(this_is_a_string))
print(type(this_is_an_int))
print(type(this_is_a_float))
print(type(this_is_a_scientific_float))
print(type(this_is_complex))
print(type(this_is_a_bool))
<class 'str'> <class 'int'> <class 'float'> <class 'float'> <class 'complex'> <class 'bool'>
int
+ float
yields a float
x = int(2.8)
y = float(3)
z = str(3)
w = int("7")
v = x + y
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
print(w)
print(type(w))
print(v)
print(type(v))
2 <class 'int'> 3.0 <class 'float'> 3 <class 'str'> 7 <class 'int'> 5.0 <class 'float'>
Strings represent a sequence of characters, and have some features we'll also see in the more complex data structures.
hello = "Hello, World!"
print(hello[1])
e
start
$\leq$ end
end
$-$ start
$=$ length of slicehello = "Hello, World!"
print(hello[2:5])
print(hello[:5])
print(hello[9:])
llo Hello rld!
You can also use negative numbers to index from the end of the string! The last character is index -1
.
hello = "Hello, World!"
print(hello[-5:-2])
orl
Use len()
to get the length of, or number of characters in, a string.
hello = "Hello, World!"
print(len(hello))
13
hello = "Hello, World!"
print(hello.upper())
print(hello.lower())
print(hello.replace("H", "J"))
print(hello.split(","))
print("world" in hello)
HELLO, WORLD! hello, world! Jello, World! ['Hello', ' World!'] False
You can concatenate two strings by adding them.
hello = "Hello, " + "World!"
print(hello)
Hello, World!
Use escape sequences to insert invisible or otherwise illegal characters in strings. These include...
Escape | Result |
---|---|
\' |
Single Quote |
\" |
Double Quote |
\n |
New Line |
\r |
Carriage Return |
\t |
Tab |
\b |
Backspace |
\\ |
Backslash |
hello = "He\"ll\"o,\tWor\nld\\!\b"
print(hello)
He"ll"o, Wor ld\!