0% found this document useful (0 votes)
12 views9 pages

Unit 1st Revised Python 12 2024-2025

This document provides an overview of Python programming, covering its basics, keywords, operators, control statements, and data structures like lists, tuples, and dictionaries. It includes examples of syntax and output for various operations, as well as common questions and answers related to Python programming concepts. The content is structured to facilitate understanding of Python for beginners.

Uploaded by

sambhavy735
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)
12 views9 pages

Unit 1st Revised Python 12 2024-2025

This document provides an overview of Python programming, covering its basics, keywords, operators, control statements, and data structures like lists, tuples, and dictionaries. It includes examples of syntax and output for various operations, as well as common questions and answers related to Python programming concepts. The content is structured to facilitate understanding of Python for beginners.

Uploaded by

sambhavy735
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/ 9

UNIT 1 : PROGRAMMING AND COMPUTATIONAL THINKING – 2

CHAPTER 1: REVISION OF THE BASICS OF PYTHON


 Python (a computer language) :
 Python is a powerful and high level language and it is an interpreted language.
 It is widely used general purpose, high level programming language developed by Guido van Rossum in 1991.
 Python has two basic modes: interactive and script.In interactive mode (python.exe/py.exe), the result is returned
immediately after pressing the enter key. In script mode (IDLE), a file must be created and saved before executing
the code to get results.
Basics of Python: Output
Simple Hello world Program Output
print('hello world') hello world
print("HELLO WORLD") HELLO WORLD
Declaring/Defining variable Output
a=10 30
b=20 23
c=a+b
print(c)
d,e=2,3
print(d,e)
Output Formatting Output
a,b=10,20 The addition of a and b is 30
c=a+b The addition of 10 and 20 is 30
print("The addition of a and b is ", c) The addition of 10 and 20 is 30
print("The addition of ",a,"and ", b, "is ",c)
print("The addition of %d and %d is %d" %(a,b,c))
name="XYZ" Output
age=26 The age of XYZ is 26 and salary is 65748.93
salary=65748.9312
print("The age of %s is %d and salary is %.2f"%(name,age,salary))
Basics of Python: Input
Accepting input without prompt Output
name=input() Govind
print(name) Govind
Accepting input with prompt Output
name=input(“Enter your name : ") Enter your name : Govind
print("My name is ",name) My name is Govind

Accepting formatted input (Integer, float, etc.) Output


a=int(input("Enter any integer number :")) Enter any integer number :10
b=float(input("Enter any float number :")) Enter any float number :3.14
print("Entered integer is : ",a) Entered integer is : 10
print("Entered float is : ",b) Entered float is : 3.14

Keywords in Python
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time. All the keywords except True, False and
None are in lowercase and they must be written as it is. The list of all the keywords is given below.
and del from not while as elif global or with assert else if pass yield
break except import print class exec in raise continue finally is return def for
lambda try
Operators in Python
Python language supports the following types of operators-
• Arithmetic Operators
• Relational Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Operators in Python: Arithmetic
Assume a=10 and b=20

Operators in Python: Relational

Relational Operators are used to show relationship between two values or variables. Following are the relational operators
< (less than), >(greater than) , <= (less than equal to), >= (greater than equal too) ,!= (Not equal to) and = = (equality check
operator)
Logical Operator in Python
Operators in Python: Assignment

Operators in Python: Bitwise

Bitwise operator works on bit and performs bit by bit operation. Assume if –
A=60 and B=13; now in binary they will be as follows
A(60)=00111100
B(13)=00001101

a&b = 0000 1100 (Use of bitwise Binary


AND) a|b = 0011 1101 (Use of bitwise Binary
OR) a^b = 0011 0001 (Use of bitwise XOR)
~a = 1100 0011 (Use of ones complement)
Operators in Python: Membership

list=[1, 2, 3, 4, 5] Output
print("Elements in the list: ",list) if(3 in list): Elements in the list: [1, 2, 3, 4, 5] 3 available in the list
print(3, "available in the list") else:
print(3, "Not available in the list")

Operators in Python: Identity

a,b = 20,20 Output


print("ID of a :",id(a)," ID of b :",id(b)) if(a is b): ID of a : 1442604432 ID of b : 1442604432
print("a and b have same identity") else: a and b have same identity
print("a and b do not have same identity")
Control Statements in Python
Control statements are used to control the flow of execution depending upon the specified condition/logic.
There are three types of control statements-
1. Decision Making Statements (if, elif, else)
2. Iteration Statements (while and for Loops)
3. Jump Statements (break, continue, pass)
Decision Making Statements Program Output
(if, elif, else) a=int(input("Enter any integer number :")) Enter any integer number :5
Syntax: if(a==0): Number is Positive
if(logic): print("Number is Zero")
Statement/s elif(a>0):
elif(logic): print("Number is Positive")
Statement/s else:
else: print("Number is negative")
Statement/s
Iteration Statements (while loop) Program Output
Syntax: n=1 Govind Govind Govind
while(condition): while(n<4):
Statement/s print("Govind ", end=“ ")
n=n+1

Iteration Statements (for loop) Program Output


Syntax: for i in range(1,6): 12345
for value in sequence: print(i, end=' ')
Statement/s

Jump Statements Program Output


(break, continue, pass) for i in range(1,11): 1 2 hello 4 6 7
Syntax if(i==3):
for val in sequence: print("hello", end=' ')
if (val== i): continue
break if(i==8):
if (val== j): break
continue if(i==5):
if (val== k): pass
pass else:
print(i, end=' ');

List in Python
Creating a list and accessing its elements Output
a=[10,20,'abc',30,3.14,40,50] [10, 20, 'abc', 30, 3.14, 40, 50]
print(a) 10 20 abc 30 3.14 40 50
for i in range(0,len(a)): 50 40 3.14 30 abc 20 10
print(a[i], end=' ') 50 40 3.14 30 abc 20 10
print('\n') 50 40 3.14 30 abc 20 10
for i in range(len(a)-1,-1,-1):
print(a[i], end=' ')
print('\n')
for i in a[::-1]:
print(i, end=' ')
print('\n')
for i in reversed(a):
print(i, end=' ')

Tuple in Python

It is a sequence of immutable objects. It is just like a list. Difference between a tuple and a list is that the tuple cannot be
changed like a list. List uses square bracket whereas tuple use parentheses.
L=[1,2,3,4,5] Mutable Elements of list can be changed
T=(1,2,3,4,5) Immutable Elements of tuple can not be
changed
Creating a tuple and accessing its elements Output
a=(10,20,'abc',30,3.14,40,50) (10, 20, 'abc', 30, 3.14, 40, 50)
print(a) 10 20 abc 30 3.14 40 50
for i in range(0,len(a)): 50 40 3.14 30 abc 20 10
print(a[i], end=' ') 50 40 3.14 30 abc 20 10
print('\n') 50 40 3.14 30 abc 20 10
for i in range(len(a)-1,-1,-1):
print(a[i], end=' ')
print('\n')
for i in a[::-1]:
print(i, end=' ')
print('\n')
for i in reversed(a):
print(i, end=' ')

Function Description

tuple(seq) Converts a list into a tuple.

min(tuple) Returns item from the tuple with min value.

max(tuple) Returns item from the tuple with max value.

len(tuple) Gives the total length of the tuple.

cmp(tuple1,tuple2) Compares elements of both the tuples.

Dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store data values along with the keys. Dictionary holds key:
value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by
a colon:, whereas each key is separated by a ‘comma’.
dict={ “a": “alpha", “o": “omega", “g": ”gamma” }

# Creating an empty Dictionary Output


Dict = {} Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict) Dictionary with the use of Integer Keys:
{1: ‘AAA', 2: ‘BBB', 3: ‘CCC'}
# Creating a Dictionary with Integer Keys Dictionary with the use of Mixed Keys:
Dict = {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'} {'Name': 'Govind', 1: [10, 11, 12, 13]}
print("\nDictionary with the use of Integer Keys: ") Dictionary with the use of dict():
print(Dict) {1: 'AAA', 2: 'BBB', 3: 'CCC'}
Dictionary with each item as a pair:
# Creating a Dictionary with Mixed keys {1: 'AAA', 2: 'BBB'}
Dict = {'Name': ‘Govind', 1: [10, 11, 12, 13]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary with dict() method


D=dict({1: 'AAA', 2: 'BBB', 3:'CCC'})
print("\nDictionary with the use of dict(): ")
print(D)

# Creating a Dictionary with each item as a Pair


D=dict([(1, 'AAA'), (2, 'BBB')])
print("\nDictionary with each item as a pair: ")
print(D)
# Creating an empty Dictionary Empty Dictionary:
Dict = {} {}
print("Empty Dictionary: ") Dictionary after adding 3 elements:
print(Dict) {0: 'Govind', 2: ‘Prasad', 3: ‘Arya’}
Dictionary after adding 3 elements:
# Adding elements one at a time {{0: 'Govind', 2: ‘Prasad', 3: ‘Arya’} , 'V': (1, 2,)}
Dict[0] = ‘Govind' Updated dictionary:
Dict[2] = ‘Prasad' {{0: 'Govind', 2: ‘Prasad', 3: ‘Arya’} , 'V': (3, 4,)}
Dict[3] = ‘Arya’
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# to a single Key
Dict['V'] = 1, 2
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[‘V’] = 3,4
print("\nUpdated dictionary: ")
print(Dict)
# Creating a Dictionary Output
D = {1: ‘Prasad', 'name': ‘Govind', 3: ‘Arya'} Accessing a element using key:
Govind
# accessing a element using key Accessing a element using key:
print("Accessing a element using key:") Prasad
print(D['name']) Accessing a element using get:
Arya
# accessing a element using key
print("Accessing a element using key:")
print(D[1])

# accessing a element using get() method


print("Accessing a element using get:")
print(D.get(3))
D={1:'AAA', 2:'BBB', 3:'CCC'} Output
print("\n all key names in the dictionary, one by one:") all key names in the dictionary, one by
for i in D: one: 1 2 3
print(i, end=' ') all values in the dictionary, one by one:
print("\n all values in the dictionary, one by one:") AAA BBB CCC
for i in D: all keys in the dictionary using keys() method:
print(D[i], end=' ') 123
print("\n all keys in the dictionary using keys() method:") all values in the dictionary using values() method:
for i in D.keys(): AAA BBB CCC
print(i, end=' ') all keys and values in the dictionary using
items()method:
print("\n all values in the dictionary using values() method:") 1 AAA 2 BBB 3 CCC
for i in D.values():
print(i, end=' ')
print("\n all keys and values in the dictionary using
items()method:")
for k, v in D.items():
print(k, v, end=' ')

Very Short Answer Type Questions (1-Mark)

Q1. What is None literal in Python?


Ans: Python has one special literal called “None”. It is used to indicate something that has not yet been created. It is a legal
empty value in Python.
Q2.Can List be used as keys of a dictionary?
Ans: No, List can’t be used as keys of dictionary because they are mutable. And a python dictionary can have only keys of
immutable types.
Short Answer Type Questions (2-Marks)

Q1. What is a python variable? Identify the variables that are invalid and state the reason
Class, do, while, 4d, a+
Ans: - A variable in python is a container to store data values.
a) do, while are invalid because they are python keyword
b) 4d is invalid because the name can’t be started with a digit.
c) a+ is also not validas no special symbol can be used in name except underscore ( _ ).

Q.2 Predict the output


for i in range( 1, 10, 3):
print(i)
Ans: - 1
4
7
Q3. Rewrite the code after correcting errors: -
if N=>0
print(odd)
else
Print("even")

Ans: - if N>=0:
print(“odd”)
else:
print("even")
Q.4 What problem occurs with the following code
X=40
while X< 50 :
print(X)
Ans: - The given code does not have the incrementing value of X, thus the loop becomes endless.
Q5. What will be the output of the following code snippet?
values =[ ]
for i in range (1,4):
values.append(i)
print(values)
Ans: [1]
[1 ,2 ]
[1,2,3]
Q6. Find the error in following code. State the reason of the error.
aLst = { ‘a’:1 ,' b':2, ‘c’:3 }
print (aLst[‘a’,’b’])
Ans: The above code will produce KeyError, the reason being that there is no key same as the list [‘a’,’b’] in dictionary
aLst.
Application Based Questions ( 3 Marks)

Q1. Find output of the following code fragment.


x=”hello world”
print(x[:2],x[:-2],x[-2:])
print(x[6],x[2:4])
print(x[2:-3],x[-4:-2])
Ans: he hello wor ld
w ll
llo wo or
Q2. Rewrite the following programs after removing syntactical errors:
for=20
for1=50:
for3=for+for1+for2
print(for3)

Ans:
f=20 #( as for is a keyword in python)
for1=50 #(: can not be used here)
for3=f+for1 #(for2 not defined)
print(for3)

You might also like