Python provides a versatile set of tools for programming beginners. Mastering the basics, including comments, variables, math operators, and functions, sets the foundation for more advanced coding concepts. Keep exploring, practicing, and building to enhance your Python skills!
As the first part of our Introduction, we'll focus on the following learning path for our cheatsheets:
- Basic syntax and data types (integers, floats, and strings).
- Variables and assignements.
Let'sss go!
- 📝 Comments
- 📊 Variables
- ➕➖✖️➗ Math Operators
- 🔄 Augmented Assignment Operators
- 🦄 Walrus Operator
- 🎲 Data Types
- 🧬 Concatenation and Replication
- 🔄 Functions
- 🖨️ The print() Function
- 📥 The input() Function
- 📏 The len() Function
- 🏛 License
Comments in Python are used to explain code and make it more readable. They can be inline or multiline.
An inline comment is a comment on the same line as a statement. It is indicated by the #
symbol.
# This is an inline comment
result = 1 # initialization
Multiline comments are used for longer explanations. They start and end with three single quotes ('''
).
'''
This is a
multiline comment
'''
Comments can also be added to the end of a line of code.
result = 1 # initialization
In Python, variables are used to store data values. Variables are created when they are assigned a value.
- It can be only one word.
name = 'John'
# valid
full_name = 'John Doe'
# valid
- It can use only letters, numbers, and the underscore (
_
) character.
user_age = 25
# valid
user@age = 25
# invalid
- It can’t begin with a number.
var_23 = 'hello'
# valid
23_var = 'hello'
# invalid
- Variable names starting with an underscore (
_
) are considered as "unuseful".
_secret_code = '12345'
# valid
_ = 'This variable is not used'
# valid but discouraged
Math operators perform operations on numeric values. They include addition (+
), subtraction (-
), multiplication (*
), and division (/
).
The addition operator (+
) adds two numbers.
result = 2 + 3
# 5
The subtraction operator (-
) subtracts the right operand from the left operand.
result = 5 - 2
# 3
The multiplication operator (*
) multiplies two numbers.
result = 3 * 4
# 12
The division operator (/
) divides the left operand
by the right operand.
result = 8 / 2
# 4.0
Expressions can include multiple operators and operands. The order of operations is followed.
result = 2 + 3 * 6
# 20
result = (2 + 3) * 6
# 30
result = 2 ** 8
# 256
result = 23 // 7
# 3
result = 23 % 7
# 2
result = (5 - 1) * ((7 + 1) / (3 - 1))
# 16.0
a = 10
b = 3
sum_result = a + b
# 13
difference_result = a - b
# 7
product_result = a * b
# 30
division_result = a / b
# 3.333...
Augmented assignment operators combine an arithmetic operation with variable assignment. They perform the operation and assign the result to the variable.
Increment and decrement are common operations where a variable's value is increased or decreased by 1.
count = 0
count += 1 # Increment by 1
# count is now 1
total = 5
total *= 2 # Multiply by 2
# total is now 10
value = 10
value += 5
# value is now 15
value -= 3
# value is now 12
value *= 2
# value is now 24
value /= 3
# value is now 8.0
The Walrus Operator (:=
) allows assignment of variables within an expression while returning the value of the variable.
message := "Python Basics"
# 'Python Basics'
is_true = True
print(result := "Success") if is_true else print("Failure")
# Success
print(name := "John")
# John
The Walrus Operator, or Assignment Expression Operator, was firstly introduced in 2018 via PEP 572 and then officially released with Python 3.8 in October 2019.
Note
PEP 572 provides the syntax, semantics, and examples for the Walrus Operator.
Data types specify the type of values that variables can hold. In Python, the main data types are integers, floating-point numbers, and strings.
Integers are whole numbers without a fractional part.
integer_number = 42
negative_integer = -10
Floating-point numbers are numbers with a decimal point or in exponential form.
float_number = 3.14
negative_float = -0.5
Strings are sequences of characters, enclosed in single or double quotes.
text = 'Hello, Python!'
multiline_text = """This is a multiline
string in Python."""
String concatenation combines two strings, while string replication repeats a string multiple times.
result = 'Python' + ' Basics'
# 'Python Basics'
phrase = 'I love ' + 'Python! ' * 3
# 'I love Python! I love Python! I love Python! '
Functions are blocks of reusable code. They receive input, perform actions, and return output.
Functions are defined using the def
keyword, followed by the function name, parameters, and a colon.
def greet(name):
"""
This function greets the user.
"""
print(f"Hello, {name}!")
Functions are called by using the function name followed by parentheses and passing any required arguments.
greet('Alice')
# Hello, Alice!
The print()
function writes the value of the argument(s) it is given. It handles multiple arguments, floating-point quantities, and strings.
print('Greetings!', 'Welcome', 'to Python Basics!')
# Greetings! Welcome to Python Basics!
The end
keyword can be used to avoid the newline after the output or end the output with a different string.
phrase = ['printed', 'with', 'a', 'dash', 'in', 'between']
for word in phrase:
print(word, end='-')
# printed-with-a-dash-in-between-
The sep
keyword specifies how to separate objects if there is more than one.
print('cats', 'dogs', 'mice', sep=', ')
# cats, dogs, mice
The input()
function takes input from the user and converts it into a string.
name = input('What is your name? ')
print(f'Hi, {name}!')
fav_language = input('What is your favorite programming language? ')
print(f'Nice choice! {fav_language}')
The len()
function evaluates to the integer value of the number of characters in a string, list, dictionary, etc.
string_length = len('Python Basics')
# 13
list_length = len([1, 2, 3, 4, 5])
# 5
Note
Test of emptiness of strings, lists, dictionaries, etc., should not use len
as it prefers direct boolean evaluation.
my_list = [1, 2, 3]
# bad
if len(my_list) > 0:
print("This list is not an empty one!")
# good
if my_list:
print("This list is not an empty one!")
Although I am the owner of the examples provided (always taking into account previous examples that I got to know during my formation, of course), I would want to send some huge thanks to Olivia Redanz for her fantastic illustration! Oh, and remember that you can make the Dinosaur extremely happy if you...