Skip to content

Instantly share code, notes, and snippets.

@pegvin
Last active March 21, 2025 22:34
Show Gist options
  • Save pegvin/e6b5772855e372454d198e4e989d2ad3 to your computer and use it in GitHub Desktop.
Save pegvin/e6b5772855e372454d198e4e989d2ad3 to your computer and use it in GitHub Desktop.
Python Notes

Print Function

The print function takes unlimited amount of inputs & Shows them on screen. So the output of print("Hello", "World") will be Hello World.

By default inputs are separated by space, But we can change that by specifying the separator at the end of the print function like so: print("Hello", "World", sep = "$", And it will result in Hello$World

By default when print function finishes it outputs a new line, We can change that by specifying the ending character like so: print("Hello", "World", end = "$"), And it will result in Hello World$

Find the output:

  1. print("Hello World", sep = "$")
  2. print("Hello", "World", sep = "\n")
  3. print("Hello", "World", sep = "-", end = "$")

Answer:

  1. Hello World
  2. Hello
    World
    
  3. Hello-World$

Escape Codes

  • Printing \n will result in a new line
  • Printing \t will result in a 4 spaces

Variables

Just like in maths, Variables are just containers that hold some value. For example x = 10 will result in variable x storing the value 10

We can use variables as arguments to other functions or use them with operators, For example:

a = 10
b = 5

print(a, b)
print(a * b)

b = 2

print(a, b)
print(a * b)

Will result in:

10 5
50
10 2
20

Input Function

You can take input for user using the input function. Optionally input takes 1 string argument that is a prompt, i.e. that string will be outputted to the user before the input is taken.

It is important to note that input returns a string value.

Example:

name = input("Enter Your Name: ")
print("Good morning", name)

Output:

Enter Your Name: Aditya
Good morning Aditya

Types In Python

  • String -> "Hello"
  • Character (or Char) -> A
  • Integer -> 1, 5, 205, etc
  • Float -> 1.0, 2.67, etc
  • Boolean -> True or False

Implicit & Explicit Type Conversion

In python, A variable maybe be automatically converted to another type to perform an operation. This is called implicit type conversion.

For example the output of print(True + True) is 2, because the values True are converted to integers to perform the addition operation, And in python True is converted to integer as 1 & False as 0.

In various cases, We might wanna explicitly convert a type of a variable to another for various reasons. For example if we want to take a Integer input from user but the input function only returns a string. Therefore we can convert the string into an integer using the int function or into an float using float function.

Example:

a = int(input("Enter a number: "))

print(a * 2)

Operators

Operators are "things" that operate on some input (Usually 2) and result in some output.

For example in Maths, the most common operator is the + operator which adds 2 numbers.

Types of Operators:

  • Arithmetic: Arithmetic operators are used with numeric values to perform common mathematical operations:
    • + Addition
    • - Subtraction
    • * Multiplication
    • / Division
    • // Floor Division (i.e. Division without floating point number)
    • % Modulus (i.e. Remainder)
    • ** Exponentiation
  • Assignment: Assignment operators are used to assign values to variables
    • = Regular Assignment
    • += Increment Assignment
    • -= Decrement Assignment
    • := Walrus (First Assignment Takes Place, Then The Value Is Used)
  • Comparison (or Relational): Comparison operators are used to compare two values
    • == Equals To
    • != Not Equals To
    • > Greater Than
    • >= Greater Than Or Equals To
    • < Less Than
    • <= Less Than Or Equals To
  • Logical: Logical operators are used to combine conditional statements
    • and Returns True if both statements are true
    • or Returns True if one of the statements is true
    • not Reverse the result, returns False if the result is true
  • Bitwise: Bitwise operators are used to compare (binary) numbers
    • & Sets each bit to 1 if both bits are 1 (And)
    • | Sets each bit to 1 if one of two bits is 1 (Or)
    • ^ Sets each bit to 1 if only one of two bits is 1 (Xor)
    • ~ Inverts all the bits (Not)
    • << Shift left by pushing zeros in from the right and let the leftmost bits fall off
    • >> Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

Operator Precedence

In an complex expression comprising of multiple operators, Some operators have higher precedence than others, It's similar to BODMAS rule in maths.

Operator Associativity
() Left To Right
** Right To Left
* / // % Left To Right
+ - Left To Right
<< >> Left To Right
& Left To Right
^ Left To Right
| Left To Right
== != > >= < <= Left To Right
not Left To Right
and Left To Right
or Left To Right

Conditional Statements

Often in programs, We want to execute some code depending on some condition, This is where if, elif & else come in.

The syntax of it is as follows:

if condition1:
    ...code...
elif condition2:
    ...code...
else:
    ...code...

The order of if, elif & else is same as above, You cannot have elif before if or after else & you cannot have else before if or elif.

Also the code for each corresponding statement can either be in the same line after the colon or it can be in new line but has to be indented to tell python that code is part of the statement above.

It is important to note that the all the if, elif & else statements will ALWAYS end with a colon (:).

Program to check if a number is divisible by 3 or 5 or both:

a = int(input("Enter A Number: "))

if a % 3 == 0 and a % 5 == 0:
    print("Divisible By Both")
elif a % 3 == 0:
    print("Divisible By 3")
elif a % 5 == 0:
    print("Divisible By 5")
else:
    print("Divisible By Neither 3 Nor 5")

Output

Enter A Number: 10
Divisible By 5

Match Statement

In various cases, We often find ourselves comparing the same variable with multiple values to do different things with it, Therefore the match statement can be used to do the same thing in much more cleaner way.

The syntax of match is as follows:

match variable:
    case 1:
        ...code...
    case "something":
        ...code...
    case 3.25:
        ...code...
    case _:
        ...default case...

Here, The code corresponding to case that matches the value of variable is executed, If no match is found then optionally a default case (_) can be used.

Example: Program to print price of a given fruit

fruit = input("Enter A Fruit")

match fruit:
    case "mango":
        print("80/Kg")
    case "banana":
        print("60/Dozen")
    case "apple":
        print("90/Kg")
    case _:
        print("Unknown Fruit")

Output:

Enter A Fruit: mango
80/Kg

While Loop

A while loop is a loop that will execute some code until the specified condition becomes false. The syntax is as follows:

while condition:
    ...code...

Example: Program to print numbers from 1 to 5

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

Output

1
2
3
4
5

You can use break inside the while loop to terminate the loop earlier like so:

a = 1
while a <= 5:
    if a == 3:
        break
    print(a)
    a += 1

Output

1
2

Or you can use continue inside the loop to continue to the next cycle of the loop like so:

a = 0
while a <= 5:
    a += 1
    if a == 3:
        continue
    print(a)

Output

1
2
4
5
6

For Loop

A for loop is used for iterating over a sequence (that is either a list or a string, etc). The syntax of an for loop is as follows:

for i in something:
    ...code...

where something is a sequence.

Example: print all the characters in the string "banana" 1 by 1

for i in "banana":
    print(i)

Output

b
a
n
a
n
a

Note that break & continue can be used in for loops as well.

Range Function

The range function creates a sequence of numbers in a given range. For example range(5) will create a sequence {0, 1, 2, 3, 4}. or range(2, 6) will create a sequence {2, 3, 4, 5}.

Therefore, We can use the sequence generated by range in a for loop to do all sorts of thing. The simplest of all is simply printing numbers from 1 to 5

for i in range(1, 6):
    print(i)

Output

1
2
3
4
5

pow Function

The pow function is same as the ** operator, Therefore pow(a, b) is same as a ** b.

len Function

The len function takes a sequence like a string or a list & returns it's length, Therefore len("Hello") must be 5.

abs Function

The abs function takes a number & Simply returns it's absolute value, i.e. abs(-5.5) is equal to 5.5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment