0% found this document useful (0 votes)
99 views27 pages

Python Basic Data Types

Here are the programs to solve the given problems: 1. To create a list where size and items are given by user and display product: size = int(input("Enter size of list: ")) list1 = [] for i in range(size): item = int(input("Enter item: ")) list1.append(item) product = 1 for num in list1: product = product * num print("Product of list items is:", product) 2. To find string in list and replace it with user input string: list2 = ['abc', 100, 'xyz', 'pqr', 200] old_string = input("Enter string to

Uploaded by

Akansha Uniyal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
99 views27 pages

Python Basic Data Types

Here are the programs to solve the given problems: 1. To create a list where size and items are given by user and display product: size = int(input("Enter size of list: ")) list1 = [] for i in range(size): item = int(input("Enter item: ")) list1.append(item) product = 1 for num in list1: product = product * num print("Product of list items is:", product) 2. To find string in list and replace it with user input string: list2 = ['abc', 100, 'xyz', 'pqr', 200] old_string = input("Enter string to

Uploaded by

Akansha Uniyal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 27

Python Basics

Python Built-in Core Data Types


Python offers following built-in core data types :
i) Numbers ii) String iii) List iv) Tuple v) Dictionary

Built-in Core Data Types

Numbers String List Tupl Dictionary


e
Floating-Point Complex
Integers
Numbers Numbers

Integers(Signed)

Boolean
Integers

Integers are whole numbers. They have no fractional parts.


Integers can be positive or negative.
There are two types of integers in Python:
i) Integers(Signed) : It is the normal integer representation
of whole numbers using the digits 0 to 9. Python provides
single int data type to store any integer whether big or
small. It is signed representation i.e. it can be positive or
negative.
ii)Boolean : These represent the truth values True and False.
It is a subtype of integers and Boolean values True and
False corresponds to values 1 and 0 respectively
Demonstration of Integer Data
Type
#Demonstration of Integer-Addition of two integer
number a=int(input("Enter the value of a:"))
b=int(input("Enter the value of
b:")) sum=a+b
print("The sum of two
integers=",sum)

Output:
Enter the value of a: 45
Enter the value of b:
67
The sum of two
integers= 112
Floating Point Numbers
A number having fractional part is a floating point
number. It has a decimal point. It is written in two forms :
i) Fractional Form : Normal decimal notation e.g. 675.456
ii) Exponent Notation: It has mantissa and
exponent. e.g. 6.75456E2
Advantage of Floating point numbers:
They can represent values between the integers.
They can represent a much greater range of values.
Disadvantage of Floating point numbers:
Floating-point operations are usually slower than
integer operations.
Demonstration of Floating Point Data
Type
#Demonstration of Float Number- Calculate Simple Interest
princ=float(input("Enter the Principal Amount:"))
rate=float(input("Enter the Rate of interest:"))
time=float(input("Enter the Time period:"))
si=(princ*rate*time)/100
print("The Simple Interest=",si)

Output:
Enter the Principal
Amount:5000 Enter the Rate of
interest:8.5 Enter the Time
period:5.5 Simple Interest=
2337.5
Strings
A String is a group of valid characters enclosed in Single or
Double quotation marks. A string can group any type of
known characters i.e. letters ,numbers and special characters.
A Python string is a sequence of characters and each
character can be accessed by its index either by forward
indexing or by backward indexing.
e.g. subj=“Computer”

Forwar d indexing 0 1 2 3 4 5 6 7
Subj C o m p u t e r
-8 -7 -6 -5 -4 -3 -2 -1 B
ackward indexing
Demonstration of String Data Type
#Demonstration of String- To input string & print
it my_name=input("What is your Name? :")
print("Greetings!!!")
print("Hello!",my_name)
print("How do you
do?")

Output :
What is your Name? :Ananya
Greetings!!!
Hello! Ananya
How do you do?
Functions
Method Description
capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a


string
encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

find() Searches the string for a specified value and returns the
position of where it was found
Method Description
format() Formats specified values in a string

index() Searches the string for a specified value and returns the
position of where it was found
isupper() Returns True if all characters in the string are upper case

lower() Converts a string into lower case

replace() Returns a string where a specified value is replaced with


a specified value
upper() Converts a string into upper case

find() Searches the string for a specified value and returns the
position of where it was found
To accept a number and change it into
Upper case
txt = "Hello my friends"

x = txt.upper()

print(x)
Print EVEN length words of a string
# declare, assign string
str = "Python is a programming language"
# extract words in list
words = list(str.split(' '))
# print string
print("str: ", str)
# print list converted string i.e. list of words
print("list converted string: ", words)
# iterate words, get length
# if length is EVEN print word
print("EVEN length words:")
for w in words: str: Python is a programming language
if(len(w)%2==0 ): list converted string: ['Python', 'is', 'a', 'programming', 'language']
EVEN length words:
print(w)
Python
is
language
Print words with their length of a string
def splitString (str):
# split the string by spaces
str = str.split (' ')
# iterate words in string
for words in str:
print(words," (", len (words), ")")
# Main code
# declare string and assign value
Hello ( 5 )
str = "Hello World How are you?"
World ( 5 )
How ( 3 )
# call the function are ( 3 )
splitString(str) you? ( 4 )
Complex Number
Python represents complex numbers in the form a+bj.

#Demonstration of Complex Number- Sum of two


Complex Numbers
a=7+8j
b=3.1+6j
c=a+b
print("Sum of two Complex Numbers")
print(a,"+",b,"=",c)
Output:
(7+8j) + (3.1+6j) = (10.1+14j)
z = complex(5, 7)
print("Output:", z)
Output: (5+7j)
z = complex(3)
print("Output:", z)
# Output: (3+0j)
z = complex()
print("Output:", z)
# Output: 0j
z = complex('1+1j')
print("Output:", z)
# Output: 1+1j
z = complex(1, -4)
print("Output:", z)
# Output: 1-4j
List

The List is Python’s compound data type.


A List in Python represents a list of comma
separated values of any data type between
square brackets.
Lists are Mutable
thislist = ["apple", "banana", "cherry"]
print(thislist)

['apple', 'banana', 'cherry', 'apple', 'cherry']


# to access an item
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
# to change an item
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

# to append an item at the end


thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
#Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Program to Join two lists

List1=eval(input("Enter Elements for List 1:"))


List2=eval(input("Enter Elements for List 2:"))
List=List1+List2
print("List 1 :",List1) eval() function evaluates the
print("List 2 :",List2) specified expression, if the
print("Joined List :",List) expression is a legal Python
statement, it will be executed.

Output:
Enter Elements for List 1:[12,78,45,30]
Enter Elements for List 2:[80,50,56,77,95]
List 1 : [12, 78, 45, 30]
List 2 : [80, 50, 56, 77, 95]
Joined List : [12, 78, 45, 30, 80, 50, 56, 77, 95]
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(5,10))
[5, 6, 7, 8, 9]
>>> list(range(5, 10, 3))
[5, 8]
Python program to sum all the items in a list.

total = 0 Sum of all elements in given


list: 74
# creating a list
list1 = [11, 5, 17, 18, 23]

# Iterate each element in list


# and add them in variable total
for s in range(0, len(list1)):
total = total + list1[s]

# printing total value


print("Sum of all elements in given list:
", total)
Sort a list
• cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

['BMW', 'Ford', 'Volvo']


thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
['apple', 'banana', 'cherry']

Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)
Tupl
e
The Tuple is Python’s compound data type. A Tuple in
Python represents a list of comma separated values of any
data type Within parentheses. Tuples are Immutable.
#Demonstration of Tuple- Program to input 2 tuple & join
it
tuple1=eval(input("Enter Elements for Tuple 1:"))

tuple2=eval(input("Enter Elements for Tuple 2:"))


Tuple=tuple1+tuple2
print("Tuple 1 :",tuple1)
print("Tuple 2 :",tuple2)
print("Joined Tuple :",Tuple)
Output:
Enter Elements for Tuple 1:(12,78,45,30)
Enter Elements for Tuple 2:(80,50,56,77,95)
Tuple 1 : (12, 78, 45, 30)
Tuple 2 : (80, 50, 56, 77, 95)
1. Write a pyhton program to create a list where size
of the list and Items are given by user and then
display its product.
2. Write a python program to find and display the
string values in the list and then replace it by
another string provided by the user
Dictionar
y
Dictionaries are unordered collection of elements in curly braces in the form of
a key:value pairs that associate keys to values. Dictionaries are Mutable. As
dictionary elements does not have index value ,the elements are accessed
through the keys defined in key:value pairs.
#Demonstration of Dictionary- Program to save Phone nos. in dictionary &
print it
Phonedict={"Madhav":9876567843,"Dilpreet":7650983457,"Murugan":906720
8769,"Abhinav":9870987067}
print(Phonedict)
Output:
{'Madhav': 9876567843, 'Dilpreet': 7650983457, 'Murugan': 9067208769,
'Abhinav': 9870987067}

You might also like