0% found this document useful (0 votes)
7 views12 pages

Class 02

The document provides an overview of programming in Python, emphasizing its importance for data scientists and analysts. It covers fundamental data types, structures like lists, tuples, sets, and dictionaries, as well as basic programming concepts such as comparison and logical operators, functions, and examples of common tasks like swapping variables and calculating factorials. Additionally, it includes practical exercises for implementing various programming challenges.

Uploaded by

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

Class 02

The document provides an overview of programming in Python, emphasizing its importance for data scientists and analysts. It covers fundamental data types, structures like lists, tuples, sets, and dictionaries, as well as basic programming concepts such as comparison and logical operators, functions, and examples of common tasks like swapping variables and calculating factorials. Additionally, it includes practical exercises for implementing various programming challenges.

Uploaded by

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

"Programming in Python".

Programming is one of the most fundamental skills you will need as a data
scientist/analyst. Among the numerous tools available for analyzing data, we choose
Python as it is the most robust, has an intuitive syntax, and is a modern and widely
used language.
Here you will learn how to think and do coding for real life scenarios. This portion
will be mostly based on building a strong sense of logic using only the basics.
Below are the fundamental data types in Python. You can create variables of these
types and perform operations accordingly.
1. Integer (int): Represents whole numbers without any decimal points.
x=5
y = -10
2. Float (float): Represents numbers with decimal points.
pi = 3.14
gravity = 9.81
3. String (str): Represents a sequence of characters enclosed within single or
double quotes.
name = "John Doe"
message = 'Hello, World!'
4. Boolean (bool): Represents the truth values True or False.
is_sunny = True
is_raining = False
5. Sequence Types:
1. list: Ordered collection of items, mutable.

2. tuple: Ordered collection of items, immutable.


point = (10, 20)
dimensions = (100, 200, 300)
6. Mapping Type:
a. dict: Collection of key-value pairs
person = {'name': 'John', 'age': 30, 'city': 'New York'}
7. Set Types: Unordered collection of unique items.
vowels = {'a', 'e', 'i', 'o', 'u'}
List: Lists are ordered collections of items, which can be of different data types.
Lists are mutable, meaning their elements can be changed after they are defined.
Syntax: They are defined using square brackets [ ].
# Defining a list
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
# Accessing elements of a list
first_number = numbers[0]
second_fruit = fruits[1]
print("Numbers:", numbers)
print("Fruits:", fruits)
print("First number:", first_number)
print("Second fruit:", second_fruit)

Tuple: Tuples are ordered collections of items, which can be of different data types.
Tuples are immutable, meaning their elements cannot be changed once defined.
Syntax: They are defined using parentheses ().
# Defining a tuple
point = (10, 20)
dimensions = (100, 200, 300)

# Accessing elements of a tuple


x = point[0]
y = point[1]
print("Point:", point)
print("Dimensions:", dimensions)
print("X-coordinate:", x)
print("Y-coordinate:", y)

Set: A set is an unordered collection of unique elements. It is iterable, mutable, and


does not allow duplicate elements. This makes sets unfit for indexing and slicing.
Syntax: Sets are created using curly braces {} or by using the set() constructor.
#Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}

# Adding elements to a set


my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

# Removing elements from a set


my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5, 6}

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}

Dictionary: A dictionary is a collection of key-value pairs. It is unordered, mutable,


and does not allow duplicate keys.
Key is like a index and it is always unique & immutable . Values are the objects that
contain information and its accessed using their keys. Each key is followed by value
separated by colon. Values can be immutable , mutable and duplicates.
Syntax: Dictionaries are created using curly braces {} and colon : to separate keys
and values, or by using the dict() constructor.
# Creating a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}

# Accessing elements in a dictionary


print(my_dict['a']) # Output: 1

# Modifying elements in a dictionary


my_dict['b'] = 5
print(my_dict) # Output: {'a': 1, 'b': 5, 'c': 3}

# Adding new key-value pairs to a dictionary


my_dict['d'] = 4
print(my_dict) # Output: {'a': 1, 'b': 5, 'c': 3, 'd': 4}

# Removing elements from a dictionary


del my_dict['c']
print(my_dict) # Output: {'a': 1, 'b': 5, 'd': 4}

# Dictionary operations
print('a' in my_dict) # Output: True
print('z' in my_dict) # Output: False
print(my_dict.keys()) # Output: dict_keys(['a', 'b', 'd'])
print(my_dict.values()) # Output: dict_values([1, 5, 4])
Comparison Operators :
Comparison operators in Python are used to compare values. They return either
True or False depending on whether the comparison is true or false. Here are the
comparison operators in Python along with examples:

1. Equal to (==): Checks if two values are equal.


x=5
y=5

print(x == y) # Output: True


2. Not equal to (!=): Checks if two values are not equal.
x=5
y = 10

print(x != y) # Output: True


3. Greater than (>): Checks if the left operand is greater than the right operand.

x = 10
y=5

print(x > y) # Output: True


4. Less than (<): Checks if the left operand is less than the right operand.

x=5
y = 10

print(x < y) # Output: True


5. Greater than or equal to (>=): Checks if the left operand is greater than or
equal to the right operand.

x = 10
y = 10

print(x >= y) # Output: True


6. Less than or equal to (<=): Checks if the left operand is less than or equal to
the right operand.

x=5
y = 10
print(x <= y) # Output: True
These comparison operators can be used to compare numbers, strings, or any other
comparable objects in Python, and they return a boolean value (True or False) based
on the comparison result.
Conditional Operators:
Python, logical operators are used to combine conditional statements. Here are the
three logical operators in Python along with examples:

1. AND (and): Returns True if both conditions on its left and right are True.
x=5
y = 10

print(x < 10 and y > 5) # Output: True


2. OR (or): Returns True if at least one of the conditions on its left or right is
True.
x=5
y = 10

print(x < 10 or y < 5) # Output: True


3. NOT (not): Returns True if the condition after it is False, and vice versa.
x=5

print(not x > 10) # Output: True


These logical operators can be used to create more complex conditions by
combining simpler conditions. They are often used in if statements, while loops, and
other control flow statements to control the flow of execution based on multiple
conditions.
F-String
F-strings, introduced in Python 3.6, provide a concise and convenient way to embed
expressions within string literals. Here's an example demonstrating how to use f-
strings:
name = "Alice"
age = 30

# Using f-string to embed variables within a string


message = f"My name is {name} and I am {age} years old."

print(message)

Output: My name is Alice and I am 30 years old.

In this example:

name and age are variables containing string and integer values respectively.
The f-string f"My name is {name} and I am {age} years old." allows embedding of
variables directly within the string using curly braces {}.
When this f-string is evaluated, the expressions within curly braces are replaced
with the values of the corresponding variables.
The resulting string is then stored in the variable message.
Finally, the message variable is printed, resulting in the formatted string being
displayed.

Swapping
Description
You are given two integer variables, x and y. You have to swap the values stored in
x and y.
----------------------------------------------------------------------------------------------------------------
Code:
x=5
y = 10

print("Before swapping:")
print("x =", x)
print("y =", y)

# Swapping values
temp = x
x=y
y = temp
print("\nAfter swapping:")
print("x =", x)
print("y =", y)

Can you swap two variables in python without using a third variable?
#x,y=y,x

a=5
b = 10
print("Before swap: a =", a, ", b =", b)
# Swapping
a, b = b, a
# After swap
print("After swap: a =", a, ", b =", b)
Even or Odd

Description
Given an integer, print whether it is Even or Odd.

-----------------------------------------------------------------------------------------------------------------

Code
#Take input on your own
num=int(input())

#start writing your code from here


if num%2==0:
print("Even")
else:
print("Odd")
Alarm Clock

Description
You're trying to automate your alarm clock by writing a function for it. You're given a
day of the week encoded as 1=Mon, 2=Tue, ... 6=Sat, 7=Sun, and whether you are on
vacation as a boolean value Based on the day and whether you're on vacation, write a
function that returns a time in form of a string indicating when the alarm clock should
ring.

When not on a vacation, on weekdays, the alarm should ring at "7:00" and on the
weekends (Saturday and Sunday) it should ring at "10:00".

While on a vacation, it should ring at "10:00" on weekdays. On vacation, it should not


ring on weekends, that is, it should return "off".

------------------------------------------------------------------------------------------------------------------

def alarm_clock(day, vacation):


if vacation:
if day in [1, 2, 3, 4, 5]: # Weekdays
return "10:00"
else: # Weekends
return "off"
else:
if day in [1, 2, 3, 4, 5]: # Weekdays
return "7:00"
else: # Weekends
return "10:00"
# Example usage:
print(alarm_clock(1, False)) # Output: "7:00" (Monday, not on vacation)
print(alarm_clock(6, False)) # Output: "10:00" (Saturday, not on vacation)
print(alarm_clock(7, True)) # Output: "off" (Sunday, on vacation)

Factorial
Factorial is a mathematical function denoted by '!'. It is defined as

n factorial = n!= 1*2*3...*(n-1)*n

In this question, you have to make a function that will take an integer as input, and
return the factorial of that integer if that integer is greater than or equal to zero and
return -1 if the number is less than zero or negative.

Note: the function doesn't return print the factorial but returns it.
def factorial(n):
if n < 0:
return -1 # Return -1 for negative numbers
elif n == 0:
return 1 # Factorial of 0 is 1
else:
result = 1
for i in range(1, n + 1):
result *= i (this is nothing but augmented function and can also be written
as result = result*i)
return result

# Example usage:
print(factorial(5)) # Output: 120 (5 factorial)
print(factorial(0)) # Output: 1 (Factorial of 0)
print(factorial(-3)) # Output: -1 (Negative input)

Reverse The Digits


You will be given a number. You have to reverse the digits of the number and print
it.

#write code to reverse the number here


n = 12345 # Sample number
r=0
while(n>0):
r = r*10 + n%10
n=n//10

print(r)

How Many Chocolates


Sanjay loves chocolates. He goes to a shop to buy his favourite chocolate. There he
notices there is an offer going on, upon bringing 3 wrappers of the same chocolate,
you will get new chocolate for free. If Sanjay has m Rupees. How many chocolates
will he be able to eat if each chocolate costs c Rupees?
#start writing your code here
m = 15 # Sample amount of money Sanjay has
c = 2 # Sample cost of one chocolate
choc = m//c
w = m//c

while w//3!=0:
choc = choc +w//3
w = w//3 + w%3
#dont forget to print the number of chocolates Sanjay can eat
print(choc)

Print the Pattern


Printing different patterns is a very good exercise to reinforce iteration through
loops and strong logic building. Here you will be given a positive integer and you will
generate pattern based on that integer.
#please take input here
n = int(input())
#start writing your code here
for i in range(1, n+1):
for j in range(n-i):
print(' ',end= '')
for k in range(i-1):
print('*_',end='')
print('*')

While surfing on Facebook, whenever you visit a profile, you must have
noticed that it shows a small tab called mutual friends. This shows the
number of mutual friends and also the names of all the mutual friends.
How would you implement this functionality?

Create two lists, my_user_list and friend_user_list.


Next compute the number of mutual friends in both lists using a third variable
"num_mutal"
by checking if user_id1 exists in both my_user_list and friend_user_list.
This way you will check for all 1,2,...,nth count.
Then identify common friends and give the count of mutual friends.

You have to implement the ATM machine. The basic function of an ATM
machine is, you insert your card and pin, if the pin matches, it lets you
withdraw money from your account and deducts the same from your
account. Don't forget to handle cases like insufficient balance and no cash
available. The more realistic ATM model you build the better.
Start -->Insert ATM card --> Select language of user choice -->Enter 4 digit ATM
PIN and press enter -->If PIN does not match for the given card , show “Error
Message” and asks to re-enter correct PIN else move to next step --> Select the
transaction type to withdraw money --> If there is no money in the ATM machine
show error as “Unable to withdraw money” else move to next step -->Enter the
amount manually in the given box or choose the amount as per given options on
the screen --> For the amount entered if user does not have enough balance in
savings , show error as “Insufficient Balance” else move to the next step--> Select
options “Yes” or “No” for the transaction receipt --> Take the cash and the receipt
when the machine gives it -->When the machine beeps take back your ATM card--
> End

Implement a simple calculator.

This will take only numbers and operations as input(addition,


subtraction, multiplication, division). You may choose to take more
operations (Let's see who can design a calculator with most
functionalities)

Please state any more assumptions that you make.

Start --> Define a function called “Calculator” that takes two arguments:
num1 and num2 --> Enter first number (num1) -->Enter the operation that
user wants to perform (+,-,*,/,%,//) --> Enter the second number (num2) --
>Perform the calculation. --> Print the result --> End

You might also like