Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Data Science Essentials for Data Analysts/1.2 Python basics for Data Science.ipynb
3074 views
Kernel: Python 3 (ipykernel)

Python For Data Science

  • Python is one of the most popular languages used by Data Scientists. Python has in-built mathematical libraries and functions, making it easier to calculate mathematical functions.

Data Containers in Python

  1. Strings 2. Lists 3. Tuples 4. Dictionary

Variable in Python

"as" type("This is my Class")
str
#Varible Declaratipon # Enter Emp_ID and Name and Age2024 in Python Interface a ="ashi" a_1="Rai" a1=9 _a=0 ash="ashi"

Operations on Numbers

(12+8*2)//3 9**9
387420489
x=2 #2x2+4x-9 2*(x**2)+4*x-9
7
#Quick Practice Declare a varible x =7 and solve following equation using Python: ## What is the output for (4x3+3x2+5x+5)?
x=3 y=6 print("sum",x+y) print("Diff",x-y) print("Div", x/y)
sum 9 Diff -3 Div 0.5
print(2+3,4+5,3*4,sep="\t")
5 9 12
x=6 print("Total number of partcipants =",x)

Type Conversion: Convert variable into another type e.g int to float

float(2)
2.0
int(9.8) int("98a")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[45], line 2 1 int(9.8) ----> 2 int("98a") ValueError: invalid literal for int() with base 10: '98a'

Input

Name = input("Enter your Name: ") ##Strings Age = int(input("Enter Age:")) ## Integers Height = float(input("Enter Height:")) ## Floats
Enter your Name: a Enter Age:12 Enter Height:23.4
## Link : https://jupyter.org/try-jupyter/lab/

Quick Pratice:

  1. Create python Script to input following details about your products:

  • Number of Products (30)

  • Name of Products Category (3*10)

  • Cost per Unit

  • Total Cost Price

solun a=int(input("no of product ")) b=input("Name of Products Category ") c=float(input("Cost per Unit ")) Total_CP=a*c print("Total Cost Price = ",Total_CP )

Strings

x="a" Y="ABCD" C="Data Science" len(Y) len(C)
12
Y[0],Y[-1],Y[1] C[3:8]
'a Sci'
#Y[4]="E" #del Y[0] del Y #Y
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[57], line 3 1 #Y[4]="E" 2 #del Y[0] ----> 3 del Y 4 Y NameError: name 'Y' is not defined
x="caderg" a="82154" y="12abc" print(min(a),max(a)) print(min(y),max(y))
1 8 1 c
C="Ms Suyashi Raiwani" d=C.split("i") d
['Ms Suyash', ' Ra', 'wan', '']
print(C+C)#3- Concadination print(4*C) #- Repeat
Ms Suyashi RaiwaniMs Suyashi Raiwani Ms Suyashi RaiwaniMs Suyashi RaiwaniMs Suyashi RaiwaniMs Suyashi Raiwani

Quick Practice:

Write a python script to open a railway ticket booking portal and enter following details from users :

  • 1-Name

  • 2-last Name

  • 3-Age

  • 4-Gender

  • 5-Boarding Point

  • 6-destination

## Solution

String Functions and Methods

x="abc123" x.isspace()
False
print(x.isalnum()) print(x.isalpha()) print(x.isupper())
True False False
x.isspace()
x.isalpha()
if (con): if(con): if(con): ---- else(*) else elseif else:

If else condition

a=0 b="ab" if a>80: print("I am happy") if b=="ab" print("correct username") else: print("Inavlid username") if a==0: print("I am Neutral") else: print("Not Happy")
b=input("Your name please") ## %s-string, %d - int, %f-float a=int(input("Enter your Age:")) if a>=18: print("Welcome and sign in to this portal") name=input("Create UserName:") if len(name)>=5: pwd=input("Create Password:") else: print("User Name does not met the criteria") else: print("%s your age i.e %d is not valid to use this portal"%(b,a))

Quick Parctice:

  1. Write a python script to open a railway ticket booking portal and enter following details from users :

  2. Ask for Sign in with UserName, Password (Greater than 5), Age > 16

  3. Login for booking UserName and Pwd

1-Name 2-last Name 3-Age 4-Gender 5-Boarding Point 6-destination

Quick Pratice:

  • Create python Script to input following details about your products:

  • Number of Products (30)

  • Name of Products Category (3*10)

  • Cost per Unit

  • Total Cost Price

# Input details for 30 products num_products = 30 # Define details for each product product_details = { f"Product_{i+1}": { "Name": input(f"Enter name for Product {i+1}: "), "Category": input(f"Enter category for Product {i+1}: "), "Cost per Unit": float(input(f"Enter cost per unit for Product {i+1}: ")), "Total Cost Price": lambda cost_per_unit, quantity=1: cost_per_unit * quantity } for i in range(num_products) } # Display entered product details for key, details in product_details.items(): cost_per_unit = details["Cost per Unit"] details["Total Cost Price"] = details["Total Cost Price"](cost_per_unit) # Calculate total cost print(f"\nDetails for {key}:") print(f"Name: {details['Name']}") print(f"Category: {details['Category']}") print(f"Cost per Unit: {cost_per_unit}") print(f"Total Cost Price: {details['Total Cost Price']}")
## If else: Name= input("Enter UserName") Age=int(input("Age Please")) if len(Name) >=5: print("Valid UserName\t:") if Age>15: print("You can Proceed with booking") else: print("Your Booking Not allowed") else: print("Please check userName Criteria")
x=range(1,10) x
x=list(range(1,10,3) )#start,stop-1,interval x

Quick Practice:

  • Please create a user name of length 6 if user name is valid then create a password of length 7, if pwd is valid then print("Welcome to homepage")

  • Write a program that performs addition, subtraction, multiplication, or division based on user input. Prompt the user to enter two numbers and an operation (+, -, *, /). Perform the calculation and print the result.

## Please create a user name of length 6, create a password of lenghth 7 user=input("Create user name for minimum 6 lenghth:") if len(user) >= 6: print("Valid user name") else: print("Ops! User name not created invalid format")

Bitwise operator

  • Work on binary representations of numbers.

  • Are useful for low-level programming, flags, or optimization tasks

Bitwise Operators in Python

OperatorNameDescriptionExample (x=5, y=3)Result
&Bitwise ANDPerforms AND operation on each bit. If both bits are 1, the result is 1, otherwise 0.x & y1
``Bitwise ORPerforms OR operation on each bit. If either bit is 1, the result is 1.`x
^Bitwise XORPerforms XOR operation on each bit. If the bits are different, the result is 1.x ^ y6
~Bitwise NOTInverts all the bits of the number (1 becomes 0 and 0 becomes 1).~x-6
<<Left ShiftShifts bits to the left by the specified number of positions.x << 220
>>Right ShiftShifts bits to the right by the specified number of positions.x >> 21

Notes:

  • Bitwise AND (&): Only 1 if both bits are 1.

  • Bitwise OR (|): At least one bit must be 1.

  • Bitwise XOR (^): True when bits differ.

  • Bitwise NOT (~): Flips all bits; equivalent to -(x+1).

  • Left Shift (<<): Shifts bits left, filling with zeros on the right.

  • Right Shift (>>): Shifts bits right, discarding bits on the right.

# Bitwise Operators in Python x = 5 # Binary: 0101 y = 3 # Binary: 0011 # Bitwise AND and_result = x & y # 0101 & 0011 = 0001 print(f"x & y = {and_result}") # Bitwise OR or_result = x | y # 0101 | 0011 = 0111 print(f"x | y = {or_result}") # Bitwise XOR xor_result = x ^ y # 0101 ^ 0011 = 0110 print(f"x ^ y = {xor_result}") # Bitwise NOT not_result = ~x # ~0101 = -(0101 + 1) = -6 print(f"~x = {not_result}") # Left Shift left_shift_result = x << 2 # 0101 << 2 = 10100 (equivalent to multiplying by 2^2) print(f"x << 2 = {left_shift_result}") # Right Shift right_shift_result = x >> 2 # 0101 >> 2 = 0001 (equivalent to dividing by 2^2) print(f"x >> 2 = {right_shift_result}")
x & y = 1 x | y = 7 x ^ y = 6 ~x = -6 x << 2 = 20 x >> 2 = 1
x = 5 x &= 4 print("After x &= 4:", x) # Bitwise AND x |= 10 print("After x |= 10:", x) # Bitwise OR x ^= 6 print("After x ^= 6:", x) # Bitwise XOR x >>= 8 print("After x >>= 8:", x) # Right Shift x <<= 8 print("After x <<= 8:", x) # Left Shift print(x := 3) # Walrus operator
After x &= 4: 4 After x |= 10: 14 After x ^= 6: 8 After x >>= 8: 0 After x <<= 8: 0 3
## Loops for i in range(0,3): user=input("Enter your name:")
for i in "ash": user=input("Enter your name:\t")

Ques 2:

Input create a password with following critera:

  1. Min len 3 and 10

  2. Should contain one number

  3. Should contain upper case member

  4. Should not have a space

  5. Shoukd have one special charactor sp=["@","?","*","$","&","^",#.!]

## Atleast one number d=0 s=0 u=0 sp=["@","?","*","$"] user=input("Create user name for minimum 6 lenghth:") for i in user: if i.isdigit(): d=d+1 if i.isspace(): s=s+1 if i.isupper(): u=u+1 else: pass if d>0 and s==0: pass else: print("Opps !! you have not added a digit to username or included a space") if u>0: print("Valid User name") else: print("Opps !! you have not added a uppercase ")
s="poor" #3s[4]=s #del s[1] del s s= "this is first session for data Science" #s.split(" ") s.index("f")

List

a=[] a=[1,1,2] b=[1,2.1,"a"] c=[[1,12], ["b",1]]
type(b)
c[0] [0]
x=["a","b","c"]
x.append("d")
x
x.insert(2,3)
x
len(x) del x[2]
x max(x)
## Tuples b=(1,2,3) len(b) #b.append(4) del b[2] ## tuples also does not support item addition or deletion.

Dictionary

  • Mapping data types

  • Key value pairs

  • key are index to members for dictionary

  • Keys are unique with one value for one key

  • Duplicate Key creation is not possible

d={} d={"A":"red","B":"Blue"}
d.keys()
d.values()
d["C"] ="green"
d["D"] = "Yellow" d
d
d['C']
d['A']
d={1:"a",2:"b"} d
d[1]="a" d

Loops

  • for i in range(1,6): range(6,2,-1) range(1,6):

a=list(range(10,2,-2)) a
## User Input List x=[] n=int(input("Enter number of members" )) for i in range (0,n): m=int(input("Add list member\t:")) x.append(m) print(x)
d["f"]=("2","3") d
#### user input Diction d={} n=int(input("Enter number of members")) for i in range (0,n): a=input("Enter Key Name:\t") d[a]=b b=input("Enter VALUE Name:\t") print(d)

Quick Practice 3 :

  • Create a list with all float values

  • Create a dictionary with Emp ID as Key and Names as Values

#Create a dict emp ID as key and names as values emp_data={} n=int(input("Enter number of employees")) for i in range (0,n): Emp_id=input("Enter Emp ID") Name = input("Enter Name") d[Emp_id]=Name print(d)
## Create a dic named Emp_details with Emp ID as Keys and job roels as values. "A101, B101"

Loops

for i in range (0,5): input("Enter Emp name\t: ")