Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Review of Python Basics End Game

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

Review of Python Basics End Game

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

REVIEW OF PYTHON BASICS

anas abdul nizar


1. Consider the given expression:
2T F - =
5
17%5==2 and 4%2>0 or 15//2==7.5
-
T adf
T
Which of the following will be correct output if the given expression is
evaluated?

(a)True
O (b) False
75
(c)None (d)Null


.

25
2. State True or False:

“In a Python loops can also have else clause”

servong :
for control vosable in

body of foo loop

#optional
else :
-

-
What is the output of the following code?
---
Text = 'Happy
--
hour12-3'
L= " "
for i in range(len(Text)):
if Text[i].isupper():
-
HAPPY#HOUR112
L=L+Text[i].lower() - 33
elif Text[i].islower():
-

X
L=L+Text[i].upper() -

elif Text[i].isdigit():
-
-
L=L+(Text[i]*2) (A)hAPPY#HOUR1122#33
-
(B)Happy#hOUR12#3
else:
(C)hAPPY#HOUR112233
L=L+'#' -
(D)Happy Hour11 22 33 #
print(L)
1X2
11 2x2 = 22
4. Select the correct output of the code:
s = "Question paper 2022-23“ -
s= s.split('2')
=>
-
to
lis

print(s)
-
a. ['Question paper ', '0', '', '-', '3'] =
b. ('Question paper ', '0', '', '-', '3')
c. ['Question paper ', '0', '2', '', '-', '3'] -
d. ('Question paper ', '0', '2', '', '-', '3')
5. What will be the output of following code if
0111
a = “abcde”
Ab
a [1:1 ] == a [1:2]
-
False
type (a[1:1]) == type (a[1:2])


6. Select the correct output of the code:

s toLupe
a = "foobar"
--

a = a.partition("o")
strins
-

print(a)
(a) ["fo","","bar"]
(b) ["f","oo","bar"]
(c) ["f","o","bar"]
(d) ("f","o","obar") -
-
7. Identify the output of the following python code: 1
L
D={1:"one",2:"two", 3:"three"} -

L=[] =
O -

for k,v in D.items():


--

if 'o' in v:
[1 ]
-

-
=

L.append(k)
- I
print(L)
-
(a) [1,2] (b) [1,3] (c)[2,3] (d)[3,1]
-
8. Which of the following is not a tuple in python? -
(a) (10,20) (b) (10,)
O (c) (10) (d) All are tuples

E)
9. What will be the output of the following Python code snippet?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
-
used
7 Sambull not
in dectionary
a. True b. False

C
c. Error d. None
10. Predict the output of the Python
code given below:
-
T = (9,18,27,36,45,54)
-

(18 36 54)
- --

L=list(T)
E , S
-
L1 = [ ] - - -
-
for i in L:
-
9 %6
& -
if i%6==0:
-

L1.append(i) I
GF
-

T1 =- tuple(L1)
print(T1)


11. What will be the output of the following Python code snippet?
--
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
-

A
d1 == d2 I

6
a) True -

b) False
c) None
d) Error
12. State True or False
“continue keyword skips remaining part of an iteration in a loop”

=<

Sa
while (ic : 3) :

If (i = = 2) :

continue :

Spent
13. Select the correct output of the code:
01231561
>>> St=”Computer”
-

>>> print(St[4:])

(a) “Comp” (b) “pmoC” (c) “uter” (d) “mput”


-
14. print(True or not True and False)
Choose one option from the following that will be the correct output
after executing the above python expression.
-
a) False b) True c) or d) not

False
or Joue
not and
Take

Faad I

or
I
18. When a Python function does not have return statement then what
it returns? -

(a) int (b) float


E
(c) None (d)Give Error
20. Which of the following statement(s) would give an error after
executing the following code?

S="Welcome to class XII" #Statement 1 -


-

print(S) # Statement 2
-

S="Thank you“ #Statement 3 -

S[0]= '@’
- - #Statement 4
S=S+"Thank you" #Statement 5 -

(a) Statement 3 =
(b) Statement 4
(c) Statement 5 (d) Statement 4 and 5
Using Interactive
-
(Python Shell window) mode, the Python commands
are directly typed at >>> (command prompt) and as soon as we press
the Enter key, the interpreter displays the result(s) immediately, which
is known as Displaying.
0

The drawback of interactive mode is that we cannot save the


commands that we type. This can be overcome using the script mode.
In order to switch over to script mode, click on the File menu option ->
-

New option or press the shortcut key Ctrl + N from the shell window.
TOKENS
A token is the smallest element of a Python script that is
meaningful to the interpreter There are five categories of tokens
which are as under
-Identifiers: The name of any variable, constant, function or module
is called an identifier. The Python identifier is made with a
combination of lowercase (a-3) or uppercase (AZ) letters, digits
(0-9) or an underscore (_) Examples of identifiers are abc, x12y,
India_123, swap, stud, Roll, no, etc

Bore * ab
- -
Keywords: The reserved words of Python, which have a special
-

fixed meaning for the interpreter, are called keywords. No


keyword can be used as an identifier eg: True , False , as ,
-

break, def , else , import , etc


- -

-Literals: A fixed numeric or non-numeric value is called a literal.


It can be defined as a number. text or other data that
represents values to be stored in variables. Examples of literals
are 2, -23.6, "abe”,’ Independence’, etc
-

S
DATA TYPES

-----
-
1. Int idata type is used to store whole numbers without Fractional part .
-
They can be +ve of - ve .

-
2. Boolean : bool data type represents one of the two values : True or
False . It is sub type that represents integer values

-
-
1 (True) and 0 (False) .

-
3. Float/Floating Point: Floating point numbers signify real numbers. This
-

data type is used to store numbers with a fraction part. They can be
represented in scientific notation where the lowercase or uppercase
letter 'e' or 'E' signifies the 10 ^ (th) power.
-
4. Complex Numbers: Complex numbers are pairs of real and
imaginary numbers. They take the form 'a + bj, where 'a' is the
-

float, 'b' is the real part of the complex number and j is the
imaginary part which represents the square root of -1.
-
5. None: This is a special data type with an unidentified value. It
-
signifies the absence of value in a situation, represented by
None. Python doesn't display anything when we give a command
to display the value of a variable containing value as None.
-
6. Sequence: A sequence is an ordered collection of items, indexed by
integers (both positive as well as negative). The three types of
sequence data types available in Python are Strings, Lists and Tuples,
-

which we will discuss later in the chapter.

-
7. Sets: Set is an unordered collection of values of any type with no
duplicate entry, enclosed within curly braces {}. It is mutable, for
E 3
-

example, S1= (10,20,30,60,100).


-
-
8. Mappings: This data type is ordered and mutable. Dictionaries in
Python fall under Mappings. A dictionary represents data in key-value
pairs and is accessed using keys, where keys are immutable and
values are mutable. Dictionary is enclosed in curly brackets { }.
-
Dynamic Typing -
One of the salient features of Python is dynamic typing. It refers to
declaring a variable multiple times with values of different data
types as and when required. It allows you to redefine a variable with
different data types such as numeric, string, etc.

O
Eg : x=20
print(x)
type(x)
int
& x=”Welcome” stries
=
type(x)
7 .
5
Operators 15% 1 =
1 %T

O -

O
O
O
O
O -
-
INPUT AND OYTPUT FUNCTIONS

-input(): The input() function accepts and returns the


user's input as a string and stores it in the variable
-

which is assigned with the assignment operator.

Eg: # ⑤ s

1. User_name =input(“Please Enter your name:”)


-
2. n1= int(input(“Enter first number”))
W
eval(): eval() method takes a string as an argument, evaluates this string as
-

a number and returns the numeric result (int or float as the case may be). If
the given argument is not a string or if it cannot be evaluated as a number,
then eval() results in an error. For example, eval (6*6) returns 36.
-

-
print() : print() is a function which is used to display the specified content on
the screen. It converts the argument into string before displaying on the
screen. The content (called argument) is specified within the parentheses.
print function without any arguments will simply jump to the next line.
Type conversion

Type casting (Explicit Conversion) -

Explicit conversion, also called type casting, happens when data type
conversion takes place deliberately, i.e., the programmer forces it in the
program. The general form of an explicit data type conversion is:

new_data_type (expression)
-

Eg: x=50.75 ~ float


print(int(x))
int (X)
50
Implicit Conversion
Implicit conversion, also known as coercion, happens when data type
conversion is done automatically during run-time by Python and is not
-
instructed by the programmer.

#Implicit type conversion from int to float


num1 = 10 #numl is an integer -


o
-

num2= 55.0 #num2 is a float -


& E
suml= numl + num2 #suml is sum of a float and an integer
-
=
print (sum1) 10 0+ 55 0
. .
-

print (type (sum1))


Suml =
FLOW OF EXECUTION

Execution in a Python program begins with the very first


statement. The way in which the statements are executed
defines the flow of execution in a Python program, which is
categorized as under:
(i) Sequential statements -
(ii) Selection/ Conditional Statements -

(iii) Iteration or Looping constructs -


Sequential Statements
Sequential, as the name suggests, signifies that statements in a
Python program are executed one after the other, i.e., from the first
statement till the last statement.

Eg: Program to calculate Area of Rectangle

-
l=int(input(“Enter the length of rectangle”))
b=int(input(“Enter the breadth of rectangle”))
a= l*b
print(“Area is”,a)
Selection Statements -

1. If statement

If condition: -

-
statement(s) -

Eg: a=5 -
-
b=6
if(a>b):
-

2
print(“Large”,a)
2. If - else -

If condition: -

Statement(s) age : 20
else:
u
statement(s)
Is
Eg: if (age>=18)
-
print(“Eligible for -
vote”)
else:
print(“Not eligible for vote”)
If-elif-else
if condition:


statement(s) -

elif condition:
statement(s)
elif condition:
statement (s)
else:
statement (s)

-
Iteration/Looping Statements
fur X In Fonts :
point(x)
For loop
Syntax of for loop

for <Control_variable> in <sequence/ items in range>:


-
-
<statements in body of loop>
else: # optional
-
<statements>
Eg: fruits = ["apple", "banana", "cherry"]
--
forgx in fruits:
-
-
print(x)
-
range()
range() function is a built-in function in Python and is used to
create a list containing a sequence of numbers starting with the
start parameter and ending with one less than the stop
parameter. We can also specify the skip value using the step
-

Em
parameter.
~
range(start,stop,step) -
-

Eg: range(0,30,5)
range
(12)
range (1 ,
10 -
While loop

while <test_expression>:
Body of while
else: # optional
Body of else

Eg: i=1
While i<=5:
print(i)
Strings

String is group of characters .Strings in python are surrounded


by either single quotation marks, or double quotation marks.
-

Eg:
'hello' is the same as "hello".

To"-
String Operation a =
"2"

+ - Concatination - b = "" =

-
* - Repetition
point (a b)
+
in/not in - membership -

[:] -Range(start,stop,[step]) -
--

e
[] - Slice[n:m]
-

a =
"2 "hello'
a =

poit (a 2) > 22 point (eina)Eze


-

* -

point C'2' not in


a)
-
The
Is
-
Lists
Like strings, lists are a sequence of values. A list is a data type
that can be used to store any type and number of variables
and information. The values in the list are called elements or
items or list members.

Syntax

[list_name]=[item1,item2,item3….,itemn]

Eg: L1=[10,20,30,40]
Built-in functions in List

len(list)

max(list)

min(list)

list(seq)

sum(list)
a =
, =

F5s-2-1
-

40 (a[B) & -

mit (a[1 : 43)

point (a[1 : 13)


out
Tuples
A tuple is a collection of Python objects separated by commas. In other
words, a tuple is a sequence of immutable Python objects. The
-

difference between lists and tuples is that the contents of tuples


cannot be changed. Tuples are represented by parentheses ()
Syntax
01214
Tup = (5,11,22,24,65)

-
print(tup[0])
print(tup[1:3])
Dictionary

A dictionary is like a list except that a list can be accessed using


an index whereas items in a dictionary can be accessed using a
unique key, which can be a number, string or a tuple. The items in a
dictionary can be changed but keys are an immutable data type.
Each key is separated from its value by a colon (:), the items are
separated by commas and the entire elements (key- value pair) are
enclosed in curly braces {).
moben lat not allowed
space


a -
2
Sri-mommy
0-9

Identifier not besing


with number

-
a =
"Heio"
0123(
Ion(a)
115
range (0, Ion(a)]
U

You might also like