Skip to main content

๐Ÿ”ฐ Python Basics

This page provides an introduction to python basics.

Variableโ€‹

# str
name = "abc"

# int
age = 5

# float
height = 172.2

# bool
is_student = True

String Formattingโ€‹

print(f"name: {name}, age: {age}, height: {height}, is_student: {is_student}")
# o/p: name: abc, age: 5, height: 172.2, is_student: True

Typecastingโ€‹

# get type of a variable 
print(f"type of name: {type(name)}, value: {name}")
# o/p: type of name: <class 'str'>, value: abc



# convert int to float
print(f"type of age: {type(age)}, value: {age}")
# o/p: type of age: <class 'int'>, value: 5


age_float = float(age)
print(f"type of age_float: {type(age_float)}, value: {age_float}")
# o/p: type of age_float: <class 'float'>, value: 5.0



# convert bool to str
print(f"type of is_student: {type(is_student)}, value: {is_student}")
# o/p: type of is_student: <class 'bool'>, value: True


is_student_str = str(is_student)
print(f"type of is_student_str: {type(is_student_str)}, value: {is_student_str}")
# o/p: type of is_student_str: <class 'str'>, value: True



# convert str to bool
print(f"type of name: {type(name)}, value: {name}")
# o/p: type of name: <class 'str'>, value: abc


name_bool = bool(name)
print(f"type of name_bool: {type(name_bool)}, value: {name_bool}")
# o/p: type of name_bool: <class 'bool'>, value: True
info

Converting a value to a boolean returns True if the value is non-zero or non-empty, and False otherwise.

User Inputโ€‹

name = input("Enter your name: ")
print(f"Hello {name}")
# o/p: Hello, abc
info

The input will always be of type str.

Arithmetic Operatorsโ€‹

count = 1


# add
count = count + 1
count += 1


# substract
count = count - 1
count -= 1


# multiply
count = count * 5
count *= 5


# divide
count = count / 2
count /= 2


# exponent
count = count ** 2
count **= 2


# modulus
count = count % 3

# round
count = round(count)

# abs
count = abs(count)

# pow
count = pow(count, 3)


# assign values
x = 1
y = 3.3
z = 4


# max
max_value = max(x, y, z)

# min
min_value = min(x, y, z)



import math

# pi
math.pi

# e
math.e

# sqrt
count = math.sqrt(count)

# ceil
math.ceil(y)

# floor
math.floor(y)

If Elseโ€‹

if age <= 0: print("Invalid")
elif age < 18: print("No")
else: print("Yes")

Conditional Expressionโ€‹

num = 2
condition = "Positive" if num >= 0 else "Negative"
print(condition)

Logical Operatorโ€‹

# not 
if not age:
print("Invalid")
# and
elif age >= 0 and age <= 18:
print("No")
# or
elif age >= 18 or age <= 30:
print("Yes")

String Methodsโ€‹

# len
len(name)
3

# find
name.find("o")

# reverse find - last occurance
name.rfind("q")

# capitalize
name.capitalize()

# upper
name.upper()

# lower
name.lower()

# isdigit - if string contains only digits
name.isdigit()

# isalpha - if string contains only alphabets
name.isalpha()
info

To list all the methods of string you can do print(help(str)).

String Indexingโ€‹

credit_card_number = "0123-4567-8901-2345"

print(credit_card_number[0])
# o/p: 0

print(credit_card_number[:4])
# o/p: 0123

print(credit_card_number[5:9])
# o/p: 4567

print(credit_card_number[5:])
# o/p: 4567-8901-2345

print(credit_card_number[-1])
# o/p: 5

print(credit_card_number[::2]) # prints every 2 character in a string
# o/p: 02-5780-35
info

Last example uses syntax [start : end : step]

Format Specifiersโ€‹

price_1 = -3.14159
price_2 = 987000.65
price_3 = 12.34

# decimal places
print(f"Price 1 is ${price_1:.2f}")
# o/p: Price 1 is $-3.14
print(f"Price 2 is ${price_2:.1f}")
# o/p: Price 2 is $987000.7
print(f"Price 3 is ${price_3:.3f}")
# o/p: Price 3 is $12.340



# width
print(f"Price 1 is ${price_1:10}")
# o/p: Price 1 is $ -3.14159
print(f"Price 2 is ${price_2:10}")
# o/p: Price 2 is $ 987000.65
print(f"Price 3 is ${price_3:10}")
# o/p: Price 3 is $ 12.34




# preset with zero
print(f"Price 1 is ${price_1:010}")
# o/p: Price 1 is $-003.14159
print(f"Price 2 is ${price_2:010}")
# o/p: Price 2 is $0987000.65
print(f"Price 3 is ${price_3:010}")
# o/p: Price 3 is $0000012.34




# left justify
print(f"Price 1 is ${price_1:<010}")
# o/p: Price 1 is $-3.1415900
print(f"Price 2 is ${price_2:<010}")
# o/p: Price 2 is $987000.650
print(f"Price 3 is ${price_3:<010}")
# o/p: Price 3 is $12.3400000




# right justify
print(f"Price 1 is ${price_1:>10}")
# o/p: Price 1 is $ -3.14159
print(f"Price 2 is ${price_2:>10}")
# o/p: Price 2 is $ 987000.65
print(f"Price 3 is ${price_3:>10}")
# o/p: Price 3 is $ 12.34




# center
print(f"Price 1 is ${price_1:^10}")
# o/p: Price 1 is $ -3.14159
print(f"Price 2 is ${price_2:^10}")
# o/p: Price 2 is $987000.65
print(f"Price 3 is ${price_3:^10}")
# o/p: Price 3 is $ 12.34




# assign sign
print(f"Price 1 is ${price_1:+10}")
# o/p: Price 1 is $ -3.14159
print(f"Price 2 is ${price_2:+10}")
# o/p: Price 2 is $+987000.65
print(f"Price 3 is ${price_3:+10}")
# o/p: Price 3 is $ +12.34




# thousand seperator
print(f"Price 1 is ${price_1:,}")
# o/p: Price 1 is $-3.14159
print(f"Price 2 is ${price_2:,}")
# o/p: Price 2 is $987,000.65
print(f"Price 3 is ${price_3:,}")
# o/p: Price 3 is $12.34




# thousand seperator, with decimal places
print(f"Price 1 is ${price_1:,.2f}")
# o/p: Price 1 is $-3.14
print(f"Price 2 is ${price_2:,.2f}")
# o/p: Price 2 is $987,000.65
print(f"Price 3 is ${price_3:,.2f}")
# o/p: Price 3 is $12.34

While Loopโ€‹

your_name = None
while not your_name:
your_name = input("Enter your name: ")
if your_name : print(f"Hello, {your_name}")

For Loopโ€‹

for i in range(1, 11): 
print(i)
# o/p: 1, 2, 3, 4, 5, 6. 7, 8, 9, 10


# reversing for loop
for i in reversed(range(1, 11)):
print(i)
# o/p: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1


# increment by 2
for i in range(1, 11, 2):
print(i)
# o/p: 1, 3, 5, 7, 9


# iterate over string
for i in "abc":
print(i)
# o/p: a, b, c
info

For loop range is inclusive on left side and exclusive on right side.

Randomโ€‹

import random

# random int
random.randint(1, 6)
# o/p: 4


# random float
random.random()
# o/p: 0.2813447139323776


# random choice
options = ["rock", "paper", "scissors"]
random.choice(options)
# o/p: rock


# shuffle collection
cards = ["A", "2", "3", "4", "5", "6"]
random.shuffle(cards)
# o/p: ['A', '6', '5', '3', '2', '4']
info

Random is inclusive on both sides.

Functionsโ€‹

# defining a function
def happy_birthday(name):
print(f"Happy Birthday {name}")


# calling function
happy_birthday("abc")
# o/p: Happy Birthday abc


happy_birthday("pqr")
# o/p: Happy Birthday pqr


happy_birthday("xyz")
# o/p: Happy Birthday xyz


# defining a function with return value
def add(x, y):
return x + y


# calling function
add(1, 2)
# o/p: 3

Arbitary Argumentsโ€‹

Arbitary arguments are of two types:

  • *args: passed as tuple.
  • **kwargs: passed as dictionary.
# *args example
def add(*args):
total = 0
for arg in args:
total += arg
return total


# calling a function with *args
add(1,2,3,4,5,6,7,8,9,10)
# o/p: 55
# **kwargs example
def print_address(**kwargs):
for value in kwargs.values():
print(value, end =" ")


# calling function
print_address(street="123 Street", city="San Jose", state="CA")
# o/p: 123 Street San Jose CA
info

In above examples name of the variable doesn't have to be args and kwargs, it can be anything.

Match Statementโ€‹

def day_of_week(day):
match day:
case 1: return "Sunday"
case 2: return "Monday"
case 3: return "Tuesday"
case 4: return "Wednesday"
case 5: return "Thrusday"
case 6: return "Friday"
case 7: return "Saturday"
case _: return "Invalid"


day_of_week(5)
# o/p: Thrusday

Moduleโ€‹

# importing a module
import math
print(math.pi)


import math as m
print(m.pi)


from math import pi
print(pi)
info

To list all the modules in python, run help("modules")

Main Guardโ€‹

Main Guard allows python script to be imported or to run as standalone program.

# script_1.py
def favorite_food(food):
print("Your favorite food is {food}")


def main():
print("This is script_1")
favorite_food("pizza")


if __name__ == '__main__':
main()
# script_2.py
from script_1 import *
favorite_food("curry")
info

In the example above, you can import favorite_food function in script_2.py.