start command line: $ python3
help: help()
exit: exit()
# single line comment
"""
multi-line comment
"""
print('this will be printed to the console')- Counting numbers, both positive and negative, are called integers. They have no decimal point.
- Integers are created by a literal number with no decimal point or through the use of the
int()constructor.
print(3) # => 3
print(int(19)) # => 19
print(int()) # => 0- The decimal numbers in Python are called floating point numbers.
- Floating point numbers are created using numbers with a decimal point, with the
float()constructor, or using scientific notation.
print(2.24) # => 2.24
print(2.) # => 2.0
print(float()) # => 0.0
print(27e-5) # => 0.00027- When once type of number is converted to another, the process used is called type casting. It is performed using built-in functions for each type.
# int -> float
print(17) # => 17
print(float(17)) # => 17.0
# float -> int
print(17.0) # => 17.0
print(int(17.0)) # => 17
# float || int -> string
print(str(17.0) + ' and ' + str(17)) # => 17.0 and 17+ |
addition |
- |
subtraction |
* |
multiplication |
/ |
division |
% |
modulo |
** |
exponent |
// |
integer division |
- Remember modulo
%gives the remainder that results from a division.- The
//operator gives the other part of that division. This is the equivalent to the floor of the answer.
- The
print(47 // 8) # => 5
print(47 % 8) # => 7"This is cool!"
'a1b2c3'"Tom shouted, "Go outside!""'Jodi asked, "What\'s up, Sam?"'print('''My instructions are very long so to make them
more readable in the code I am putting them on
more than one line. I can even include "quotes"
of any kind because they won't get confused with
the end of the string!''')print(len("Spaghetti")) # => 9print("Spaghetti"[4]) # => h
print("Spaghetti"[-4]) # => e- A range consists of a start value followed by a colon then an end value.
- Important: The series returned does not include the end value.
print("Spaghetti"[1:4]) # => pag
print("Spaghetti"[4:-1]) # => hett
print("Spaghetti"[4:4]) # => (empty string)- Omit the first number for the beginning of a string:
print("Spaghetti"[:4]) # => Spag print("Spaghetti"[:-1]) # => Spaghett
- Omit the second number for the end of a string:
print("Spaghetti"[1:]) # => paghetti print("Spaghetti"[-4:]) # => etti
-
- Calculate the first position of a character within a string using
index.
print("Spaghetti".index("h")) # => 4
- Calculate the first position of a character within a string using
-
- Find out how many times a substring appears in the primary string using
count. It returns zero if the substring is not there.
print("Spaghetti".count("t")) # => 2 print("Spaghetti".count("s")) # => 0
- Find out how many times a substring appears in the primary string using
- Addition operation
+stitches strings together
print("gold" + "fish") # => goldfish- Multiplication operation
*repeats string a given number of times
print("s"*5) # => sssssfirst_name = "Billy"
last_name = "Bob"
print('Your name is {0} {1}'.format(first_name, last_name)) # => Your name is Billy Bob- Use
fflag:
print(f'Your name is {first_name} {last_name}')| Value | Method | Result |
|---|---|---|
s = "Hello" |
s.upper() |
"HELLO" |
s = "Hello" |
s.lower() |
"hello" |
s = "Hello" |
s.islower() |
False |
s = "hello" |
s.islower() |
True |
s = "Hello" |
s.isupper() |
False |
s = "HELLO" |
s.isupper() |
True |
s = "Hello" |
s.startswith("He") |
True |
s = "Hello" |
s.endswith("lo") |
True |
s = "Hello World" |
s.split() |
["Hello", "World"] |
s = "i-am-a-dog" |
s.split("-") |
["i", "am", "a", "dog"] |
| Method | Purpose |
|---|---|
isalpha() |
returns True if the string consists only of letters and is not blank. |
isalnum() |
returns True if the string consists only of letters and numbers and is not blank. |
isdecimal() |
returns True if the string consists only of numeric characters and is not blank. |
isspace() |
returns True if the string consists only of spaces, tabs, and newlines and is not blank. |
istitle() |
returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters. |
- Python has no variable declaration keyword such as
let,varorconst. Instead, the assignment of a value automatically declares a variable.
a = 7
b = 'Marbles'
print(a) # => 7
print(b) # => Marbles- Python's replacement for
nullisNone. It is used to indicate a variable has no value.
my_var = None
print(my_var is None) # => TrueANY object can be tested for a truth value in an if statement or while loop even it is not a Boolean type
Python considers an object to be true (notice the lower case 't') UNLESS it is one of the following:
- constant:
NoneorFalse - zero of any numeric type: 0, 0.0
- empty sequence or collection
- string:
'' - list:
[] - tuple:
() - dictionary:
{} set()range(0)
- string:
| Python | JavaScript |
|---|---|
| and | && |
| or | || |
| not | ! |
# Logical AND
print(True and True) # => True
print(True and False) # => False
print(False and False) # => False
# Logical OR
print(True or True) # => True
print(True or False) # => True
print(False or False) # => False
# Logical NOT
print(not True) # => False
print(not False and True) # => True
print(not True or False) # => False| > | greater than |
| < | less than |
| >= | greater than or equal to |
| <= | less than or equal to |
| == | equal to |
| != | not equal to |
Python has a different way to handle strict comparisons:
is(strictly equal to)is not(not strictly equal to)
In Python, an if statement consists of the following:
- The
ifkeyword - A condition (that is, an expression that evaluates to
TrueorFalse) - A colon
- Starting on the next line, an indented block of code (called the
ifclause)
if name == 'Jeff':
print('Hi, Jeff.')An else statement doesn’t have a condition, and in code, an else statement always consists of the following:
- The
elsekeyword - A colon
- Starting on the next line, an indented block of code (called the
elseclause)
if name == 'Jeff':
print('Hi, Jeff.')
else:
print('Hello, stranger.')if name == 'Jeff':
print('Hi, Jeff.')
elif age < 21:
print('You are not Jeff, kiddo.')a while statement always consists of the following:
- The
whilekeyword - A condition (that is, an expression that evaluates to
TrueorFalse) - A colon
- Starting on the next line, an indented block of code (called the while clause)
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1If the execution reaches a break statement, it immediately exits the while loop’s clause.
spam = 0
while True:
print('Hello, world.')
spam = spam + 1
if spam >= 5:
breakWhen the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop and reevaluates the loop’s condition.
spam = 0
while True:
print('Hello, world.')
spam = spam + 1
if spam < 5:
continue
break- An error that occurs while a program is executing is called an exception.
- The process of detecting these execution errors is often referred to as catching exceptions.
a = 321
try:
print(len(a))
except:
print('Silently handle error here')
# Optionally include a correction to the issue
a = str(a)
print(len(a))Outputs:
Silently handle error here
3
