Python PPT 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

Multi-Line Statements

• Statements in Python typically end with a new line. Python, however, allows the use of the line
continuation character (\) to denote that the line should continue. For example
total= item_one + \
item_two + \
item_three
• The statements contained within the [], {}, or () brackets do not need to use the line continuation character.
For example
days= ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']

• Multiple Statements on a Single Line


• The semicolon ( ; ) allows multiple statements on a single line given that no statement starts a new code
block. Here is a sample snip using the semicolon
• Import sys; x = 'foo'; sys.stdout.write(x + '\n’)`
1
Quotation in Python
• Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string. The triple quotes are used to span the string across
multiple lines.
• For example, all the following are legal
word= 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

2
Standard Data Types

The data stored in memory can be of many types. For example, a


person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the
storage method for each of them.

Python has five standard data types-


•Numbers
•String
•List
•Tuple
•Dictionary

3
Python Numbers

Number data types store numeric values. Number objects are created when you assign a
value to them. For example
var1= 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement.
For example
del var
del var_a, var_b
Python supports three different numerical types −
• int (signed integers) eg: 100
• float (floating point real values) eg: 32.3+e18
• complex (complex numbers) eg: 9.322e-36j

4
Data Type Conversion

•Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type-name as a function.
•There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.

5
Data Type Conversion

6
Basic Operators

Types of Operator

Python language supports the following types of operators-


•Arithmetic Operators
•Comparison (Relational) Operators
•Assignment Operators
•Logical Operators
•Bitwise Operators
•Membership Operators
•Identity Operators

7
Python Arithmetic
Operators

8
Python Comparison Operators

9
Python Assignment
Operators
Assume variable a
holds 10 and variable
b holds 20

10
Python Bitwise Operators
Assume if
a = 60; and
b = 13;
a= 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

function bin() can be


used to obtain binary
representation of an
integer number.

11
Python Logical Operators
Assume variable
a holds True and
variable b holds False

12
Python Membership Operators
Python’s membership
operators test for
membership in a
sequence, such as
strings, lists,
or tuples.

13
Python Identity Operators
Identity operators
compare the memory
locations of two objects.
There are two Identity
operators as explained
below:

Line 1 a= 20 : 1594701888
b= 20 : 1594701888
Line 2 - a and b have same identity

14
Python Operators
Precedence

15
Python Operators
Precedence

16
Python Programming Development Cycle

17
Interacting with Python

•Starting the Interpreter


•Command Line
•Through IDE (IDLE)

18
Starting the Interpreter
In Windows, there will likely be a program group in the Start menu
labeled Python 3.x, and under it a menu item labeled Python 3.x (32-
bit), or something similar.
Clicking on that item will start the Python interpreter:

19
Command Line
•In Windows, it is called Command Prompt.
•In macOS or Linux, it should be called Terminal.

20
Executing Python Code
1. Ensure that the >>> prompt is displayed, and the cursor is
positioned after it.
2. Type the command print("Hello, World!") exactly as shown.
3. Press the Enter key.

21
Exiting the Interpreter
When you are finished interacting with the interpreter, you can exit a
REPL session in several ways:
•Type exit() and press Enter:
•In Windows, type Ctrl+Z and press Enter:

22
Running a Python Script from the
Command Line
•Windows: Notepad
•Unix/Linux: vi or vim
•macOS: TextEdit
Using whatever editor you’ve chosen,
create a script file
called hello.py containing the
following:

23
Interacting with Python through an
IDE
IDEs usually provide capability as well as an editor with which you can
create and modify code to then submit to the interpreter for execution.

You may also find cool features such as:


•Syntax highlighting: IDEs often colorize different syntax elements in the
code to make it easier to read.
•Context-sensitive help: Advanced IDEs can display related information
from the Python documentation or even suggested fixes for common types
of code errors.
•Code-completion: Some IDEs can complete partially typed pieces of code
(like function names) for you—a great time-saver and convenience feature.
•Debugging: A debugger allows you to run code step-by-step and inspect
program data as you go. This is invaluable when you are trying to
determine why a program is behaving improperly, as will inevitably
happen. 24
IDLE
Most Python installations contain a rudimentary IDE called IDLE. The name ostensibly
stands for Integrated Development and Learning Environment.
Go to the Start menu and select All Programs or All Apps. There should be a program
icon labeled IDLE (Python 3.x 32-bit) or something similar. 
The interpreter behaves more or less the same as when you ran it directly from the
console. The IDLE interface adds the perk of displaying different syntactic elements in
distinct colors to make things more readable.

25
Features of IDLE
 
The interpreter behaves more or less the same as when you ran it directly from the
console. The IDLE interface adds the perk of displaying different syntactic elements in
distinct colors to make things more readable.
It also provides context-sensitive help. For example, if you type print( without typing any
of the arguments to the print function or the closing parenthesis, then flyover text should
appear specifying usage information for the print() function.

One other feature IDLE provides is statement recall:


•If you have typed in several statements, you can recall them with Alt+P and Alt+N in
Windows or Linux.
•Alt+P cycles backward through previously executed statements; Alt+N cycles forward.
•Once a statement has been recalled, you can use editing keys on the keyboard to edit it
and then execute it again.

26
Features of IDLE
You can also create script files and run them in IDLE. From the Shell window menu,
select File → New File. That should open an additional editing window. Type in the code
to be executed.

From the menu in that window, select File → Save or File → Save As… and save the file to
disk. Then select Run → Run Module. The output should appear back in the interpreter
Shell window:

27
Numbers
 Numbers are Immutable objects in Python that cannot change their
values.
 There are three built-in data types for numbers in Python3:
•• Integer (int) numbers (float)
Floating-point
•Complex numbers: <real part> + <imaginary (not used much in Python
programming)
part>jNumber
 Common
Functions
Function Description
int(x) to convert x to an integer
float(x) to convert x to a floating-point number
abs(x) The absolute value of x
cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: ex
log(x) The natural logarithm of x, for x> 0
pow(x,y) The value of x**y
sqrt(x) The square root of x for x > 0
28
Numbers

29
Numbers

30
Strings
 Python Strings are Immutable objects that cannot change their
values.

 You can update an existing string by (re)assigning a variable to another string.


 Python does not support a character type; these are treated as strings of length one.
 Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals.

 String indexes starting at 0 in the beginning of the string and working their way from -
1
at the end.

31
Strings
 String Formatting

 Common String Operators


Assume string variable a holds 'Hello' and variable b holds
'Python’
Operator Description Example

+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple copies a*2 will give HelloHello
of the same string

[] Slice - Gives the character from the given index a[1] will give e
a[-1] will give
o
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given string ‘H’ in a will give True
32
Strings

33
Strings

34
Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" 1 # comparison
• "e" in "hello" 1 # search
• "escapes: \n etc, \033 etc"
• 'single quotes' """triple quotes""" r"raw strings"

35
Strings
 Common String
Methods
Method Description
str.count(sub, Counts how many times sub occurs in string or in a substring of
beg= string if starting index beg and ending index end are given.
0,end=len(str))
str.isalpha() Returns True if string has at least 1 character and all characters
are alphanumeric and False otherwise.
str.isdigit() Returns True if string contains only digits and False otherwise.
str.lower() Converts all uppercase letters in string to lowercase.
str.upper() Converts lowercase letters in string to uppercase.
str.replace(old, new) Replaces all occurrences of old in string with new.

str.split(str=‘ ’) Splits string according to delimiter str (space if not


provided) and returns list of substrings.
str.strip() Removes all leading and trailing whitespace of string.
str.title() Returns "titlecased" version of string.

 Common String str(x) :to convert x to a string


Functions len(string):gives the total length of the
string
36

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