0% found this document useful (0 votes)
3 views87 pages

Computer science intro to python ppt

The document covers Python fundamentals including keywords, identifiers, variables, data types, and operators. It explains the rules for naming identifiers, the use of different data types like strings, lists, and dictionaries, as well as control structures like if-else statements and loops. Additionally, it provides exercises and examples to illustrate the concepts discussed.

Uploaded by

g9pvg5py6h
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as KEY, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views87 pages

Computer science intro to python ppt

The document covers Python fundamentals including keywords, identifiers, variables, data types, and operators. It explains the rules for naming identifiers, the use of different data types like strings, lists, and dictionaries, as well as control structures like if-else statements and loops. Additionally, it provides exercises and examples to illustrate the concepts discussed.

Uploaded by

g9pvg5py6h
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as KEY, PDF, TXT or read online on Scribd
You are on page 1/ 87

Python Fundamentals

Python Keywords
Keywords are reserved words. Each keyword has a specific meaning
to the Python interpreter. As Python is case sensitive, keywords must
be written exactly as given
Identifiers
identifiers are names used to identify a variable, function, or other entities in
a program.
The rules for naming an identifier in Python are as follows:
The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_).
This may be followed by any combination of characters a-z, A-Z, 0-9 or
underscore (_).
Thus, an identifier cannot start with a digit.
It can be of any length. (However, it is preferred to keep it short and
meaningful).
It should not be a keyword or reserved word .
We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
For example, to find the average of marks obtained by a student in
three subjects namely Maths, English, Informatics Practices (IP), we can
choose the identifiers as marksMaths, marksEnglish, marksIP and avg
rather than a, b, c, or A, B, C, as such alphabets do not give any clue
about the data that variable refers to. avg = (marksMaths +
marksEnglish + marksIP)/3
Identify the valid and invalid identifier
Mybook, file123, z2td, date_2, _no ,2rno,break,my.book,data-cs
Variables
Variable is an identifier whose value can change. For example
variable age can have different value for different person. Variable
name should be unique in a program.
Value of a variable can be string (for example, b’, ‘Global Citizen’),
number (for example 10,71,80.52) or any combination of
alphanumeric (alphabets and numbers for example ‘b10’) characters.
In Python, we can use an assignment statement to create new
variables and assign specific values to them. gender = 'M' message =
"Keep Smiling" price = 987.
Exercise for the day
Write a Python program to find the area of a rectangle given that its
length is 10 units and breadth is 20 units.
Data Types
Data type identifies the type of data which a variable can hold and
the operations that can be performed on those data.
Number
Boolean data type (bool) is a subtype of integer. It is a unique data
type, consisting of two constants, True and False. Boolean True value
is non-zero. Boolean False is the value zero.
To determine the data type of the variable using built-in function
type()
>>> quantity = 10
>>> type(quantity)
>>> Price = -1921.9
>>> type(price)
Sequence
Strings: Anything enclosed with ‘ ‘ or “ “ quotes is referred to as
strings.
EX:>>> str1 = 'Hello Friend’
>>> str2 = "452“
List :List is a sequence of items separated by commas and items are
enclosed in square brackets [ ].
EX:>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
Tuple: Tuple is a sequence of items separated by commas and items
are enclosed in parenthesis ( ).
EX:>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
Mapping
Mapping is an unordered data type in Python.
Currently, there is only one standard mapping data type in Python
called Dictionary.
Dictionary in Python holds data items in key-value pairs and Items
are enclosed in curly brackets { }
Ex: dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
AFL
What is the difference between a keyword and identifier.
What will be the output of the following code?
x,y=2,6
x,y=y, x+2
print(x,y)
What are data types? What are the built-in core data types ?
Which data type of python handle numbers.
Identify the data types of the values given below:
3 ,3i ,13.0 ,’13’, ”13”, 2+0i,13, [3,13,2], (3,12,2),”hello”
Operators
What will be the output for:
(a) 12/4
(b) 14//4
(c) 14%4
(d)14.0/4
AFL
What will be the output for:
(i) 17%5 (ii) 87//5 (iii) 2**4
What will be the output produced by the following code:
a=3+5/8
b=int(3+5/8)
c=3+float(5/8)
d=3+float(5)/8
e=3+5.0/8
f=int(3+5/8.0)
print(a, b, c, d, e, f)
Relational Operators
Consider the given Python variables num1 = 10, num2 = 0, num3 = 10, str1 = "Good", str2 = "Afternoon"

Operator Operation Description Example


== Equals to If values of two operands are equal, then >>> num1 == num2 False
the condition is True, otherwise it is >> str1 == str2 False
False
!= Not equal to If values of two operands are not equal, >>> num1 != num2 True
then condition is True, otherwise it is >>> s tr1 != str2 True >>>
False num1 != num3 False
Operator Operation Description Example
> greater than if the value of the left operand is greater >>> num1 > num2 True
than the value of the right operand, then >>> s tr1 > str2 True
condition is True, otherwise it is False.

< Less than if the value of the left operand is less >>> num1 < num3 False
than the value of the right operand, the
condition is true otherwise it is False
Assignment Operators
AFL
a=3, b=13, p=3.0, c=‘n’, d=‘g’, e=‘N’, f=‘god’, g=‘God’, h=‘god’, j=u’God’,
L=[1,2,3], M=[2,4,6], N=[1,2,3] , o=(1,2,3), P=(2,4,6), Q=(1,2,3)
What will be the output for the following:
(i)a<b (vi) g==j
(ii)c<d (vii) a==p
(iii)f<h (viii) L==M
(iv)f==h
(v)c==e
Logical Operators
AFL
Q. Given i=4, j=5, k=4, what will be the output of the following
expressions
(i) i<k (ii) i<j (iii) i<=k (iv) i==j
(v) i==k (vi) j>k (vii) j>=I (viii) j!=I (ix) j<>k
Q. How are the following expressions different
(i) ans=8 (ii) ans==8
Or OperatorRelational expressions
as operands
In this the or operator evaluates to true if either of its operands
evaluates to true else false.
X y x or y
false false false
false true true
true false true
true true true
Ex: (4==4)or (5==8) is true
5>8 or 5<2 = ?
Exercise
A. X Y X or Y
1 0
0 1
0 0
1 1
example
(4==4) and (5==8) ?
5>8 and 5<2 ?
8>5 and 2<5 ?
examples
Not 5 ?
Not 0 ?
Not -4 ?
Not(5>2) ?
Not(5>9) ?
Operator precedence
operator highest
()
**
+x,-x
*,/,//,%
+,-
<,>,<=,>=,<>,!=,==
Not x
and
or lowest
AFL
What will be the output for:
(5<10) and (10<5) or (3<18) and not 8<18
false
a=5-4-3
b=3**2**3
print(a)
print(b)
-2
6561
p=10
q=20
p*=q//3
q+=p+q**2
print(p,q)
p=5/2
q=p*4
r=p+4
p+=p+q+r
r+=p+q+r
q-=p+q*r
print(p,q,r)
60,480
27.5,-642.5,62.5
How will the following expression be evaluated?
15.0 / 4.0 + (8 + 3.0)
14.75
a=5
b=10
a+=a+b
b+=a+b
print(a,b)
(20,300)
x=8
y=2
x+=y
y-=x
print(x,y)
(10,-8)
p=2/5
q=p*4
r=p*q
p+=p+q-r
r*=p-q+r
q+=p+q
print(p,q,r)
1.7599999,4.96,0.166
Input and Output
In python input() function is there to input the values.
a=input(“enter your name”)
For output there is print()
#Calculate square of a number
num = int(input("Enter the first number"))
square = num * num
print("the square of", num, " is ", square)
Built in Functions
If- else Statement
This form of if statement tests a condition and if the condition
evaluates to true it carries out statements intended below if
If condition evaluates to false , it carries out statements intended
below else.
If- else Statement(cont…)
Syntax :
if<conditional expression>:
statement
[statements]
else:
statement
[staements]
If- else Statement(cont…)
Example1:
if a>=0 :
print a, “is a zero or a positive number”
else :
print a, “is a negative number”
Program
#WAP to accept three integers and print the largest of the three using
if statements only.
x =y = z = 0
x = float(input(“enter first no:”))
y = float(input(“enter second no:”))
z = float(input(“enter third no:”))
max = x
Program (cont…)
if y>max:
max = y
if z> max :
max = z
print “largest number is”, max
WAP that takes a number and check whether the given number is
odd or even.
age = int(input("Enter your age "))
if age >= 18: # use ‘:’ to indicate end of condition.
print("Eligible to vote")
If –elif Statement(cont..)
Synatx :
if<conditional expression>:
statement
[statements]
elif<conditional expression>:
statement
[statements]
else:
statement
[statements]
#Program to subtract smaller number from the #larger number and
display the difference.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2, "is", diff)
If –elif Statement(cont..)
Example2 :
if runs>=100:
print ”batsman scored a century”
elif runs>=50:
print ”batsman scored a fifty”
else:
print ”batsman has neither scored a century nor fifty”
Check whether a number is positive, negative, or zero.
number = int(input("Enter a number: ")
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
AFL
WAP that reads two numbers and an arithmetic operator and
displays the computed result.
WAP to perform the following task according to the user’s choice
using menu
(a) area of circle (b) area of rectangle (c)area of square
WAP to print whether a given character is an uppercase or a
lowercase character or a digit or any other character.
The range() Function
This range function is used with the python for loop.
It generates a list which is a special sequence type.
A sequence in python is a succession of values bound together by a
single name.
Some sequence types are: lists, tuples ,strings etc
The range() Function
Syntax is :
range(<lower limit>, <upper limit>)
# both limits must be integers
The function in the form range(l,u) will produce a list having values
starting from l, l+1, l+2……..u-1. the lower limit is always included in
the list but the upper limit is never included.
The range() Function
Example1: (0,5)
will produce list as[0,1,2,3,4]
Example2: (5,0)
will return an empty list[] as no number falls in this arithmetic
progression.
Example3: (12,18)
will return list as [12,13,14,15,16,17]
The range() Function
This function works as
range (l,u,s) all are integers
will produce a list with values(l,l+s,l+2s…..<=u-1)
Example1: (0,10,2)
will produce a list [0,2,4,6,8]
AFL
What will be the result of the range (5,0,-1)?
What will be the value generated for the following statements:
Range(10), range(5,10), range(3,7), range(5,15,3), range(9,3,-1)
For loop
Sometimes we need to repeat certain things for a particular number
of times,
Python provides two kinds of loops: for and while to represent two
categories of loops
For Loop
The general form of for loop is
for<variable> in <sequence>:
statements_to_repeat
Example: for a in [1,4,7]:
print a
output will be 1
4
7
For Loop(cont..)
Example 2: for ch in ‘calm’:
print ch
output : c
a
l
m
For Loop(cont..)
Example3: for v in [1,2,3]:
print v*v
output : 1
4
9
Starter Activity
Create a for loop using the below sequences:
School=[“Principal”, “PGT”,”TGT”,”PRT”]
Code=(10,20,30,40,50,60)
“plan now”
For with range()
Let us create a loop to print all the natural numbers from 1 to 100
for i in range(1,101):
print(i, end=‘\t’)
For Loop(Also called Counting Loop)
WAP to print table of any number.
num=int(input(“enter any number:”))
for a in range(1,11):
print num,’*’, a ‘=‘ ,num*a
output: 5*1=5
5*2=10
……
Sum=0
For i in range(1,101):
if(i%7==0):
sum=sum+I # sum=0+7=7 # sum=7+14
Print(sum)
WAP to find the sum of all numbers divisible by 7 between 1 to 100.
sum=0
for i in range(1,101):
if i%7==0:
sum+=i
print(sum)
AFL
WAP to print the sum of natural numbers between 1 to 7.
What is the output of the following code fragment?
for a in “abcde”:
print a, ‘+’,
Sum=0
for n in range(1,8):
sum+=n
print(“sum of natural numbers<=“,n,”is”,sum)
WAP to print the following Fibonacci series 0,1,1,2,3,5,8……n terms.
WAP to enter 10 numbers and find its sum and average.
First=0
second=1
print(first)
print(second)
for a in range(1,19):
third=first + second
print(third)
first , second=second , third
While Loop
A while loop is a conditional loop that will repeat the instructions
within itself as long as a condition remains true.

It is a entry controlled loop ie. It first checks the condition if the


condition is true then allows to enter in loop.

While loop contains various loop elements: initialization , test


condition, body of loop and update statements.
While Loop
Example:
i=1 # initialization
while(i<=10): # test condition
print(i) # body of loop
i+=1 # update
Find the Output for:
a=5
while a>0:
print(a)
a-=1
print(“Thank you”)
x=10
y=0
while x>y:
x=x-4
y+=4
print(x, end=“ “)
i=0
sum=0
while(i<9):
if i%4==0:
sum=sum+i
i=i+2
print(sum)
x,y=2,4
if(x+y==10):
print(“True”)
else:
print(“false”)
Convert while to for
x=5
while(x<10):
print(x+10)
x+=2
for x in range(5,10,2):
print(x+10)
Convert for to while
for k in range(10,20,5):
print(k)

k=10
while(k<20):
print(k)
k+=5
Jump Statements
There are two jump statements break and continue
A break statement terminates the very loop it lies within. Program
resumes from the statement immediately after it.
Continue statements is used to skip the statements below continue
statements inside the loop and forces the loop to continue with the
next value.
Example
for i in range(1,20):
if i%6==0:
break
print I
print(“loop over”)
1
2
3
4
5
Loop over
Continue
for i in range(1,20):
if i%6==0:
continue
print(i, end=“ “)
print(“loop over”)
1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19
loop over
Debugging
a program may not execute or may generate wrong output. :
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors
Like any programming language, Python has rules that determine
how a program is to be written. This is called syntax.
Example (7+10) is correct whereas (7+10 is incorrect.
Such errors need to be removed before execution of the program.
Logical Errors
A logical error/bug (called semantic error) does not stop execution
but the program behaves incorrectly and produces undesired /wrong
output.
if we wish to find the average of two numbers 10 and 12 and we
write the code as 10 + 12/2, it would run successfully and produce
the result 16, which is wrong. The correct code to find the average
should have been (10 + 12) /2 to get the output as 11.
Runtime Error
Runtime error is when the statement is correct syntactically, but the
interpreter can not execute it.
We have a statement having division operation in the program. By
mistake, if the denominator value is zero then it will give a runtime
error like “division by zero”.
AFL
i=1
while(i<=10):
print(i)
i+=1
else:
print(“loop over”)
1
2
3
4
5
6
7
8
9
10
Loop over
names=[“allahabad”, “lucknow”, “Varanasi”, “Kanpur”, “agra”,
“Ghaziabad”, “Mathura”, “meerut”]
City=input(“enter the city to search:”)
for c in names:
if c==city:
print(“city found”)
break
else:
print(“not found”)
Nested loops

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy