Module 1 Cheat Sheet: Python Basics
Package/Method Description Code Example
Comments are
lines of text that 1.1
are ignored by the
Comments 1.# This is a comment
Python interpreter
when executing
the code<./td>
Syntax:
1.1
1.concatenated_string =
string1 + string2
Combines
Concatenation (concatenates)
Example:
strings.
1.1
1.result = "Hello" + "
John"</td>
Data Types - Integer - Float - Example:
Boolean - String
1.1
2.2
3.3
4.4
5.5
6.6
7.7
8.8
9.9
10. 10
1.x=7
2.# Integer Value
3.y=12.4
4.# Float Value
5.is_valid = True
6.# Boolean Value
7.is_valid = False
8.# Boolean Value
9.F_Name = "John"
10. # String Value
Example:
1.1
Accesses
2.2
Indexing character at a
specific index. 1.my_string="Hello"
2.char = my_string[0]
Syntax:
1. len(string_name)
Returns the length Example:
len()
of a string.
1.1
2.2
1.my_string="Hello"
2.length = len(my_string)
Example:
1.1
2.2
Converts string to
lower() 1.my_string="Hello"
lowercase.
2.uppercase_text =
my_string.lower()
print() Prints the Example:
message or
variable inside 1.1
`()`. 2.2
1.print("Hello, world")
2.print(a+b)
- Addition (+): Example:
Adds two values
together. 1.1
- Subtraction (-): 2.2
Subtracts one 3.3
value from 4.4
another. 5.5
6.6
- Multiplication
7.7
(*): Multiplies
two values. 1.x = 9 y = 4
- Division (/): 2.result_add= x + y #
Divides one value Addition
Python Operators
by another, 3.result_sub= x - y #
returns a float. Subtraction
- Floor Division 4.result_mul= x * y #
(//): Divides one Multiplication
value by another, 5.result_div= x / y #
returns the Division
quotient as an 6.result_fdiv= x // y #
integer. Floor Division
- Modulo (%): 7.result_mod= x % y #
Returns the Modulo</td>
remainder after
division.
Example:
1.1
2.2
Replaces 1.my_string="Hello"
replace()
substrings. 2.new_text =
my_string.replace("Hello
", "Hi")
Slicing Extracts a portion Syntax:
of the string.
1.1
1.substring =
string_name[start:end]
Copied!
Example:
1.1
1.my_string="Hello"
substring =
my_string[0:5]
Example:
1.1
2.2
Splits string into a
split() list based on a 1.my_string="Hello"
delimiter. 2.split_text =
my_string.split(",")
Example:
1.1
2.2
Removes
strip() leading/trailing 1.my_string="Hello"
whitespace. 2.trimmed =
my_string.strip()
Example:
1.1
2.2
Converts string to
upper()
uppercase. 1.my_string="Hello"
2.uppercase_text =
my_string.upper()Copied!
Variable Assigns a value to Syntax:
Assignment a variable.
1.1
1.variable_name = value
Example:
1.1
2.2
1.name="John" # assigning
John to variable name
2.x = 5 # assigning 5 to
variable x