Python Core 3.12
Python Core 3.12
12]
1. Basic Concepts
Printing Text
print("Hello World")
+ - Addition
- - Subtraction
* - Multiplication
/ - Reminder
% - Modulus
1. Escape Sequences
The backslash allows you to include special characters in strings.
quotes)
: Double quote (to include a double quote inside a string enclosed in double
\"
quotes)
2. Raw Strings
If you prefix a string with an r or R, the backslashes will not be treated as
escape characters, and you’ll get a raw string where backslashes are displayed
as they are.
3. Line Continuation
You can use a backslash at the end of a line to continue the statement on the
next line.
total = 10 + 20 + 30 + \
40 + 50 # Line continuation*
Newlines
Newlines will be automatically added for strings that are created using three
quotes.
print("""this
is a
multiline
text""")
Concatenation
Two or More Strings can be added using a process called Concatenation.
Even if strings contain numbers, they are still added as strings rather than
integers.
Variables
name_of_variable = value
You can use variables to perform corresponding operations, just as you did
with numbers and strings
In Python, variables don't have specific types, so you can assign a string to
a variable, and later assign an integer to the same variable.
Input
The input statement needs to be followed by parentheses. You can provide a
string to input() between the parentheses, producing a prompt message.
age = int(input())
print(age)
• += (Addition assignment)
• -= (Subtraction assignment)
• *= (Multiplication assignment)
• /= (Division assignment)
• %= (Modulus assignment)
The walrus operator was introduced in Python 3.8. It allows you to both assign
a value to a variable and return that value in a single expression. This is useful
for reducing redundancy and improving readability.
Syntax:
variable := expression
Example
3. Control Structures
Another type in Python is the Boolean type. There are two Boolean values:
True and False
There are many Comparison Operator, i.e
3. > (Greater than) : Returns True if the left operand is greater than the right.
4. < (Less than) : Returns True if the left operand is less than the right.
5. >= (Greater than or equal to) : Returns True if the left operand is greater
than or equal to the right.
6. <= (Less than or equal to) : Returns True if the left operand is less than or
equal to the right.
if expression:
statements
if 10 > 5:
print("10 greater than 5")
print("Program ended")
This means that the inner if statement is the statement part of the outer
one. This is one way to see whether multiple conditions are satisfied.
num = 12
if num > 5:
The if statement allows you to check a condition and run some statements,
if the condition is True
The else statement can be used to run some statements when the condition
of the if statement is False.
x = 4
if x == 5:
print("Yes")
else:
print("No")
Every if condition block can have only one else statement. In order to make
multiple checks, you can chain if and else statements.
num = 3
if num == 1:
print("One")
else:
if num == 2:
print("Two")
else:
if num == 3:
print("Three")
else:
print("Something else")
elif Statements
Multiple if/else statements make the code long and not very readable. The elif
(short for else if) statement is a shortcut to use when chaining if and else
statements, making the code shorter
1. and Operator
Example:
x = 5
y = 10
if x > 0 and y > 0:
print("Both numbers are positive.")
2. or Operator
• Takes two arguments
• Evaluates to True if either or both arguments are True
Example:
3. not Operator
• Takes one argument
• Inverts the value:
Example:
x = False
if not x:
print("x is False.")
You can combine and, or, and not to create complex conditions.
Example:
x = 5
y = -3
z = 0
if (x > 0 and y < 0) or not z:
print("Complex condition met!")
a = 7
b = 10
c = 7
These operators are essential for writing clear and concise conditional
statements in Python. Use them to control program flow effectively!
Lists
Lists are versatile data structures in Python used to store multiple items. They
are mutable, meaning their contents can be changed after creation.
Creating a List
A list is defined using square brackets [], with items separated by commas.
Lists can hold elements of any data type.
Example:
Example:
Empty Lists
Example:
empty_list = []
Adding a comma after the last item in a list is valid but optional.
Example:
Heterogeneous Lists
Lists can contain elements of different types, including other lists (nested lists).
Example:
number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1]) # Outputs: 0*
print(things[2]) # Outputs: [1, 2, 3]*
print(things[2][2]) # Outputs: 3 (accessing nested list)*
Nested Lists
Nested lists are often used to represent 2D structures like matrices or grids.
Example (Matrix):
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Strings as Lists
Strings can be indexed like lists. Each character, including spaces, is treated as
an element.
Example:
Out-of-Range Index
numbers = [1, 2, 3]
print(numbers[5]) # Raises IndexError: list index out of rang
Lists are powerful tools for managing collections of data. They allow flexibility
in operations like adding, removing, or modifying elements, and are commonly
used in Python programming!
List Operations
1. Reassigning Items in a List
You can change the value of a specific index in a list by assigning a new value
to it.
Example:
nums = [7, 7, 7, 7, 7]
nums[2] = 5 # Reassign the value at index 2
print(nums) # Outputs: [7, 7, 5, 7, 7]
nums = [1, 2, 3]
Lists and strings are similar in that both can be indexed and sliced.
However, unlike lists, strings are immutable (cannot be modified).
Example:
word = "Hello"
print(word[0]) # Outputs: H (first character)
Example:
nums = [1, 2, 3]
List Functions
Function/Method Description Example Result
Loops [Iterators]
1. While Loop
while Loops and Control Statements in Python
Example:
i = 1
while i <= 5:
print(i)
i = i + 1
print("Finished!")
Output:
1
2
3
4
5
Finished!
x = 1
while x < 10:
if x % 2 == 0:
print(str(x) + " is even")
else:
print(str(x) + " is odd")
x += 1
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
i = 0
while 1 == 1: # Infinite loop
print(i)
i = i + 1
if i >= 5:
print("Breaking")
Output:
0
1
2
3
4
Breaking
Finished
The continue statement skips the current iteration and goes back to the top of
the loop for the next iteration.
Example:
i = 0
while i < 5:
i += 1
if i == 3:
print("Skipping 3")
continue
print(i)
Output:
1
2
Skipping 3
4
5
5. Infinite Loops
A while loop with a condition that is always True creates an infinite loop.
Example: while True :
2. for Loop
The for loop is used to iterate over a given sequence, such as lists or strings.
The code below outputs each item in the list and adds an exclamation mark at
the end:
for x in str:
if(x == 't'):
count += 1
print(count)
Similar to while loops, the break and continue statements can be used
in for loops, to stop the loop or jump to the next iteration.
for vs while
Both, for and while loops can be used to execute a block of code for
multiple times.
It is common to use the for loop when the number of iterations is fixed. For
example, iterating over a fixed list of items in a shopping list.
The while loop is used in cases when the number of iterations is not known
and depends on some calculations and conditions in the code block of the
loop.
Both, for and while loops can be used to achieve the same results,
however, the for loop has cleaner and shorter syntax, making it a better
choice in most cases.
Ranges
1. Basic Usage
Generates numbers from 0 (default) to stop - 1:
print(list(range(5))) # [0, 1, 2, 3, 4]
3. Steps
Use a third argument for steps:
for i in range(3):
print("Hi!") # Prints "Hi!" 3 times*
6. More Types
7. Functional Programming
9. Regular Expressions