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

Intro2Python

Uploaded by

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

Intro2Python

Uploaded by

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

Welcome to 2 Day of

nd

Python Training
Installing Jupyter Notebook

pip install notebook

jupyter notebook --version

jupyter notebook
Basic data types and variables

Data Types are used to define the type of a variable, indicating the kind
of data that will be stored.
Different types of data can be stored in memory, such as numeric
values, alphanumeric characters, and more.

Numeric: int, float, complex Mapping: dict

String: str Boolean: bool

Sequence: list, tuple, range Set: set, frozenset

Binary: bytes, bytearray, memoryview None: NoneType


Numeric Data Type
Python numeric data types store numeric values. Number objects are
created when you assign a value to them.
For example: var1 = 1

var2 = 10

var3 = 10.023
Numeric Type Examples

int 10, 100, -786, 080, -0490

long 51924361L, 0x19323L

float 0.0, 15.20, -21.9

complex 3.14j, 45.j, 9.322e-36j


a = 100print("The type of variable having value", a, " is ", type(a))

b = 20.345print("The type of variable having value", b, " is ", type(b))

c = 10 + 3jprint("The type of variable having value", c, " is ", type(c))


Output:

The type of variable having value 100 is <class 'int’>

The type of variable having value 20.345 is <class 'float’>

The type of variable having value (10+3j) is <class 'complex'>


String Data Type:

• Strings are sequences of characters enclosed within either single (' ')
or double (" ") quotes.
• They represent textual data and can include letters, digits, and
special characters.
• Python allows for the use of various operations and manipulations
on strings.
String Indexing and Slicing:
Strings can be indexed and sliced using the square brackets [ ] and the
slicing notation [:]. Indexing starts from 0 for the first character and can
also be negative for backward indexing.

String Concatenation and Repetition:


Strings can be concatenated using the + operator and repeated using the *
operator.
str = 'Hello World!’
print(str)
str = 'Hello World!’
print(str[0])
str = 'Hello World!’
print(str[2:5])
str = 'Hello World!’
print(str[2:])
str = 'Hello World!’
print(str * 2)
str = 'Hello World!’
print(str + "TEST")
Output:

Hello World!
H
lo
llo World!
Hello World!Hello World!
Hello World!TEST
List Data Type:

• Lists are versatile and dynamic sequences of items enclosed


within square brackets ([]).
• Each item in a list can be of any data type, and the items
are separated by commas.
• Lists are similar to arrays in other programming languages,
but they can hold items of different types.
List Indexing and Slicing:
List Concatenation and
List items can be accessed using the Repetition:
indexing notation [ ] and the slicing
notation[:] Lists can be concatenated using the +
operator and repeated using the *
operator.
Indexing starts from 0 for the first
element and can also be negative for
backward indexing.
my_list = [10, 'Hello', 3.14, [1, 2, 3]]

# Accessing list elements


print(my_list[0])
print(my_list[1])
print(my_list[3][1])

# Slicing the list


print(my_list[1:3])

# Concatenating lists
new_list = my_list + [5, 6]print(new_list)
Output:

10
Hello
2
['Hello', 3.14]
[10, 'Hello', 3.14, [1, 2, 3], 5, 6]
Tuple Data Type:
• Tuples are similar to lists but are enclosed in parentheses ( ).

• They are another sequence data type that consists of a


number of values separated by commas.

• Unlike lists, tuples are immutable, meaning their elements


cannot be changed after creation.

• Tuples are often used to group related data.


# Defining a tuple
my_tuple = (10, 'World', 2.718, (7, 8, 9))

# Accessing tuple elements


print(my_tuple[0])
Output:

10
World
9
range() Function:

• The range() function is a built-in function that returns a


sequence of numbers.
• It starts from a specified value (default is 0) and increments
by a specified value (default is 1), until it reaches a specified
stopping value.
• This sequence of numbers is often used in loops to iterate
over a certain range.
Syntax:
range(start, stop, step)
# Using range() to create a sequence of numbers
for num in range(5): # Generates numbers from 0 to 4
print(num, end=' ')
print() # Prints a new line

# Using range() with start and stop values


for num in range(2, 8): # Generates numbers from 2 to 7
print(num, end=' ')
print() # Prints a new line

# Using range() with start, stop, and step values


for num in range(1, 10, 2): # Generates odd numbers from 1 to 9
print(num, end=' ')
Output:

01234
234567
13579
Dictionaries:
• Python dictionaries are a type of hash table that consists of
key-value pairs.
• They work like associative arrays or hashes found in other
programming languages.
• A dictionary's key can be almost any Python type, but they
are usually numbers or strings. The corresponding values can
be any arbitrary Python objects.
• Dictionaries are enclosed within curly braces {} and values
can be assigned and accessed using square brackets [].
# Creating a dictionary

person = {
"first_name": "John",
"last_name": "Doe",
"age": 30,
"city": "New York“
}
# Accessing values using keys
print("First Name:", person["first_name"])
print("Age:", person["age"])
# Modifying values
person["age"] = 31print("Updated Age:", person["age"])
# Adding new key-value pairs
person["occupation"] = "Engineer“ # Iterating through keys and
# Deleting a key-value pair values
del person["city"] for key, value in person.items():
print(key + ":", value)
# Checking if a key exists
if "occupation" in person: # Clearing the dictionary
print("Occupation:", person["occupation"]) person.clear()
Output:

First Name: John


Age: 30
Updated Age: 31
Occupation: Engineer
first_name: John
last_name: Doe
age: 31
occupation: Engineer
Boolean Type:

• The Python boolean type is a built-in data type that


represents one of two values: either True or False.
• Booleans are fundamental for control flow and logical
operations in programming.
• The bool() function in Python allows you to evaluate the
value of any expression and returns either True or False
based on the expression's truthiness.
# Using boolean values
is_sunny = True
is_raining = False
print("Is it sunny?", is_sunny)
print("Is it raining?", is_raining) # Using bool() function

number = 42
# Using comparison operators is_positive = bool(number > 0)
x=5 is_even = bool(number % 2 == 0)
y = 10
greater_than = x > y print("Is the number positive?", is_positive)
print("Is the number even?", is_even)
less_than = x < y
print("Is x greater than y?",
greater_than)
print("Is x less than y?", less_than)
Output:

Is it sunny? True
Is it raining? False
Is x greater than y? False
Is x less than y? True
Is the number positive? True
Is the number even? True
Data Type Conversion Functions:

You can convert between different data types using built-in functions. These
functions allow you to change the type of a variable to another type.
The most commonly used data type conversion functions are:
• int() - converts to an integer
• float() - converts to a floating-point number
• str()- converts to a string
• bool() - converts to a boolean
• list() - converts to a list
• tuple() - converts to a tuple
• dict() - converts to a dictionary
• set()- converts to a set
# Converting to int
string_number = "42“
integer_number = int(string_number)
print("Converted to int:", integer_number)

Output:
Converted to int: 42
# Converting to float
integer_value = 25
float_value = float(integer_value)
print("Converted to float:", float_value)

Converted to float: 25.0


# Converting to str
number = 123
string_value = str(number)
print("Converted to str:", string_value)

Converted to str: 123


# Converting to bool
truth_value = "True“
bool_value = bool(truth_value)
print("Converted to bool:", bool_value)

Converted to bool: True

# Converting to list
tuple_values = (1, 2, 3)
list_values = list(tuple_values)
print("Converted to list:", list_values)

Converted to list: [1, 2, 3]


# Converting to tuple
list_items = [4, 5, 6]
tuple_items = tuple(list_items)
print("Converted to tuple:", tuple_items)

Converted to tuple: (4, 5, 6)


# Converting to dict
list_of_pairs = [("a", 1), ("b", 2), ("c", 3)]
dict_items = dict(list_of_pairs)
print("Converted to dict:", dict_items)

Converted to dict: {'a': 1, 'b': 2, 'c': 3}


# Converting to set
list_of_numbers = [1, 2, 3, 2, 1]
set_of_numbers = set(list_of_numbers)
print("Converted to set:", set_of_numbers)

Converted to set: {1, 2, 3}


Interview Questions
1. What are the built-in data types in Python?
Discuss the various built-in data types available in Python such as int, float, str, list, tuple, dict, set, and bool.
TCS Infosys Wipro Cognizant
2. Explain the difference between a list and a tuple in Python.
Highlight that lists are mutable and enclosed in [], while tuples are immutable and enclosed in ().
Accenture Tech Mahindra HCL Capgemini
3. How do you convert data types in Python?
Explain the use of conversion functions like int(), float(), str(), etc., to convert between different data types.
IBM Oracle Microsoft
4. What is the purpose of the range() function in Python?
Describe how the range() function generates a sequence of numbers, and its parameters: start, stop, and step.
Google Amazon Flipkart

Coding Questions
1. Write a Python program to demonstrate string concatenation and repetition.
Create a simple code snippet that shows how to concatenate and repeat strings in Python.
Uber Ola Swiggy Zomato
2. Implement a function that takes a list and returns a tuple containing the first and last elements.
Write a function that accepts a list and returns a tuple with the first and last elements of the list.
Paytm PhonePe Razorpay
1. Create a simple program that defines variables of different data
types (int, float, str) and prints their types using the type()
function.
2. Write a function that takes a numeric value and returns its string
and boolean representations using str() and bool().
3. Implement a small program that creates a list of mixed data types
(int, str, float) and demonstrates indexing and slicing.
Solution 1

var1 = 10
var2 = 3.14
var3 = "Hello"
print(type(var1), type(var2), type(var3))
Solution 2

def convert_value(num):
return str(num), bool(num)
Solution 3

my_list = [1, "Python", 3.14, True]


print(my_list[1:3])
# Output: ['Python', 3.14]
input() Function:

# Accepting user input


name = input("Enter your name: ")
print("Hello,", name)

# Accepting.numerical input
age = int(input("Enter your age: "))
print("You are", age, "years old.")
1. Create a simple program that prompts the user for their favorite
color and then prints a message that includes their response.

2. Write a program that asks the user for two numbers, then prints
their sum.

3. Build a program that asks for the user's name and age, then prints
a personalized greeting that includes both pieces of information.
1.
color = input("What is your favorite color? ")
print("Your favorite color is", color)

2.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("The sum is", num1 + num2)

3.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old!")
Arithmetic Operators
a = 10
b=3

print("Addition:", addition)
addition = a + b print("Subtraction:", subtraction)
subtraction = a - b print("Multiplication:", multiplication)
multiplication = a * b print("Division:", division)
division = a / b print("Floor Division:", floor_division)
print("Modulus:", modulus)
floor_division = a // b print("Exponentiation:", exponentiation)
modulus = a % b
exponentiation = a ** b
Output:

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000
Comparison Operators:
x = 5, y = 7
# Equal to (==) operator
print(f"x == y : {x == y}")

# Not Equal to (!=) operator


print(f"x != y : {x != y}")

# Greater than (>) operator


print(f"x > y : {x > y}")

# Less than (<) operator


print(f"x < y : {x < y}")

# Greater than or equal to (>=) operator


print(f"x >= y : {x >= y}")
Output:

x == y : False
x != y : True
x > y : False
x < y : True
x >= y : False
x <= y : True
a = True, b = False
logical_and = a and b
logical_or = a or b
logical_not_a = not a
logical_not_b = not b
print(f'a and b : {logical_and}')
print(f'a or b : {logical_or}')
print(f'not a : {logical_not_a}')
print(f'not b : {logical_not_b}')
Output:

a and b : False
a or b : True
not a : False
not b : True

You might also like