[Go to site: main page, start]

0% found this document useful (0 votes)
7 views18 pages

Python Basics: Syntax, Variables, Operators

The document provides a comprehensive overview of Python programming, covering basic syntax, variable types, operators, decision making, loops, lists, tuples, and dictionaries. It includes examples of how to use these concepts in Python code. Additionally, it offers links for further practice exercises for beginners.

Uploaded by

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

Python Basics: Syntax, Variables, Operators

The document provides a comprehensive overview of Python programming, covering basic syntax, variable types, operators, decision making, loops, lists, tuples, and dictionaries. It includes examples of how to use these concepts in Python code. Additionally, it offers links for further practice exercises for beginners.

Uploaded by

pannphyu24497
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python

[Link]
(I) Python Basic Syntax

(II) Python - Variable Types

(III) Python - Basic Operators

(IV) Python - Decision Making

(V) Python – Loops

(VI) Python Lists

(VII) Python - Tuples

Exercises
Then, Pls practice python exercises from the below link

[Link]
(I) Python Basic Syntax

(1)Interactive Mode Programming

$ python
>>> print "Hello, Python!"

Result is Hello, Python!

Python files have extension .py. Type the following source code in a [Link] file −

print "Hello, Python!"

Now, try to run this program as follows −

$ python [Link]

This produces the following result −

Hello, Python!

(2) Reserved Words


and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

(3) Lines and Indentation


Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation
if True:
print "True"
else:
print "False"
(4) Multi-Line Statements
total = item_one + \
item_two + \
item_three

(5) 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.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

(6) Comments in Python


Single line comment #
# First comment
print "Hello, Python!" # second comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

multiline comments: ‘’’ ‘’’

'''
This is a multiline
comment.
'''

(7) Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line

import sys; x = 'foo'; [Link](x + '\n')


(8) Multiple Statement Groups as Suites

A group of individual statements, which make a single code block are called suites in Python.
Compound or complex statements, such as if, while, def, and class require a header line and a
suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are
followed by one or more lines which make up the suite.

if expression :
suite
elif expression :
suite
else :
suite

(II) Python - Variable Types

(1) Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name

(2) Multiple Assignment


a=b=c=1
a,b,c = 1,2,"john"

(3) Standard Data Types

Python has five standard data types

 Numbers
 String
 List
 Tuple
 Dictionary
(i)Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them.
var1 = 1
var2 = 10

Python supports four different numerical types −

 int (signed integers)


 long (long integers, they can also be represented in octal and hexadecimal)
 float (floating point real values)
 complex (complex numbers)

(ii) Python Strings


str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

(iii) Python Lists


Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). The values stored in a list can be accessed
using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

(iv) Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists.

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints the complete tuple


print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples

This produce the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
(v) Python Dictionary

Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but
are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one'] # Prints value for 'one' key


print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print [Link]() # Prints all the keys
print [Link]() # Prints all the values

This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
(4)Data Type Conversion

int(x[,base]) Converts x to an integer. Base specifies the base if x is a string

long(x [,base] )Converts x to a long integer. base specifies the base if x is a string.

float(x) Converts x to a floating-point number.

str(x)Converts object x to a string representation.

tuple(s) Converts s to a tuple.\

list(s)Converts s to a list.
(III) Python - Basic Operators

(1)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

Python Arithmetic Operators


Operator Description Example
Adds values on either side of the
+ Addition a + b = 30
operator.
Subtracts right hand operand from left
- Subtraction a – b = -10
hand operand.
* Multiplies values on either side of the
a * b = 200
Multiplication operator
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power)
** Exponent a**b =10 to the power 20
calculation on operators

Floor Division - The division of


operands where the result is the quotient
in which the digits after the decimal
// 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -
point are removed. But if one of the
operands is negative, the result is
floored, i.e., rounded away from zero
(towards negative infinity) −
Python Comparison Operators

Operator Description Example


If the values of two operands are equal,
== (a == b) is not true.
then the condition becomes true.
If values of two operands are not equal,
!= (a != b) is true.
then condition becomes true.
If values of two operands are not equal, (a <> b) is true. This is similar to !=
<>
then condition becomes true. operator.
If the value of left operand is greater than
> the value of right operand, then condition (a > b) is not true.
becomes true.
If the value of left operand is less than the
< value of right operand, then condition (a < b) is true.
becomes true.
If the value of left operand is greater than
>= or equal to the value of right operand, (a >= b) is not true.
then condition becomes true.
If the value of left operand is less than or
equal to the value of right operand, then
<= (a <= b) is true.
condition becomes true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then

Operator Description Example

Assigns values from right side operands


= c = a + b assigns value of a + b into c
to left side operand

+= Add It adds right operand to the left operand


c += a is equivalent to c = c + a
AND and assign the result to left operand

-= It subtracts right operand from the left


Subtract operand and assign the result to left c -= a is equivalent to c = c - a
AND operand
*= It multiplies right operand with the left
Multiply operand and assign the result to left c *= a is equivalent to c = c * a
AND operand

It divides left operand with the right


/= Divide
operand and assign the result to left c /= a is equivalent to c = c / a
AND
operand

%=
It takes modulus using two operands and
Modulus c %= a is equivalent to c = c % a
assign the result to left operand
AND

**= Performs exponential (power) calculation


Exponent on operators and assign value to the left c **= a is equivalent to c = c ** a
AND operand

//= Floor It performs floor division on operators


c //= a is equivalent to c = c // a
Division and assign value to the left operand

Python Logical Operators


Operator Description Example
and
If both the operands are true then
Logical (a and b) is true.
condition becomes true.
AND
or Logical If any of the two operands are non-zero
(a or b) is true.
OR then condition becomes true.
not
Used to reverse the logical state of its
Logical Not(a and b) is false.
operand.
NOT

Python Identity Operators


Operator Description Example
Evaluates to true if the variables on either
x is y, here is results in 1 if id(x) equals
is side of the operator point to the same
id(y).
object and false otherwise.
Evaluates to false if the variables on
x is not y, here is not results in 1 if id(x) is
is not either side of the operator point to the
not equal to id(y).
same object and true otherwise.
(IV) Python - Decision Making
[Link]. Statement & Description

if statements An if statement consists of a boolean expression followed by one or more


1
statements.

if...else statements An if statement can be followed by an optional else statement,


2
which executes when the boolean expression is FALSE.

nested if statements You can use one if or else if statement inside another if or else if
3
statement(s).

Single Statement Suites


var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"

(V) Python – Loops

while loop Repeats a statement or group of statements while a given condition is TRUE. It
1
tests the condition before executing the loop body.

for loop Executes a sequence of statements multiple times and abbreviates the code that
2
manages the loop variable.

3 nested loops You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements


break statement
1
Terminates the loop statement and transfers execution to the statement immediately following
the loop.
continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
3 pass statement

The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute.

(VI) Python Lists


list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

Accessing Values in Lists


list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result −

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists

list = ['physics', 'chemistry', 1997, 2000];


print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

it produces the following result −

Value available at index 2 :


1997
New value available at index 2 :
2001

Delete List Elements

list1 = ['physics', 'chemistry', 1997, 2000];


print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the prior
chapter.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!', 'Hi!', 'Hi!',


['Hi!'] * 4 Repetition
'Hi!']

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print


123 Iteration
x,

Indexing, Slicing, and Matrixes


L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description
L[2] SPAM! Offsets start at zero
L[-2] Spam Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Built-in List Functions & Methods

Python includes the following list functions −

[Link]. Function with Description

cmp(list1, list2)
1
Compares elements of both lists.
len(list)
2
Gives the total length of the list.
3 max(list) Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.
list(seq)
5
Converts a tuple into list.

Python includes following list methods

[Link]. Methods with Description

[Link](obj)
1
Appends object obj to list
[Link](obj)
2
Returns count of how many times obj occurs in list
[Link](seq)
3
Appends the contents of seq to list
[Link](obj)
4
Returns the lowest index in list that obj appears
[Link](index, obj)
5
Inserts object obj into list at offset index
[Link](obj=list[-1])
6
Removes and returns last object or obj from list
[Link](obj)
7
Removes object obj from list
[Link]()
8
Reverses objects of list in place
[Link]([func])
9
Sorts objects of list, use compare func if given

(VII) Python - Tuples


Accessing Values in Tuples

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];

When the above code is executed, it produces the following result −

tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples


# tup1[0] = 100;

# So let's create a new tuple as follows


tup3 = tup1 + tup2;
print tup3;

Delete Tuple Elements

tup = ('physics', 'chemistry', 1997, 2000);


print tup;
del tup;
print "After deleting tup : ";
print tup;

This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist any more −

('physics', 'chemistry', 1997, 2000)


After deleting tup :
Traceback (most recent call last):
File "[Link]", line 9, in <module>
print tup;
NameError: name 'tup' is not defined

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration

Built-in Tuple Functions

Python includes the following tuple functions −

[Link]. Function with Description

cmp(tuple1, tuple2)
1
Compares elements of both tuples.
len(tuple)
2
Gives the total length of the tuple.
max(tuple)
3
Returns item from the tuple with max value.
min(tuple)
4
Returns item from the tuple with min value.

tuple(seq)

Converts a list into tuple.

Python – Dictionary

Accessing Values in Dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result −

dict['Name']: Zara
dict['Age']: 7
Updating Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

When the above code is executed, it produces the following result −

dict['Age']: 8
dict['School']: DPS School

Defining a Function
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

Calling a Function

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Python - Object Oriented


Creating Classes and Functions

The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows −

class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
[Link] = name
[Link] = salary
[Link] += 1

def displayCount(self):
print "Total Employee %d" % [Link]

def displayEmployee(self):
print "Name : ", [Link], ", Salary: ", [Link]

Then, Pls practice python exercises from the below link

[Link]

You might also like