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

Python 2

The document provides an overview of basic data types in Python, including strings, integers, floats, and booleans, along with their operations and conversions. It explains how to handle user input, perform mathematical operations, and the importance of type conversion functions. Additionally, it covers the order of operations and the use of f-strings for formatting output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Python 2

The document provides an overview of basic data types in Python, including strings, integers, floats, and booleans, along with their operations and conversions. It explains how to handle user input, perform mathematical operations, and the importance of type conversion functions. Additionally, it covers the order of operations and the use of f-strings for formatting output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Data Types

Stuings
Code :
priat('23'" , 'use") Output!
123456
" In Python text ins ide
zuotes i's treated as a sting,
The 4' opeY atos wtn st ing s Cona
tena tes
adding them. Jet the Su m 59
them, ins tecd af
wee
with iateg ers, not strings need to Ork
IntegerS
An inte gey is ba sic data
a

numbe'
type YepYesen ting oh ole
from
negative to posibe
strings, which handle tex t, inclding teio Ualike
integ ers are Crafted for
numerc oper atio ns such as
addibon, subtrac tion mu itiplica tiog,
si on and
divi 5i0n and mnore
"With guotes ' (oncatenates ond ithout guote s adds.

with guotes called st ing and without guotes Called mteger


’ Babic Py thon Da ta Types

Egs: 4 strings,: Text ("Helto'")


2 Tntegers : Whole numbers ()
3. Flba ts: Decimal numbeYs (3"1)
4 Booleans : Tue br False va lues
’ Floating Point Numbers:
In Python, a floa t is a numerie da ta type
that
numbers uoth decimal points It's pes fec t for handles
precise,Caleulaton.
The term flpat" is shrt for loa ting- point number
" Even ust 70 is Seen as a Ploat not as in teg ex
’ Boole ans
In Py thon, when we need
clear cChoice be tween
q
two options - ike 'on' oY OfP Yes o
Mo' ts Colled
the boolean data
type. Boaleans allow us to
these binary condibons and represent
guides dur code rs dec's'ons
oi th rue' or Folse'.
’ Bool en in Py thon Teprese nt tuso
. I t stats wi{h a values.
capita le tter
Only two values exit: true
and Fa ls
while Tyue is a vald
boolean,
true is
Yeco gni 2ed as one
in Py thon

funct'on helps us determine the kind of data


stored in a var iable
Type Func tion
.5et vavia ble day s in- week to

" De tevmine its dato tpe using typel0,5aving to

data-tYpe
tyee
to reve al the
" print data- type

Code Outpu t
Lcla ss int'>
1 t Days in a week
days.in_ week :1
3
4. Get data type
S data- type ty pe (days. in- wee k)
6

Point the data type


8 print (da ta - type)

Dat a Ty pes with type ( )

upe()

(Kclass 'Str'> <Class' int') cClass float' > Cclass 'bepl')


Hello Truel Fal se

Type Convessibn

Type Conve rsibn funcions

"Str() floa t)) 6Dol(


string Ineger float Bosleae
In Python
are buik-in-funetions to change data
there
types int) foy inte gers, tloat) fo decimals str) os text,
and bool() for
3uoteh betueen
Thue/False values. These fune t'orns help easily
) Sting o Integes
Code:
#Stose23' as a s tring
2. numbestet = 23"
3"
4 Convert the s trin to arn integer
5* actual-number - int(number text)
6

?-#save the type, of the conves ted variable


3 data-type type (actual- number.

topxìnt the saved ty pe to cornfim converS0on


I|· priat (data type)

<classint'>

Decoding Uses Inpu b


Imagine f a uses inp uts n umber t23 whats the
actuar data type of that input ?
The inpu b) function In Py
thon always re turns data.
Qs a string (t),egardless of user's input:
Py thon trea ts user inpu t s tring by defaulb,
even if the input appear s numeric
Code:
1tGe L num be input fron the user
2. use- input : input ("ptea se
enter a numbe
3

4# Determine the data type of


user- input
5. input type type (use input)
6

7#print the data' ty pe


s' print(input type)
Output

enter number: 23
plea se
<closs 34y'

to floa t
i) Sthing
Code
dema number from the useT.
decimat number)
2. userinpu t inpu t (please entex a

4# onvert to floa t

S Con Ver ted input :floot (usev- input)


# tev mine the da ta type of converted-inpu-.
S Conver ted - type : type (coverted - input)

to # Displa y the deteymined data type


14: paintleonverted. type)
Ou tpub
Please enter a deinal numbey 12 3-4s
< cla ss ploat'

Sim phyfgins Coding


Instead of using tuo lines of code to get user input
and hen changing t, we Can do it all in just one hne
Je do this using the type fan ction float(), with the
InputU tuncton placed inside it
Egi 2 lines Code :

1. uses-input inpu(Enter a decimal numbes;")


2 Conver ted. input float (useYinpu t
1 line of Code : input piomp t
use'- float :float (input ("Enter a deimal numbes")
Vaniaple ype Funetion
0 cnVea
Code :
1"#Get and Conves t use nput to float
2. user- floot flbot (input (Enter a de cima! number' )
3
4 # Shouw dato type
S puint (ty pe (user- Ploo t))
6utput:
En tex a deaimol numbe
1234$
< chss float' >

Rules of ConvexsI0 n

int() Type Conversion

int ('i23') 123


Int (123+ 5") 123
int (True)
int (talse)
int (abe")
’ float() Type Conversion

foat (12345") 1234S


floa t (i23') I23"0
Ploet (r23) 123 O
float hello")
-’ St() Type lonvexsion

st (23) 123
st (23 s) l23-5a
sts (rue) "Tyue
Str (False) "False
Con vevsion
bool () Type
bool() funeton trans fos ms a value into a booleon,
The

either Tsue or False. Non -


empty values, Ii ke booi (ab)

Tr ue Frnp ty values tke bool Yeturns foi se .


vetuns

.when conves ting integexs, bol( retuns False, any


othey integex value, whèther postive o6 negative like boo) (c)
ve tusns Tsue

bool (abe") Tyue


boot (* ") False
bosl (o) False
bool Tsue
bool (-) Tyue
Mathematical Opera torS
"A ddition; Utilize Pytho'n's(+) opexato to
of numnbers
calculate S um

" Subtro ction: Pu


thon's G)ope vato makes Subtracing
nu mbes stYaightforward.
" Multplico tion; Py
thonhelps in pefoiming multiplic aton
tas ks efficientiy
using the ()pevato.
Division : ()opeatoris used for division in
Divi sin alwoy s produ ces a Python
Code
floa t ou tpu t by default.
Eg: Pa int ( sko/ 2) Output.:
60-0
" Modulo The mo
the dul o opera tor ( )
Yemain der ia Py thon provides
Eg
Code.
rint
after di vision
(1o. 3) brtpu t:
-Expongnt bpeva ter (a+):
The erpon en t, multiplies nunm bes by i tsele
a
repeatedyy
Code: butput:
Eg:
priat(a3)

fevcentage Caleulation

100/.
A $ 200 gadget i th a L0 dis tount touw much i S
saved
AnS To fnd o/. o 200 si mpy divide 1o by
1D0. and then
mu lt'ply this by 200, lke this:
Code
Outpub.
pvint (1o/1D0 * 200) 20"0

Solving Tules
" Py thon also folloues BoDMAS tyfe Tule (PEMDA)
Parentheses () broto

Want to make addition come


before mul tiplication in
Py th of
Eg: +3)*2
. By placing
paventheses avOund the a dditi on, you Can
ensue it gets calcula ted befove the
"Parentheses alays take top multiplicotion.
pro cessed even before priority' They ate
multipli ca ton and addi bion.
The oider Operations s
1" Pasentheses
3" Additiorn
2 Multipli cation
Orde of pe ration s:
Thitd feur t
Seo

)
E M D A

The priorrty order of operation 5 in


Python is decided
by PEMDAS Lohich i5 an
acTonym fov:
1" P -Parentheses get the high pviovit:
2 E Expenent comes next
3" m/p- Then, Multiplica tion and Divison in the
osder theu
4'A)5- Addition and Subtract'on, in the order
they appear.
Floot Divisio n in Py thon!
Floos divis 'on diides one numbe b9 andther, 6ut
instead of giving a decimal reSult, ?t
conver ts the
Outomne to a ohole numbey, dropping the decima
par t For ins tan Ce, shile | divided
give S 363, using loor division converts
just 3
Nomal diisi on
3666666-- 7

Floos divisi'on
/3 = 3
Code : Output
print(n13) 366666

prnt(u))3) elk 3
" Normal aivision gives
flogt as output
"Floor division gives
intege as outpu t
"int( function is another method to obta In t.
ohole numbey a Pter divi's'on.5peciically it onverte
de ci mal number to integ ev s by emoving de cimal,
Code : Output
umber =L/s
2 priat(numbe)
3 pviat(int (numbe)

Tbund() Function
In
Python,if you want to Yound numbeS
can se the round() functibn
For deinals below os, 1'llround douwn
" for decima's ike oS or hig he, it' Yound up

Code:
1 RDunding 3-d
2: print (Yound (3 ) o'teiv/ 3

4.# Rounding 3
S print(round (3))
4Rounding 36
8' pvint (Yound(-6))

Python f - strings
Ty peErvot tn Blling
19kile butlding a silllng system, you entoun
tered a
TypErroí hen trying to display the totaf bilh using
the follong code
Code:
1 tal: iso

2prins (our total bill is : tota )


Outpu t!
<Type F ro : Canno t Concatenate'sty and nt' obje cts
6n line 2>

Solution 1:
To fix it, convet to tal to
a String using sttta)
before Concatenation
Co de
print ("Yous totol bill is: "+ str (tota))
Solution 2:
Le t's leavn a bettet method to combine di
ffere nt
data ty pes without u sing conver sion me thod s
like.
str()
f-stingsns2h9re lerit

.F- sthings in Py thon provide a practic al and


easy way fovmat and combine differern t data tupts
oi thin a
single stving The y are Shos t fos
fos mat
st ing and are bettey in this case thon the str )
method
"An f-string begins ith
guo te fbefore i ts opening
wthin the sting, place any vaviable
ex pression ihin $
Python automatieally
as a sting, preventing the
typetyor.
Code :

1 to tal = so tunlg byac ke 4

2 priat (Your tatal bill is fto tal")


letter before varia ble |integer
opening uote
Output:
Your total bill is : 15o

|Rraject -2
E- Comnmes ce Product Price Calculator :

Designing a progrom tha t seamlessly calculates and


displays a produet's final price after applying a gien
discount'
Code :
1- # Poduet Price Caculator
2 onginat- pri'ce =toa t(input (" En tet origina Price:'))
3 discount- per cen t = foat (input ("Enter
disount ",.:"))
4: dis cOunt = d'scoun t t
amount
percent/roo* original- price
S final- price 6rqinalprice - di's coun ted- price
6 print('Final price af ter
faiscount_percen t/. ais count:
ttinal-.px ce?")n
Output:
9

Enter oiginal price :lo


En tey Dis count , I 0
Final pr'ce after l0- 07. discoun 90-0

You might also like