0% found this document useful (0 votes)
2 views15 pages

Python_01 (8)

Chapter 1 introduces Python as a high-level, general-purpose programming language developed by Guido van Rossum in 1991, highlighting its features such as ease of use, cross-platform compatibility, and being open-source. It covers fundamental concepts including Python modes (script and interactive), character sets, tokens, variables, data types, operators, and input/output functions. Additionally, it discusses the importance of indentation, comments, and data type conversion in Python programming.

Uploaded by

Jiya Pant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views15 pages

Python_01 (8)

Chapter 1 introduces Python as a high-level, general-purpose programming language developed by Guido van Rossum in 1991, highlighting its features such as ease of use, cross-platform compatibility, and being open-source. It covers fundamental concepts including Python modes (script and interactive), character sets, tokens, variables, data types, operators, and input/output functions. Additionally, it discusses the importance of indentation, comments, and data type conversion in Python programming.

Uploaded by

Jiya Pant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Chapter -1 (Introduction to python)

It is widely used general purpose,high level programming language.Developed by Guido van Rossum in
1991.

Features:

1.Easy to use – Due to simple syntax rule


2. Interpreted language – Code execution & interpretation line by line
3. Cross-platform language – It can run on windows,linux,macinetosh etc. equally
4. Expressive language – Less code to be written as it itself express the purpose of the code.
5. Completeness – Support wide rage of library 6. Free & Open Source – Can be downloaded freely and
source code can be modify for improvement
How to work in Python

Python has two basic modes: script and interactive. The normal mode is the mode where the scripted and
finished .py files are run in the Python interpreter. Interactive mode is a command line shell which gives immediate
feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the
interpreter, the fed program is evaluated both in part and in whole.

(i) in Interactive mode * Search the python.exe file in the drive in which it is installed. If found double
click it to start python in interactive mode

A sample interactive session:

>>> 5
5
>>> print(5*7)
35
>>> "hello" * 4
'hellohellohellohello'
>>> "hello".__class__
<type 'str'>

(ii) Click start button -> All programs -> python->IDLE(Python GUI)

Python Character Set


A set of valid characters recognized by python. Python uses the traditional ASCII character set. The
latest version recognizes the Unicode character set. The ASCII character set is a subset of the Unicode
character set
Letters :– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbol available over keyboard
White spaces:– blank space,tab,carriage return,new line, form feed
Other characters:- Unicode

Python Chapter-01 Page 1


Token
Smallest individual unit in a program is known as token.
1. Keywords 2. Identifiers 3. Literals 4. Operators 5. Punctuators
Keywords
Reserve word of the compiler/interpreter which can’t be used as identifier.examples:
and exec not as finally or assert for pass break from print class
global raise continue if return def import try del in while
elif is with else lambda yield
Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
* An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
* Python does not allow special characters
* Identifier must not be a keyword of Python.
* Python is a case sensitive programming language. Thus, Rollnumber and rollnumber are two different
identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no
Some invalid identifier : 2rno,break,my.book,data-cs
Literals
Literals in Python can be defined as number, text, or other data that represent values to be stored in
variables.
Example of String Literals in Python
name = ‘Johni’ , fname =“johny”
Example of Integer Literals in Python(numeric literal) age = 22
Example of Float Literals in Python(numeric literal) height = 6.2
Example of Special Literals in Python name = None

Escape sequence
Escape Sequence are non printable characters.
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)

Python Chapter-01 Page 2


\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh

Operators
Operators can be defined as symbols that are used to perform operations on operands.
Types of Operators
1. Arithmetic Operators.
Arithmetic Operators are used to perform arithmetic operations like addition, multiplication, division
etc.
Operators Description Example
+ perform addition of two number a+b
- perform subtraction of two number a-b
/ perform division of two number a/b
* perform multiplication of two number a*b
% Modulus = returns remainder a%b
// Floor Division = remove digits after the decimal point a//b
** Exponent = perform raise to power a**b
2. Relational Operators.
Relational Operators are used to compare the values.
Operators Description Example
== Equal to, return true if a equals to b a == b
!= Not equal, return true if a is not equals to b a != b
> Greater than, return true if a is greater than b a>b
>= Greater than or equal to a >= b
< Less than, return true if a is less than b a<b
<= Less than or equal to a <= b

Python Chapter-01 Page 3


3. Assignment Operators (Also Known as shorthand notation).
Used to assign values to the variables.
Operators Description Example
= Assigns values from right side operands to left side operand a=b
+= Add 2 numbers and assigns the result to left operand. a+=b
/= Divides 2 numbers and assigns the result to left operand. a/=b
*= Multiply 2 numbers and assigns the result to left operand. a*=b
-= Subtracts 2 numbers and assigns the result to left operand. a-=b
%= modulus 2 numbers and assigns the result to left operand. a%=b
/= Perform floor division on 2 numbers and assigns the result to left a//=b
**= calculate power on operators and assigns the result to left operand. a**=b
4. Logical Operators.
Logical Operators are used to perform logical operations on the given two variables or values
Operators Description Example
And return true if both condition are true x and y
Or return true if either or both condition are true x or y
Not reverse the condition not(a>b)

Example:
a=30
b=20
if(a==30 and b==20):
print('hello')
Output :- hello
5. Membership Operators
The membership operators in Python are used to validate whether a value is found within a sequence
such as such as strings, lists, or tuples.
Operators Description Example
In return true if value exists in the sequence, else false. a in list
not in return true if value does not exists in the sequence, else false. a not in list
E.g.
a = 22
list = [22,99,27,31]
In_Ans = a in list

Python Chapter-01 Page 4


NotIn_Ans = a not in list
print(In_Ans)
print(NotIn_Ans)
Output :- True False

Punctuators
Used to implement the grammatical and structure of a Syntax.Following are the python punctuators.
< > , . ; “ [ ] ( ) ' ' " " { }

Creating Variables

Variable is a name given to a memory location. A variable can consider as a container which holds value.
Python is a type infer language that means you don't need to specify the datatype of variable.Python
automatically get variable datatype depending upon the value assigned to the variable.

Unlike other programming languages, Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x = 5
y = "John"
print(x)
print(y)
In above assignment variable i.e., x and y are refer to L-Value because it reside in memory and is
addressable and 5 and “John” refer to as R-Value as they are expression.
Multiple Assignment:
assign a single value to many variables
a = b = c = 1 # single value to multiple variable
a,b = 1,2 # multiple value to multiple variable
a,b = b,a # value of a and b is swaped

Input/Output in python

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character or , chacater:

x = "awesome"
print("Python is" + x)

Python Chapter-01 Page 5


Output : Python isawesome

OR

x = "awesome"
print("Python is" , x)

Output : Python is awesome

Note : in first code there is no space between the word is and awesome while in
second case there is a space.

You can also use the + character to add a variable to another variable:

x = "Python is "
y = "awesome"
z = x + y
print(z)

Output : Python is awesome

For numbers, the + character works as a mathematical operator:

x = 5
y = 10
print(x + y)

Output is: 15

If you try to combine a string and a number, Python will give you an error:

x = 5
y = "John"
print(x + y)

Output : TypeError: unsupported operand type(s) for +: 'int' and 'str'

print(‘Computer',‘Science')
print(‘Computer',‘Science',sep=' & ')
print(‘Computer',‘Science',sep=' & ',end='.')
Output :-
Computer Science
Computer & Science
Computer & Science.

Python Chapter-01 Page 6


input() Function In Python allows a user to give input to a program from a keyboard but returns the
value accordingly.
e.g. age = int(input(‘enter your age’))
NOTE : input() function always enter string value in python 3.so on need int(),float() function can be
used for data conversion.

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
#This is a comment.
print("Hello, World!"

Docstrings
Python also has extended documentation capability, called docstrings.
Docstrings can be one line, or multiline.
Python uses triple quotes at the beginning and end of the docstring:
Docstrings are also comments:

"""This is a
multiline docstring."""
print("Hello, World!")

Data Types

Data Type specifies which type of value a variable can store.


type() function is used to determine a variable's type in Python.

x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Output

<class 'int'>
<class 'float'>
<class 'complex'>

Python support following datatypes

1. Number 2. String 3. Boolean 4. List 5. Tuple 6. Set 7. Dictionary

Python Chapter-01 Page 7


1. Numbers : It is used to store numeric values Python has three numeric types:

a. Integers : Int, or integer, is a whole number, positive or negative, without decimals, of


unlimited length.

b. Floating point numbers :Float, or "floating point number" is a number, positive or


negative, containing one or more decimals.

c. Complex numbers.: Complex numbers are combination of a real and imaginary part. Complex
numbers are in the form of X+Yj, where X is a real part and Y is imaginary part.

e.g. a = complex(5) # convert 5 to a real part val and zero imaginary part
print(a)
b=complex(101,23) #convert 101 with real part and 23 as imaginary part
print(b)
Output :-
(5+0j)
(101+23j)
NOTE: REST OF THE DATAYPES WILL BE DISCUSSED IN COMING CHAPTERS

Data Type conversion

int() function converts any data type to integer.

e.g
a = "101" # string
b=int(a) # converts string data type to integer.
c=int(122.4) # converts float data type to integer.
print(b)
print(c)
Output :-
101
122

float() function converts any data type to floating point number.

e.g.

a='301.4' #string
b=float(a) #converts string data type to floating point number.
c=float(121) #converts integer data type to floating point number.
print(b)
print(c)
Output :-

Python Chapter-01 Page 8


301.4
121.0

PYTHON OPERATOR PRECEDENCE

Python has well-defined rules for specifying the order in which the operators in an expression are evaluated
when the expression has several operators. For example, multiplication and division have a higher precedence
than addition and subtraction. Precedence rules can be overridden by explicit parentheses.

Precedence Order

When two operators share an operand, the operator with the higher precedence goes first. For example, since
multiplication has a higher precedence than addition, a + b * c is treated as a + (b * c), and a * b +
c is treated as (a * b) + c.

Associativity

When two operators share an operand and the operators have the same precedence, then the expression is
evaluated according to the associativity of the operators. For example, since the ** operator has right-to-left
associativity, a ** b ** c is treated as a ** (b ** c). On the other hand, since the /operator has left-to-
right associativity, a / b / c is treated as (a / b) / c.

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

Python Chapter-01 Page 9


| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR

Indentation
Python relies on indentation, using whitespace, to define scope in the code. Other programming
languages often use curly-brackets for this purpose.

All statements with the same distance to the right belong to the same block of code, i.e. the statements
within a block line up vertically. The block ends at a line less indented or the end of the file. If a block has to
be more deeply nested, it is simply indented further to the right.

Multi-Line Statement In Python


Usually, every Python statement ends with a newline character. However, we can extend it over to
multiple lines using the line continuation character (\).

And Python gives us two ways to enable multi-line statements in a program.

Explicit Line Continuation


When you right away use the line continuation character (\) to split a statement into multiple lines.

Example
# Initializing a list using the multi-line statement
>>> my_list = [1, \
2, 3\
,4,5 \

Python Chapter-01 Page 10


]
>>> print(my_list)
[1, 2, 3, 4, 5]

Implicit Line Continuation


Implicit line continuation is when you split a statement using either of parentheses ( ), brackets [ ] and
braces { }. You need to enclose the target statement using the mentioned construct.
Example
>>> result = (10 + 100
* 5 - 5
/ 100 + 10
)
>>> print(result)
519.95
Another Example
>>> subjects = [
'Maths',
'English',
'Science'
]
>>> print(subjects)

Python Chapter-01 Page 11


Practice Questions
Part – 1 (Theory)

1. Who is the developer of Python Programming Language?


2. Python is free and open source language. here, what is free and open source?
3. What are the advantages of Python Programming Language?
4. In how many different ways we can work of Python?
5. Differentiate interactive and script mode of Python programming language?
6. What are literals in Python? How many types of literals are there in Python?
7. How string literal is represented in Python?
8. What is a statement and expression?
9. What is the role of indention in Python?
10. What are variables?
11. Differentiate keyword and identifier.
12. What are tokens in Python?
13. How comments are given in Python program?
14. How many parts are there for any complex number?
15. What is data type in python? Is there any importance of data type?
16. Differentiate implicit type conversion and explicit type conversion.

Part -2 ( Output and Errors)

1. What will be the output of following?


a=20
b=a+1
a=33
print(a+b)
2. What is wrong with following code fragment?
a=20
print(a)
b=33
print(b)
3. What is wrong with following code fragment?
name="freya"
classs=4
print(name+classs)
4. What will be the output of following python code?
a,b=3,4
a,b,c=b,a+3,b-1
print(a,b,c)

Python Chapter-01 Page 12


5. What will be the output of following python code?
a,b=3,4
c,a=b*4,a+4
print(a,b,c)
6. What will be the output of following python code/code fragment?
a. print(print("vishal"))
b. print("vishal")
print("indian")
c. print("vishal",end=" ")
print("indian")
d. a=int(input("enter first no"))
b=int(input("enter second no"))
a,b=b,a
print("a=",a)
print("b=",b)
#if user is entering 5 and then 10
7. Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
8. What is the error of following code : a,b=100?
9. What is the output of the following code :
print(9//2)
10. Can you identify the data types of following values,if yes write their data tpe.
4, 5.2, 8j , ’1’ , ”1” , 4+0j
11. What will be the output of the following code
print(5/2)
print(5//2)
12. What will the output of following codes
print (8*2 - 2*4)
print (3 + 18/9 - 3**2+1)
print ((4 + 24)/8 - (2**3+3))
13. What will the output of following code snippet
x=5
y = -1
print ((x+y)*1./x)
print (3*x )
print (x )

14. Write the equivalent Boolean value


a. 7+3*4 < 3 *3 + 4

Python Chapter-01 Page 13


15. What is the problem with following code fragments
a. x="marks"+100
print(x)
b. a=5
b=a+500
a="marks"
c=a/2 print(c)
16. What will be the output of following code fragments
a,b=5,6
a,b,c=10,b,a
a,b,c=c/2,a+4,b*6+2
print(a)
print(b)
print(c)
17. What will be the output of following python statements
print(type(100))
print(type(100/2))
print(type('0'))
print(type(5.2))
18. Classify each of the following as either a legal or illegal Python identifier:
1. fred #Keywords
2. #if # Invalid
3. #2x #Invalid
4. -4 #Constant
5. sum_total #identifier
6. sumTotal #identifier
7. sum-total #Expression
8. #sum total #Invalid
9. Sumtotal #identifier
10. While #identifier
11. x2 #identifier
12. Private #Keywords
13. public #Keywords
14. #$16 #Invalid
15. xTwo #identifier
16. _static #identifier
17. _4 #identifier
18. ___ #identifier
19. #10% #Invalid
20. a27834 #identifier
21. #wilma’s #Invalid

Python Chapter-01 Page 14


19. If x = 2 Indicate what each of the following Python statements would print.
print(’x’)
print(‘x’)
print(x)
print(‘x+1’)
print(’x’ + 1)
print(x + 1)

Part – 3 (Programs)

1. WAP to add 2 numbers.[R=a+b]


2. WAP to add 4 numbers.[R=a+b+c+d]
3. WAP to multiply 3 numbers.[R=a*b*c]
4. WAP to find average 5 numbers[R=(a+b+c+d+e)/5]
5. WAP to display age after 15 years.[nage =age+15]
6. WAP to display a 3 numbers [R=a*a*a]
7. WAP to find the area of square. [A=a*a]
8. WAP to find the area of rectangle [A=a*b]
9. WAP to find the result X N pow()
10. WAP to find the perimeter of rectangle[A=2*(l+ b) ]
11. WAP to find the area of circle [A=3.14*r*r]
12. WAP to find the circumference of circle [C=2*3.14*r]
13. WAP to swap the values of two variables.[a= a + b; b=a – b; a= a – b;]
14. WAP to input Hours, Minutes and Seconds and display in seconds. [TS=H*60*60+M*60+S]
15. WAP to input cost and display cost after increasing 25% [cost+(cost*25)/100]
16. WAP to display squire of a numbers [a*a]
17. WAP to find the volume of sphere.[v=4/3*3.14*r 3 ]
18. WAP to find the area of triangle using HEROS formula[s= (a + b + c)/2, R=] math.sqrt()
19. WAP to take principal, rate and time and display C.I. (Compound Interest) CI=p*(1+R/100) T pow()
20. WAP to calculate sum of 5 subjects &amp; find percentage[TOT=s1+s2+s3+s4+s5,Per=TOT/5]
21. WAP which accept temperature in Fahrenheit and print it in centigrade[c=5/9*(T-32)]
22. WAP which accept temperature in centigrade and print it in Fahrenheit[F=(1.8*T)+32]
23. WAP to calculate simple interest. [SI=(PRT)/100]
24. WAP to find gross salary [GS=BASIC+DA-PF+HRA]
25. Write a python program to solve quadratic equation
26. Python Program to Convert Kilometers to Miles.

Python Chapter-01 Page 15

You might also like