0% found this document useful (0 votes)
8 views

PYTHON NOTES

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, mathematics, and system scripting. Key features include the importance of indentation for code blocks, the use of comments for code clarity, and the ability to create and manipulate variables without strict type declarations. Python supports various data types, operators, and allows for operations such as casting and unpacking collections.

Uploaded by

Ali Sultan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PYTHON NOTES

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, mathematics, and system scripting. Key features include the importance of indentation for code blocks, the use of comments for code clarity, and the ability to create and manipulate variables without strict type declarations. Python supports various data types, operators, and allows for operations such as casting and unpacking collections.

Uploaded by

Ali Sultan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PYTHON NOTES

What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability


only, the indentation in Python is very important.

1. Python uses indentation to indicate a block of code.

2. Python will give you an error if you skip the indentation.

3. The number of spaces is up to you as a programmer, the most


common use is four, but it has to be at least one.

4. You have to use the same number of spaces in the same block of
code, otherwise Python will give you an error

Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:

Example: #This is a comment


print("Hello, World!")

Multiline Comments
Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

Example: #This is a comment


#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your comment
inside it:

Example: """
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Python Variables
Variables are containers for storing data values. Remember that variable
names are case-sensitive.
Creating Variables
A variable is created the moment you first assign a value to it.

Example: x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even
change type after they have been set.

Example: x = 4 # x is of type int


x = "Sally" # x is now of type string
print(x)

Casting
If you want to specify the data type of a variable, this can be done with casting.

Example: x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type


You can get the data type of a variable with the type() function.

Example: x = 5
y = "John"
print(type(x))
print(type(y))

Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)
 A variable name cannot be any of the Python Keywords.
Example: myvar = "John"
my_var = "John" Correct ✅
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

2myvar = "John" Incorrect ❌


my-var = "John"
my var = "John"

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:

Example: x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:

Example: x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to
extract the values into variables. This is called unpacking.

Example: fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)
Python Data Types
Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Random Number
Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make random
numbers:

Example: import random

print(random.randrange(1, 10))

Python Operators
Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3
^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

:= print(x := 3) x=3
print(x)

Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y


<= Less than or equal to x <= y

Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

Membership Operators
Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with the x in y
specified value is present in the
object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

Bitwise Operators
Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits x|y


is 1

^ XOR Sets each bit to 1 if only one of two x^y


bits is 1

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from x << 2
shift the right and let the leftmost bits
fall off
>> Signed right Shift right by pushing copies of the x >> 2
shift leftmost bit in from the left, and let
the rightmost bits fall off

Operator Precedence
Operator precedence describes the order in which operations are performed.

If two operators have the same precedence, the expression is evaluated from
left to right.

The precedence order is described in the table below, starting with the highest
precedence at the top:

Operator Description

() Parentheses

** Exponentiation

+x -x ~x Unary plus, unary minus, and bitwise NOT

* / // % Multiplication, division, floor division, and modulus

+ - Addition and subtraction


<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

== != > >= < <= is Comparisons, identity, and membership operators

is not in not in

You might also like