0% found this document useful (0 votes)
49 views28 pages

Python Basics: Variables & I/O Statements

The document provides an extensive overview of Python programming, covering its features, syntax, data types, operators, control statements, loops, and functions. It includes examples of variable assignments, output statements, and various operations such as arithmetic and comparison. Additionally, it discusses data structures like lists, tuples, dictionaries, and arrays, along with exercises for practice.

Uploaded by

GOD OF AMW
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)
49 views28 pages

Python Basics: Variables & I/O Statements

The document provides an extensive overview of Python programming, covering its features, syntax, data types, operators, control statements, loops, and functions. It includes examples of variable assignments, output statements, and various operations such as arithmetic and comparison. Additionally, it discusses data structures like lists, tuples, dictionaries, and arrays, along with exercises for practice.

Uploaded by

GOD OF AMW
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

Python

It is a cross-platform programming language


Developed by guido van rossum during 1985-1990.
Features -> Easy to learn, write, maintain, oops and Gui programming

Output statement
x=10; y="raja"
print "age = ",x
print "name = ",y
print x,y

multiline statement
a=10+20+\
50+10+\
20
print a
or using (), []

a=(10+20+
50+10+
20)
print a

a=['raja','mani',
'bala']
print a

comment
non exicutable statement
# sample prg
Multiline
“”” sample prg
For if stat “””

Variable and Data Types

In python don’t need to declare variable


Data type
Int
long
float
complex
string

Rules for variable name


 empno=111
× emp no=111
 emp_no=111
 empno1=111
× 1empno=111
× [Link]=111
 employeenumber=111
× print=111

value assingment
a=5
b=7.2
c=’raja’
print a,b,c

a,b,c=5,7.2,’raja’
print a,b,c

multiple assignment
a=b=c=100
print a,b,c

s1="csc computer education"


s2="villianur"
print s1
print s2
print s1+s2
print s1[0]
print s1[2:5]
print s1[:2]
print s1[2:]
print s1[-1]
print s1+ ' '+s2
print s2*2
print '-'*10

output
csc computer education
villianur
csc computer educationvillianur
c
cc
cs
c computer education
n
csc computer education villianur
villianurvillianur
----------

a=5
print (a, " type is ", type(a))
b=7.2
print (b, "type is ",type(b))

output
(5, ' type is ', <type 'int'>)
(7.2000000000000002, 'type is ', <type 'float'>)

Convertion data types


a=5
print float(a)
b=5.6
print int(b)

c='5.6'
#print c +5
print float(c)+5
d=45
#print 'age ' + d
print 'age ' + str(d)

output

5.0
5
10.6
age 45

Output Statement

print('hello world')
print("good")
print "happy"
print 'nice'
a=25
print a
print 'age = ' , a
print (1,2,3,4)
b=(5,6,7,8)
print b

output
hello world
good
happy
nice
25
age = 25
(1, 2, 3, 4)
(5, 6, 7, 8)

Input
m1=input('enter eng mark = ')
m2=input('enter tam mark = ')
m3=input('enter maths mark = ')
tot=m1+m2+m3
avg=tot/3.0;

print 'Total mark = ' , tot


print 'Average mark = ' ,avg

output
enter eng mark = 98
enter tam mark = 98
enter maths mark = 99

Total mark = 295


Average mark = 98.3333333333

x=raw_input("enter character = ")


y=raw_input("enter name = ")
print x
print y

output

enter character = y
enter name = muthu
y
muthu

Operators

Arithmatic

+
-
*
/
% -remainder
// - rounded value
** - power
a=15
b=4
print 'a+b = ',a+b
print 'a-b = ',a-b
print 'a*b = ',a*b
print '10/3 = ',10/3.0
print 'a%b = ',a%b
print '10//3 = ',10//3.0
print 'a**b = ',a**b

output
a+b = 19
a-b = 11
a*b = 60
10/3 = 3.33333333333
a%b = 3
10//3 = 3.0
a**b = 50625

comparison(Realation) operator

>
<
>=
<=
==
!=

a=15
b=4
print 'a>b = ', a>b
print 'a<b = ', a<b
print 'a>=b = ', a>=b
print 'a<=b = ', a<=b
print 'a==b = ', a==b
print 'a!=b = ', a!=b
output
a>b = True
a<b = False
a>=b = True
a<=b = False
a==b = False
a!=b = True

Assignment Operato

=
+=
-=
*=
/=
%=
//=
**=

Logical operator
and, or, not

Special operator

Is
Is not

a=15
b=15
c='raja'
d='raja'
print a is b
print a is not b
print c is d
print c is not d

output
True
False
True
False

Membership operator

In
not in

a='hello world'
b={1:'a',2:'b'}
print 'h' in a
print 'h' not in a
print 'H' in a
print 1 in b
print 'a' in b

output
True
False
False
True
False

Exercise:
 Find Area of rectangle
 Find Area of circle
 Get loan amt, interest rate, no of year, find due amt

Control statement

Contitional statement

If statement
If else statement
If elif statement
Nested if statement

Loop statement
While loop
For loop

If statement

If <Condition>:
Statements

a=input("enter a value = ")


if a>0:
print 'given number is +ve'

If else statement

If <condition>:
Statements
else:
statements

a=input("enter a value = ")


b=input("enter b value = ")
if a>b:
print 'a is great'
else:
print 'b is great'

Exercise:
 Given no is +ve/-ve
 Given no is odd/even
 Given two numbers are same/not
 Given age is eligible for voter/not
 Given character is vowel or not
 Given age is teen age or not
 Get 3 marks, Find Total, average, result

Nested if statement

a=input("enter a value = ")


if a>0:
print "Given no is +ve"
else:
if a<0:
print "Given no -ve"
else:
print "Given no is zero"

Exercise:
 Great of 3 numbers

If elif statement

If <cond>:
Statements
elif <cond>:
statements
elif <cond>:
statements
--
else:
statements

a=input("enter a value = ")


if a>0:
print "Given no is +ve"
elif a<0:
print "Given no -ve"
else:
print "Given no is zero"

Exercise:

1) Find age status


Age<=5 -> child
6 to 12 -> boy/girl
13 to 20 -> teen age
21 to 50 -> middle age
>50 -> old age
2) Find bonus based on salary
Salary <=10000 -> 2000
10001 to 20000 ->3000
20001 to 30000 -> 4000
>30000 -> 5000
3) convert day of week from number to character

While loop

While <condition>:
Statements

a=1
while a<=5:
print "csc"
print "villianur"
a=a+1

while with else


a=1
while a<=5:
print a
a=a+1
else:
print "end"
print "Thank you"

output
1
2
3
4
5
end
Thank you

Exercise:

 Print 1,2,3,…..10
 Print 1,2,3,…..n
 Print 1,3,5,….n
 Print 2,4,6,….n
 Print 10,9,8,…1
 Sum 1+2+3….n
 Sum 1+3+5….n
 Find factorial 1*2*3….n
 Sum 1-2+3-4+5-6….100
for loop

for <variable> in <range/sequence>:


statements

range(st value, end value, step value)

for a in range(1,10,):
print a
output -> 1 to 9

for a in range(1,10,2):
print a

output -> 1 3 5 7 9

for a in range(2,10,2):
print a

output -> 2 4 6 8

for a in range(10,0,-1):
print a

output -> 10 9 8 .. 1

sequence(string,list,tuple,dictionary,array)

for a in "csc":
print a

output
c
s
c
a=[10,20,30,40,50,7.2,'csc']
for i in a:
print i

output
10
20
30
40
50
7.2
csc

break and continue statement

for a in range(1,11,1):
if a==5: continue
print a
if a==7:
break
else:
print "end"
print "Thank you"

output
1
2
3
4
6
7
Thank you
.0
Exercise:

 Find given no is prime/not


 Print prime no upto 100
 Print fibnocci series
 Sum the digits 457 – 16
 Print the digits
 Reverse the no.
 Print only odd nos from list
 Sum the list

Sequences

LIST

List is an ordered sequence of different type of item


It is given within []

a=[10,20,3.3,4.5,7.3,"csc","villianur"]
"""print a
print a[1]
print a[:3]
print a[3:]
print a[2:4]
print a[:]
print a[-1] """

""" change
a[0]=5
print a
a[1:4]=[6,7,8]
print a """

""" add
[Link](10)
print a
[Link]([7,8,8])
print a
[Link](1,55)
print a
a[2:2]=[77,88]
print a """

""" delete
del a[2]
print a
del a[1:4]
print a
del a
[Link]("csc")
print a
[Link](1)
print a """

""" other function


print [Link](20)
print [Link](20)
print len(a)
print max(a)
print min(a)
[Link]()
print a
[Link]()
print a """

Tuple

tuple is an ordered sequence of different type of item like a list


Item cannot be alter(immutable)
It is given within ()

a=(10,20,30,40)
print a[1]=99  error

Dictionary

Collection of unordered collection os key-value pairs


Key:value

a={1:'sun',2:'moon','sky':100}
print a
print ("a[1] = ", a[1])
print ("a[2] = ", a[2])
print ("a['sky'] = ", a['sky'])
print ("a[100] = ", a[100])
output
{1: 'sun', 2: 'moon', 'sky': 100}
('a[1] = ', 'sun')
('a[2] = ', 'moon')
("a['sky'] = ", 100)
Traceback (most recent call last):
File "D:\soft\sara\ex2", line 6, in -toplevel-
print ("a[100] = ", a[100])
KeyError: 100

ARRAY
Collection of same type values

from array import *


typecode -> i –int, f – float, l –long , d –double, c- char

ar=array('i',[5,10,15,20,25])
for b in ar:
print b

print ar[2]

add
[Link](30)
print ar

[Link](0,40)
print ar

ar2=array('i',[30,35,40,45])
[Link](ar2)
print ar

c=[40,45,50]
[Link](c)
print ar
delete

[Link](10)
print ar

[Link]()
[Link](1)
print ar

other function

print [Link](10)
[Link]()
print ar
print [Link](10)

Convert array to string, list

b=array('c',['r','a','j','a'])
print [Link]()
c=[Link]()
print c

Function

Types
 Udf
 Buit in function

Udf (user defined function)

def functionname(parameter1,para2,arg3,…):
-----

-----
-----
Functionname(para1, arg2,..)

#example without parameter and without return value


def display():
print 'csc welcomes you'
print 'villianur'

print 'hello student'


display()
print 'thank you'

output
hello student
csc welcomes you
villianur
thank you

#example with parameter and no return value


def add(a,b):
print a+b
def sub(a,b):
print a-b
def mul(a,b):
print a*b
def div(a,b):
print a/b

a=10
b=3
add(a,b)
sub(a,b)
mul(a,b)
div(a,b)
add(5,5)
add(a,5)
print 'thank you'

output
13
7
30
3
10
15
thank you

#example with parameter and with return value


def great(a,b):
if a>b:
g=a
else:
g=b
return(g)

a=10
b=3
c=great(a,b)
print c
print great(67,89)
print 'thank you'

output
10
89
thank you

#example without parameter and with return value


def great():
a=input("Enter a value = ")
b=input("Enter b value = ")
if a>b:
g=a
else:
g=b
return(g)

c=great()
print c
print great()
print 'thank you'

output
Enter a value = 6
Enter b value = 8
8
Enter a value = 99
Enter b value = 33
99
thank you

#function to find vowels


def vowel(st):
v=0
for i in st:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
v=v+1
return(v)

st=input("enter name = ")


print 'No of vowels = ', vowel(st)

output
enter name = 'computer'
No of vowels = 3

Exercise:
 Write function for swap two numbers
 Write function for factorial
 Write function to find simple interest Si=pnr/100

Function with default argument

def sum(x=10,y=20,z=30):
return(x+y+z)

print sum(5,5,5)
print sum(5,5)
print sum(5)
print sum()

output
15
40
55
60

Arbitary arguments

def display(*x):
for na in x:
print "hello ",na

display('raja','mani','muthu','arun')

output
hello raja
hello mani
hello muthu
hello arun

Formal and arbitary argument

def display(x,*y):
print 'formal arg ' ,x
for na in y:
print "another arg ",na

display('raja','mani','muthu','arun',5000)

output
formal arg raja
another arg mani
another arg muthu
another arg arun
another arg 5000

Recursion function

def fact(x):
if x==1:
return 1
else:
return(x*fact(x-1))

n=input("enter n value = ")


print 'factorial of ',n, ' is ', fact(n)

output
enter n value = 5
factorial of 5 is 120

Files

It is used to store data permanently


To Open
f=open(filename,mode)
mode -> r, w,a, bw,br,r+,w+

Read

f=open(“[Link]”,”r”)
print [Link](5) -> print first 5 char from [Link]
print [Link]() - >print remaining char from [Link]
[Link](0) -> move cursor to starting position of file
print [Link]()  print cursor position of file

for i i
print i
 Read line by line

print [Link]() -> print first line


print [Link]() -> print remaining lines

To close
[Link]()

Write

f=open(“[Link]”,”w”)
[Link](“csc\n”)
[Link](“computer\n”)
[Link](“education\n”)

f=open("[Link]","w")
ch='y'
while ch=='y':
x=raw_input("Enter name = ")
[Link](x + "\n")
ch=raw_input("continue = ")
[Link]()
Binary files
Using dictionary

import pickle
f=open("[Link]","w")
c={1001:['raja','dca',7500],1002:['mani','hdca',12500]}
[Link](c,f)
[Link]()

f1=open("[Link]","r")
c1=dict([Link](f1))
[Link]()

r =input("Enter no = ")
for id,cc in [Link]():
if id==r:
print 'name = ', cc[0]
print 'balance fees = ' , cc[2]
amt=inp c1[id]=[cc[0],cc[1],cc[2]-amt]
f1=open("[Link]","w")
print c1
[Link](c1,f1)
[Link]()

output
Enter no = 1001
name = raja
balance fees = 7500
E nter amount = 2500
{1001: ['raja', 'dca', 5000], 1002: ['mani', 'hdca', 12500]}

using List

import pickle
f=open("[Link]","w")
c=[[1001,'raja','dca',7500],[1002,'mani','hdca',12500]]
[Link](c,f)
[Link]()
f1=open("[Link]","r")
c1=list([Link](f1))
[Link]()

r=int(input("Enter no = "))
for i in c1:
if i[0]==r:
print 'name = ', i[1]
print 'balance fees = ' , i[3]
amt=input("Enter amount = ")
i[3]=i[3]-amt
break;

print c1
f1=open("[Link]","w")
[Link](c1,f1)
[Link]()

output
Enter no = 1001
name = raja
balance fees = 7500
Enter amount = 2500
[[1001, 'raja', 'dca', 5000], [1002, 'mani', 'hdca', 12500]]

Directory

import os
print [Link]()
[Link]('d:\\anbu')
print [Link]()
print [Link]('d:\\tani')
[Link]('sun')
[Link]('sun','moon')
[Link]('[Link]')
[Link]('moon') #rmdir removes only empty directry
to remove non-empty directry use rmtree in shutil module

import shutil
[Link]('sun')

exception

error(syntax,logic,runtime)
try:
stataments
except exp1:
statements
except exp2:
statements
else:
statements

try:
a,b=input("enter two values = ")
c=a/b
print c
except ZeroDivisionError:
print 'Dont divide by zero'
except SyntaxError:
print 'comma is missing'
except:
print 'wrong input'
else:
print 'no error'
output
enter two values = 10,3
3
no error

enter two values = 10 3


comma is missing

enter two values = 10,0


Dont divide by zero

enter two values = 10,y


wrong input

try:
f=open("[Link]","r")
print [Link]()
[Link]()
except IOError:
print 'file not found'

user defined exception

class MyError(Exception):
pass
class ZeroValueError(Exception):
pass
try:
n=input("enter n value = ")
if n==0:
raise ZeroValueError
if n<0:
raise MyError
else:
print n
except MyError:
print 'Give positive no'
except ZeroValueError:
print 'Dont give zero'

output
enter n value = 5
5

enter n value = 0
Dont give zero

enter n value = -3
Give positive no

Common questions

Powered by AI

Control statements such as 'if-else' and loops in Python enhance logical flow and decision-making by directing the execution path according to conditions and repetitions. 'If-else' statements allow a program to make decisions based on conditions, executing different blocks of code based on boolean evaluations. Loops, like 'for' and 'while', allow repetitive execution of code blocks, facilitating tasks like traversing data structures or implementing repetitive procedures without manual repetition, thus reducing error and enhancing efficiency .

Python handles arithmetic and comparison operations by attempting to convert operands to a common compatible type, often resulting in type promotion (e.g., implicit conversion of integers to floats in mixed-type expressions). Arithmetic involving distinct types leads to outcomes based on the highest precision type (e.g., an int and float yields a float). Comparisons between incompatible types result in errors unless handled explicitly via type conversion functions. This automatic type management ensures a degree of flexibility and reduces type-related errors but requires careful consideration to prevent unexpected results .

Python uses dynamic typing, meaning you do not need to declare the type of a variable at the time of its declaration; the interpreter assigns data types automatically based on the value assigned to the variable. This differs from statically typed languages where you must specify the variable type explicitly. For instance, assigning 'a=5' automatically makes 'a' an integer type, and you can reassign 'a' to a float or string later without any syntax errors .

Recursive functions in Python are significant when a problem can be broken down into smaller, similar subproblems, like computing factorials or generating Fibonacci series. They simplify code and promote logical clarity by eliminating the need for complex looping constructs. However, they can lead to potential pitfalls such as excessive memory usage and stack overflow errors if the recursion depth exceeds a certain limit, which must be cautiously managed using base cases and tail-recursion optimizations when necessary .

When using loops, 'break' and 'continue' serve distinct purposes. 'Break' is used to terminate the loop when a desired condition is met, preventing further iterations, which is useful when the loop satisfies the task prematurely. 'Continue' skips the current iteration and moves to the next, useful when certain loop cycles need to be bypassed without stopping the loop entirely. Choosing between them depends on whether the task requires complete exit from the loop or merely skipping processing within the current loop .

Lists are mutable, meaning their elements can be changed, deleted, or added, whereas tuples are immutable, meaning once a tuple is created, it cannot be modified. This immutability of tuples makes them more suitable for fixed data collections where data integrity is critical, preventing accidental alterations during program execution. On the other hand, lists offer more flexibility and are more suitable for scenarios where data needs to be modified or dynamically managed .

Python's file handling enables persistent data storage by allowing programs to read from and write to files stored on a disk. Typical operations include opening a file in different modes ('r', 'w', 'a', 'r+', etc.), reading data using methods like 'read' and 'readlines', writing data using 'write' methods, and closing files to ensure there are no data leaks. This approach allows applications to maintain state or logs across sessions, providing a seamless user experience by persisting user preferences, configurations, or execution logs .

Exception handling in Python is crucial for managing runtime errors, which allows a program to continue executing by catching errors and preventing a complete crash. Scenarios include handling division by zero, file not found errors, and invalid user input. By using try-except blocks, developers can specify responses to different exceptions, make their code error-resistant, and improve usability by providing informative error messages or default actions instead of abrupt terminations .

User-defined functions in Python allow programmers to encapsulate reusable code for specific tasks, enhancing modularity and readability. They are implemented using the 'def' keyword and can have parameters that generalize tasks for various inputs. For instance, a function to calculate simple interest for varying principal amounts and rates would be preferable over built-in functions as it is specific to the application's needs. User-defined functions tailor functionality in ways built-in functions cannot, supporting custom operations unique to the user's problem domain .

Python's membership operators 'in' and 'not in' are used to test whether a value or variable is found in a sequence (e.g., strings, lists, tuples, or dictionaries), addressing problems related to element verification. For example, checking if a specific character exists in a string. Meanwhile, logical operators such as 'and', 'or', and 'not' are used to combine conditional statements, addressing logical flow control problems. Membership operators focus on item presence, whereas logical operators evaluate boolean expressions .

You might also like