0% found this document useful (0 votes)
32 views20 pages

Python Core 3.12

Uploaded by

Code MSEC
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views20 pages

Python Core 3.12

Uploaded by

Code MSEC
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python Core [3.

12]

High Level Programming Language

1. Basic Concepts
Printing Text
print("Hello World")

The output text should be enclosed in Single or double quotes.


We can carry out Arithmetic operations directly in print statement
Arithmetic operations in Python follows BODMAS rule in Mathematics.

+ - Addition

- - Subtraction

* - Multiplication

/ - Reminder

% - Modulus

Python Core [3.12] 1


Floats are used in Python to represent numbers that aren't integers (whole
numbers).
Python also supports exponentiation, which is represented as **

2. Strings & Variables


String is a sequence of characters
It is created by entering text between two single or double quotation marks.
The delimiter ( " or ' ) used for a string doesn't affect how it behaves in any
way.
In Python, a backslash (\) is a special character used as an escape character.
It is often used to insert characters that are otherwise difficult or impossible to
include in a string, such as newline characters, tabs, or quotes.

1. Escape Sequences
The backslash allows you to include special characters in strings.

\n : Newline (moves the cursor to the next line)

\t : Tab (inserts a tab space)


: Single quote (to include a single quote inside a string enclosed in single
\'

quotes)

: Double quote (to include a double quote inside a string enclosed in double
\"

quotes)

\\ : Backslash (to include an actual backslash character)

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.

Python Core [3.12] 2


Example:

total = 10 + 20 + 30 + \

40 + 50 # Line continuation*

print(total) # Outputs: 150*

Newlines
Newlines will be automatically added for strings that are created using three
quotes.

print("""this
is a
multiline
text""")

We can also use /n in-order to have Newlines in String.

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.

print("Hello" + " World" + "!"). #=> Hello World!

Strings can also be multiplied by integers. This produces a repeated version of


the original string

print("Hello " * 3). #=> Hello Hello Hello

Strings can't be multiplied by other strings.


Strings also can't be multiplied by floats, even if the floats are whole numbers.

Variables

Python Core [3.12] 3


A variable allows you to store a value by assigning it to a name, which can be
used to refer to the value later in the program.

To assign a variable, use one equals sign.

name_of_variable = value

Certain restrictions apply in regard to the characters that may be used in


Python variable names. The only characters that are allowed
are letters, numbers, and underscores. Also, they can't start with
numbers.

You can use variables to perform corresponding operations, just as you did
with numbers and strings

Variables can be reassigned as many times as you want, in order to change


their value.

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.

name = input("Enter your name: ")

print("Hello, " + name)

By default, the inputed value will be considered as String.

To convert it to a number, we can use the int() function:

age = int(input())
print(age)

imilarly, in order to convert a number to a string, the str() function is used.


This can be useful if you need to use a number in string concatenation.

Python Core [3.12] 4


In-Place and Walrus Operators
In-place operators allow you to perform operations that modify an object and
then assign the result back to the object itself, typically saving memory and
improving performance. They perform an operation and reassign the result to
the variable. These are also called augmented assignment operators.

Examples of In-Place Operators:

• += (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

print( "Youre Name is "+ (name:=input("Whats Your Name?")))


print("Good Morning, "+ name)

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

Python Core [3.12] 5


1. == (Equal to) : Returns True if both operands are equal.

2. != (Not equal to) : Returns True if operands are not equal.

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 and else Statements [Selectors]


we can use if if certain condition holds true, the the statements will work

if expression:
statements

If an expression evaluates to True , some statements are carried out.


Otherwise, they aren't carried out.

Python uses indentation, which is like curly braces in other programming


language.

Example for if statements

if 10 > 5:
print("10 greater than 5")

print("Program ended")

To perform more complex checks, if statements can be nested, one inside


the other.

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:

Python Core [3.12] 6


print("Bigger than 5")
if num <=47:
print("Between 5 and 47")

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

Python Core [3.12] 7


num = 3
if num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
print("Three")
else:
print("Something else")

Boolean Logic in Python


Boolean logic allows you to create complex conditions for if statements by
combining multiple conditions. Python provides three main Boolean operators:
and, or, and not.

1. and Operator

• Takes two arguments


• Evaluates to True only if both arguments are True
• Returns False if either or both arguments are False

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

• Returns False only if both arguments are False

Example:

Python Core [3.12] 8


x = -5
y = 10
if x > 0 or y > 0:
print("At least one number is positive.")

3. not Operator
• Takes one argument
• Inverts the value:

• not True becomes False


• not False becomes True

Example:

x = False
if not x:
print("x is False.")

Combining Boolean Operators

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!")

Boolean Logic with Variables

• You can use Boolean logic to compare variables as well as values.


Example:

a = 7
b = 10
c = 7

Python Core [3.12] 9


if a == c and b > a:
print("a equals c, and b is greater than a.")

Operator precedence is a very important concept in programming. It is an


extension of the mathematical idea of order of operations (multiplication
being performed before addition, etc.) to include other operators, such as
those in Boolean logic.

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:

words = ["Hello", "world", "!"] # A list with three string i

Accessing List Items

List elements are accessed using indices. Indexing starts at 0.

Use square brackets [index] to retrieve an item.

Example:

words = ["Hello", "world", "!"]


print(words[0]) # Outputs: Hello*
print(words[1]) # Outputs: world*
print(words[2]) *# Outputs: !*

Empty Lists

Python Core [3.12] 10


You can create an empty list to populate later, often useful for dynamic
operations.

Example:

empty_list = []

print(empty_list) *# Outputs: []*

Lists with Trailing Commas

Adding a comma after the last item in a list is valid but optional.
Example:

numbers = [1, 2, 3,]

print(numbers) *# Outputs: [1, 2, 3]*

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]
]

Python Core [3.12] 11


print(matrix[1]) # Outputs: [4, 5, 6]*
print(matrix[1][2]) # Outputs: 6 (second row, third column

Strings as Lists

Strings can be indexed like lists. Each character, including spaces, is treated as
an element.
Example:

text = "Hello world!"


print(text[6]) # Outputs: w*

Out-of-Range Index

Attempting to access an index that doesn’t exist raises an IndexError.


Example:

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]

Python Core [3.12] 12


2. Adding and Multiplying Lists
Addition (+): Combines two lists into one (concatenation).
Multiplication (*): Repeats the list elements a specified number of times.
Example:

nums = [1, 2, 3]

print(nums + [4, 5, 6]) # Outputs: [1, 2, 3, 4, 5, 6] (conca

print(nums * 3) # Outputs: [1, 2, 3, 1, 2, 3, 1, 2, 3

3. Similarities Between Lists and Strings

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)

4. Membership Checks Using in


The in operator checks whether an item exists in a list.
Returns True if the item is found, False otherwise.

Example:

words = ["spam", "egg", "spam", "sausage"]

print("spam" in words) # Outputs: True


print("egg" in words) # Outputs: True
print("tomato" in words) # Outputs: False

The in operator can also check if a string is a substring of another string.

Python Core [3.12] 13


Example:

sentence = "Hello world"

print("world" in sentence) # Outputs: True


print("python" in sentence) # Outputs: False

5. Checking for Non-Membership


Use not in or not with in to check if an item is not in a list.
Examples:

nums = [1, 2, 3]

print(4 not in nums) # Outputs: True (4 is not in the li


print(not 4 in nums) # Outputs: True (equivalent to the a
print(3 not in nums) # Outputs: False (3 is in the list)
print(not 3 in nums) # Outputs: False (equivalent to the

List Functions
Function/Method Description Example Result

Adds an item to the end


list.append(item) [1, 2].append(3) [1, 2, 3]
of the list
list.insert(index, Inserts an item at a
item) [1, 3].insert(1, 2) [1, 2, 3]
specific index

Returns the number of


len(list) len([1, 2, 3]) 3
items in the list

Returns the index of the


list.index(item) first occurrence of the [1, 2, 3].index(2) 1
item

Returns the maximum


max(list) max([1, 2, 3]) 3
value in the list

Returns the minimum


min(list) min([1, 2, 3]) 1
value in the list

Counts occurrences of an [1, 2, 2,


list.count(item) 2
item 3].count(2)

Python Core [3.12] 14


Removes the first [1, 2,
list.remove(item) [1, 3]
occurrence of the item 3].remove(2)

Reverses the order of [1, 2,


list.reverse() [3, 2, 1]
items in the list 3].reverse()

Loops [Iterators]
1. While Loop
while Loops and Control Statements in Python

The while loop in Python allows code to be executed repeatedly as long as a


specified condition is True. It is especially useful when the number of iterations
is not known in advance.
1. Basic while Loop
A while loop executes a block of code repeatedly as long as its condition is
True.

Example:

i = 1

while i <= 5:
print(i)
i = i + 1

print("Finished!")

Output:

1
2
3
4
5
Finished!

2. Using Multiple Statements in while

Python Core [3.12] 15


You can include other control structures (like if/else) within a while loop.
Example: Even and odd number classification.

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

3. Breaking Out of a Loop: break


The break statement exits the loop immediately, even if the condition is still
True.

It is often used to stop infinite loops when a specific condition is met.


Example:

i = 0
while 1 == 1: # Infinite loop
print(i)
i = i + 1
if i >= 5:
print("Breaking")

Python Core [3.12] 16


break
print("Finished")

Output:

0
1
2
3
4
Breaking
Finished

4. Skipping Iterations: continue

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 :

Python Core [3.12] 17


These loops can be stopped manually (e.g., pressing Ctrl+C in the console) or
by using the break statement.

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:

words = ["hello", "world", "spam", "eggs"]


for word in words:
print(word + "!")

The for loop can be used to iterate over strings.

str = "testing for loops"


count = 0

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.

Python Core [3.12] 18


For example, ending the loop when the user enters a specific input in a
calculator program.

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]

2. Start and Stop


Specify start and stop:

print(list(range(3, 7))) # [3, 4, 5, 6]

3. Steps
Use a third argument for steps:

print(list(range(2, 10, 2))) # [2, 4, 6, 8]


print(list(range(10, 2, -2))) # [10, 8, 6, 4]

4. With for Loops


Iterate with range:

for i in range(3):
print("Hi!") # Prints "Hi!" 3 times*

range(start, stop, step) efficiently generates sequences for iterations.

Python Core [3.12] 19


4. Functions & Modules

5. Exceptions & Files

6. More Types

7. Functional Programming

8. Object Oriented Programming

9. Regular Expressions

10. Pythonicness & Packaging

Python Core [3.12] 20

You might also like