0% found this document useful (0 votes)
0 views

004 - 14-05-2020 XI-Python Basics - Programming #2

The document covers the basics of Python programming, including comments, operators, statements, and user input. It explains various types of errors such as syntax, logical, and run-time errors, along with examples for clarity. Additionally, it emphasizes the importance of writing clear and simple code for better readability and maintenance.

Uploaded by

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

004 - 14-05-2020 XI-Python Basics - Programming #2

The document covers the basics of Python programming, including comments, operators, statements, and user input. It explains various types of errors such as syntax, logical, and run-time errors, along with examples for clarity. Additionally, it emphasizes the importance of writing clear and simple code for better readability and maintenance.

Uploaded by

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

Python Basics

Computer Science
Programming with Python - 2
Topics to be covered 2

● Comments: (Single line & Multi Line/ Continuation statements)


● More on operators & their types - Relational Operators, Logical
Operators, Augmented Assignment Operators
● Displaying outputs in a Python program
● Accepting user input from the console
● Clarity & Simplification of expression
● Errors in a program - syntax error, run-time error and logical error.
Comments: Single line 3

Comments in Python are used to describe what a particular segment of


the code is doing. Comments are for increasing readability of a program.
Python Interpreter ignores comment.
In Python, we use the hash (#) symbol to start writing a comment. It
extends up to the newline character (till the enter key is pressed).

#The following statement is used to

#display the output My First Python

print('My First Python') #this statement is to display a value


Comments: Multi line 4

If a comment extends over multiple lines we can use triple


quotes, either ''' or """ to mark the beginning of a multi-line
comment and similarly a pairing set of ''' or """ to mark the
end of the comment.

'''The following statement is used to


display the output My First Python'''
print('My First Python')
Operators - Relational 5

Python Relational Operators are used to compare two values and


return a result as either True or False:

Operato Meaning Example


r
== Equal to x == y
!= Not equal to x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Operators - Logical 6

Python Logical Operators are used to operate upon Boolean Values and
return a single result as either True or False:

Operator Meaning Example


and Returns True only if both x < 5 and x < 10
statements are true
or Returns True if at least one of x < 5 or x < 4
the statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
Operators - Assignment and 7
Augmented
Assignment and Augmented (Arithmetic Assignment) operators are used
to assign values to variables:

Sn Operato Exampl Equivalen Meaning


o r e t
1 = x = 5 x is assigned value 5
2 += x += 5 x=x+5 x is incremented by 5
3 -= x -= 5 x=x-5 x is decremented by 5
4 *= x *= 5 x=x*5 x is assigned product of last value of
x and 5
Operators - Assignment and 8
Augmented
Assignment and Augmented (Arithmetic Assignment) operators are used
to assign values to variables:

Sno Operato Example Equivale Meaning


r nt
5 /= x /= 5 x=x/5 x is assigned quotient of last value of
x divided by 5
6 %= x %= 5 x=x%5 x is assigned remainder of last value
of
x divided by 5
7 //= x //= 5 x=x//5 x is assigned floor division of last
value of x divided by 5
8 **= x **= 5 x=x**5 x is assigned last value of x to the
power 5
Python Statements 9

Instructions that a Python interpreter can execute are called statements.


For example: This statement assigns the
x = 1 value 1 to a variable named x.

Multi-line statements
In Python, end of a statement is marked by a newline character (by
pressing the enter key). However, a statement can be extended over
multiple lines with the line continuation character (\). For example:
x = 2 + 4 + \ These 3 lines are equivalent to the
6 + 8 + \ single line statement
10 + 12 x = 2 + 4 + 6 + 8 + 10 + 12
Python Statements 10

Different statements are generally written in different lines,


example:
x = 1
y = 2
z = x + y

However, we can put multiple statements in a single line using


semicolons, as follows:
x = 1; y = 2; z = x + y
Assigning Multiple Variables 11

Assigning multiple values to multiple variables


Multiple variables can be assigned values using a single Python
assignment statement as follows:

x, y, z = 15, 95.5, "Welcome" The code assigns 15 to x, 95.5


to y and "Welcome" to z

Assigning same value to multiple variables


Multiple variables can be assigned the same value using a single Python
assignment statement as follows:
The code assigns the value 15 to
x = y = z = 15 the three variables x, y and z.
print() with escape sequence 12

Escape Sequence Description


\n Newline character
\\ To print backslash
\t To use a horizontal tab
\' OR \" To print a single quote or double quote

Python Hello
print("Hello\nFriends") code
Friends
print('We aren\'t afraid')
We aren't afraid
print("Just \t tabbed")
Just tabbed
print("My Car __/===\\__") Output My Car __/===\__
print() - Displaying outputs 13

The print() function prints the specified message to the screen. The
message can be a declared and initialized variable, any literal, or the
result of any operation. Example:
Python
print('Hello World') Hello World
code
print("Double quotes") Double quotes
print('concatena'+'tion') concatenation
print('hello','there') hello there
print('I\'m 5') I'm 5
Output I'm 5
print("I'm 5")
He said "hi"
print('He said "hi"')
print() - Displaying outputs 14

print(23==23,45==34) True False


print("Hello"=="Bye","Bye"=="Bye") False True
print(43>23,43<23) True False
print("AB">"AC","AB"<"AC") Python False True
print(51<=51,51<=54) code
print("51"<"533")
True True
print(50>34 and 52<90) True
print(50>34 and 52>90) True
print(65>34 or 52<90,50<34 or False
52>90) True False
print(not("Morning"=="Evening")) Output True
print(not(25>35)) True
Syntax of Python print() 15

print(object(s), sep = <separator>, end = <end>)


PARAMETERS

Parameter Description
object(s) Any object (variable/literal/calculation). If there
are multiple objects, they may be separated by
comma.
sep=<separator> Optional. Used to specify what character to be
used to separate multiple objects to be printed
with a single print(). Default is space ' '
end=<end> Optional. Used to specify what character
should be printed at the end. Default is '\n'
(line feed)
print() - Examples 16

print ('Hello', 'World')


Hello World

print ('Hello', 'World', sep = '#')


Hello#World

print ('Hello')
Hello

print ('World')
World
Taking user input 17

Programmers often need to interact with users to get data for processing.
Python provides us with the inbuilt function input() to take a user input for
any data. The value entered by the user is returned back by the input() as
a string.

Syntax:
<Var>=input( <prompt> )
Parameter Description
prompt A String, representing a default message before the
input.
Taking user input 18

The input() in Python works as follows:

● When input() function executes the program flow stops until the user
has given an input.
● The prompt is displayed on the output screen to ask a user to enter
input value (However, the prompt, to be printed on the screen is
optional with input()).
● The user input value is accepted as a string and returned back by the
input(). Even a number entered with input() is treated as a string.
Thus to input a number as an integer or a float value, an explicit
conversion is needed from string to an int or float respectively.
Taking user input 19

FirstName= input('First Name:')


LastName = input('Last Name:') Python
code
FullName = FirstName+" "+LastName
print('Good Day',FullName,sep="!")

for user Inputs as First Name:Priya


Priya and Sahay Last Name:Sahay
Output → Good Day!Priya Sahay
Taking user input 20

By default, input takes


N = int(input('Number:')) string, so, we need
C = input("Pattern Character:") convert it into integer to
treat it as a number
print(N,C*N)
print("7 Times",N,"=",7*N) Pytho
n code

for user Inputs Number:9


as
Pattern Character:*
9 and *
Output → 9 *********
7 Times 9 = 63
Taking user input 21

By default, input takes


E = float(input('English:')) string, so, we need
M = float(input('Maths:')) convert it into float to
treat it as a number
AVG = (E+M)/2
print("Average Marks:",AVG) Pytho
n code

for user Inputs English:65


as Maths:85
65 and 85 Average Marks: 75.0
Output →
Taking user input 22

By default, input takes


P = float(input('Principal:'))
string, so, we need
convert it into float to
R = float(input('Rate:'))
treat it as a number
T = float(input('Time:'))
SI = P*R*T/100
Pytho
print("Simple Interest:",SI)
n code

Principal:7000
for user Inputs as
Rate:10
7000,10 and 5
Output → Time:5
Simple Interest: 3500.0
While conversion, keep the following in 23
mind
P = float(input('Principal:')) While converting the input data
to int or float, remember - if we
R = float(input('Rate:')) enter string, it will raise an
T = float(input('Time:')) exception. The program will not
SI = P*R*T/100
execute further.
print("Simple Interest:",SI)

Principal:7000
Rate:10
Time:Good Time
----------------------------------------------
ValueError: could not convert string to float: 'Good Time'
Simplicity of Instructions 24

You do not write programs for executing it once by the computer, you
need to write clear instructions so that any whosoever reads the
program later (even you yourself!!) should be able to understand.

It is very common for programmers not to understand the logic of


their own programs after some time. Maintenance and Modification of
such programs would be very difficult.

A=float(input("A:")) P=float(input("P:"))
B=float(input("B:")) R=float(input("R:"))
C=float(input("C:")) T=float(input("T:"))
D=A*B*C/100 SI=P*R*T/100
print(D) print(SI)
Simplicity of Instructions 25

Writing simple instructions helps in avoiding this problem. Some Tips


are as follows:
● Avoid clever instructions.
● One instruction per task
● Use standards − Every language has its standards, follow them
● Use appropriate comments

S=float(input("Sal:"))
IH=S+S*(30/100)+S*(10/100)
print(IH) Sal=float(input("Sal:"))
DA=Sal*(30/100)
Tax=Sal*(10/100)
InHand=Sal+DA-Tax
print(InHand)
Clarity & Simplification of expression 26

Expression in a program is a sequence of operators and operands to do


an arithmetic or logical computation.
Some examples of valid expressions:
● Assigning a value to a variable
● Arithmetic calculations using one or more variables
● Comparing two values

Writing non-ambiguous expressions is a skill that must be developed by


every programmer.
Here are some points to be kept in mind while writing such expressions
● Avoid expressions which may give ambiguous results
● Avoid complex expressions

Keep the names of the variables simple, short and meaningful


Errors in a program 27

● Error/Bug: Any malfunction, which either “stops the normal


compilation/execution of the program” OR “program execution with
wrong results” is known as an error/bug in the program. Removal of
Bug from a program is known as debugging.

● Syntax Error: Syntax error, also known as parsing error, is the most
common kind of error in the program, which occurs due to wrong use
of syntax of the language. The process of translation of the script to
be understood by the system is known as parsing. The parser stops
translation at the offending line (line with wrong syntax) and displays
a little ‘arrow’ pointing at the earliest point in the line where the error
was detected.
Syntax Errors - Examples 28

Code with Error Message Corrected


Code
23=A SyntaxError:can't assign to A=23
literal
A=90,B=100 SyntaxError: can't assign to A=90;B=100
literal
print("Hello")) SyntaxError: unmatched ')' print("Hello")
City="Mumbai' SyntaxError: EOL while City="Mumbai"
scanning string literal
A=10 SyntaxError: unexpected A=10
B=20 indent B=20
print(A+B) print(A+B)
Logical Errors 29

These errors occur due to wrong use of formula or expression by the


programmer. Due to this, the program produces wrong results while
execution.
Example of Logical Error:
If following statement is written by the If following statement is written
programmer to calculate Average by the programmer to calculate
marks of three subjects, it is a Logical Area of rectangle, it is a Logical
error. error.
Avg=English + Maths + Science / 3 Area = Length + Breadth

Correct Code after removal of Logical Correct Code after removal of


Error Logical Error
Avg=(English + Maths + Science)/3 Area = Length * Breadth
Run-time Errors/Exceptions 30

Run-Time/Execution-Time Error: These errors are encountered during


execution of the program due to unexpected input or output or
calculation.
Example of Run-Time/Execution-Time Error/Exceptions
A=int(input("Numerator"))
B=int(input("Denominator"))
C=A/B;
print(C)
The program shown above will The program shown above will throw
throw an Exception an Exception (ValueError), if user
(ZeroDivisionError), if user enters a non numeric value for
enters 0 for the variable B. example Hello for any of the
variables A or B.
31

Thank You
Computer Science Department
Delhi Public School, R.K.Puram

You might also like