0% found this document useful (0 votes)
17 views47 pages

Python Programming Basics: Quickstart Guide

Uploaded by

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

Python Programming Basics: Quickstart Guide

Uploaded by

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

Python Programming

Module 1
PYTHON : QUICKSTART
• Let's write our first Python file, called [Link], which can be
done in any text editor.
[Link]
print("Hello, World!")
• Save the file. Open command line, navigate to the directory where
you saved your file, and run:
C:\Users\Your Name>python [Link]
• Output:
Hello, World!
PYTHON INDENTATION
• In other programming languages, indentation in code is for readability
only.
• Python uses indentation to indicate a block of code.
• Example(Error): if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation.
• Example(Correct): if 5 > 2:
print("Five is greater than two!")
PYTHON COMMENTS
1. Comments can be used to explain Python code.
2. Comments can be used to make the code more readable.
3. Comments can be used to prevent execution when testing code.
Creating comments
• Comments starts with a #.
Example:
#This is a comment
print("Hello, World!")
• Comments does not have to be text to explain the code, it can also be used
to prevent Python from executing code:
Example:
#print("Hello, World!")
print("Cheers, Mate!")
CREATING VARIABLES
• Variables are containers for storing data values.
• 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.
Example:
x=5
y = "John"
print(x)
print(y)
CREATING VARIABLES
• Variables do not need to be declared with any particular type and can even change type after
they have been set.

Example:
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
• String variables can be declared either by using single or double quotes
Example
x = "John"
# is the same as
x = 'John'
VARIABLE NAMES
• A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three
different variables)
ASSIGNING VALUE TO MULTIPLE VARIABLES
• Python allows you to assign values to multiple variables in one line:
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• The same value can be assigned to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
OUTPUT VARIABLES
• Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
Example:
x = "awesome"
print("Python is " + x)
+ character can also be used to add a variable to another variable
Example:
x = "Python is "
y = "awesome"
z= x+y
print(z)
PYTHON KEYWORDS
• Python keywords are the words that are reserved, i.e, they cannot be
used as name of any entities like variables, classes and functions.
• They are used for defining the syntax and structures of Python
language.
• There are 33 keywords in Python programming language. Keywords in
Python are case sensitive. So they are to be written as it is.
PYTHON IDENTIFIERS
• Python Identifier is the name we give to identify a variable, function,
class, module or other object.
Rules for writing Identifiers
1. Identifiers can be combination of uppercase and lowercase letters,
digits or an underscore(_).
Example:
myVariable, variable_1, variable_for_print
2. An Identifier can not start with digit.
Example:
variable1 is valid
1variable is not valid.
PYTHON IDENTIFIERS
3. Special symbols like !,#,@,%,$ etc cannot be used.
>>> a@ = 0
File "<interactive input!>", line 1
a@ = 0
^
SyntaxError: invalid syntax
4. Identifier can be of any length.
5. Keywords cannot be used as identifiers
NAMING CONVENTIONS
Naming conventions which are not mandatory but rather good practices to
follow.
1. Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
2. Starting an identifier with a single leading underscore indicates the
identifier is private.
3. If the identifier starts and ends with two underscores, that means the
identifier is language-defined special name.
4. While c = 10 is valid, writing count = 10 would make more sense and it
would be easier to figure out what it does even when you look at your code
after a long time.
5. Multiple words can be separated using an underscore, for
example this_is_a_variable.
PROGRAM – PYTHON VARIABLES

myVariable="hello world"
print(myVariable)
var1=1
print(var1)
var2=2
print(var2)
DATA TYPES
Integral Types:
• Python provides two built-in integral types, int and bool.
• Both integers and Booleans are immutable.
• When used in Boolean expressions, 0 and False are False, and any
other integer and True are True.
• When used in numerical expressions True evaluates to 1 and False to
0.
Example:
we can increment an integer I using the expression i += True.
BASIC DATA TYPES
Python has five standard data types
Numbers Boolean String List Tuple
Python supports different numerical types. They are
• int (signed integers) − They are often called just integers or ints, are positive or
negative whole numbers with no decimal point.
• long (long integers ) − Also called longs, they are integers of unlimited size,
written like integers and followed by an uppercase or lowercase L.
• float (floating point real values) − Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and fractional
parts. Floats may also be in scientific notation, with E or e indicating the power of
10 (2.5e2 = 2.5 x 102 = 250).
• complex (complex numbers) − are of the form a + bJ, where a and b are floats
and J (or j) represents the square root of -1 (which is an imaginary number). The
real part of the number is a, and the imaginary part is b. Complex numbers are
not used much in Python programming.
INTEGER DATA TYPE
• The size of an integer is limited only by the machine’s memory.
NUMERIC OPERATORS AND FUNCTIONS
OBJECT WITH DATA TYPE
When an object is created using its data type there are three possible use
cases.
1. The first use case is when a data type is called with no arguments. In this
case an object with a default value is created—for example, x = int() creates
an integer of value 0. All the built-in types can be called with no arguments.
2. The second use case is when the data type is called with a single
argument. If an argument of the same type is given, a new object which is a
shallow copy of the original object is created. If an argument of a different
type is given, a conversion is attempted. This use is shown for the int type in
Integer conversion functions . If the argument is of a type that supports
conversions to the given type and the conversion fails, a ValueError
exception is raised; otherwise, the resultant object of the given type is
returned. If the argument’s data type does not support conversion to the
given type a TypeError exception is raised. The built-in float and str types
both provide integer conversions;
OBJECT WITH DATA TYPE
3. The third use case is where two or more arguments are given—not
all types support this, and for those that do the argument types and
their meanings vary. For the int type two arguments are permitted
where the first is a string that represents an integer and the second is
the number base of the string representation. For example, int("A4",
16) creates an integer of value 164. This use is shown in Integer
conversion functions
BITWISE OPERATORS
BITWISE OPERATORS- Example
BOOLEAN DATA TYPE
• There are two built-in Boolean objects:
True and False
FLOATING POINT TYPES
• Python provides three kinds of floating-point values:
1. Built-in float 2. Complex types [Link]
• Type float holds double-precision floating-point numbers whose
range depends on the C (or C# or Java) compiler Python was built
with.
• Numbers of type float are written with a decimal point, or using
exponential notation.
• Example:
0.0, 4., 5.7, -2.5, -2e9, 8.9e-4.
FLOATING POINT NUMBERS
• The float data type can be called as a function—
1. with no arguments it returns 0.0,
2. with a float argument it returns a copy of the argument,
3. and with any other argument it attempts to convert the given
object to a float
FLOATING POINT NUMBERS
FLOATING POINT NUMBERS
FLOATING POINT NUMBERS
>>>import math
>>> [Link] * (5 ** 2)
# Python 3.1 outputs: 78.53981633974483

>>> [Link](5, 12)


13.0

>>> [Link](13.732)
# Python 3.1 outputs: (0.7319999999999993, 13.0 )
Complex Numbers
• The complex data type is an immutable type that holds a pair of
floats, one representing the real part and the other the imaginary
part of a complex number
>>> z = -89.5+2.125j
>>> [Link], [Link]
(-89.5, 2.125)
• //, %, divmod(), and the three-argument pow() cannot be used for
complex numbers
• conjugate(), which changes the sign of the imaginary part
[Link]() (3+4j)
Decimal Numbers
• The decimal module provides immutable Decimal numbers that are as
accurate as we specify.
• Calculations involving Decimals are slower than those involving floats, but
whether this is noticeable will depend on the application
• To create a Decimal we must import the decimal module.
• For example:
>>> import decimal
>>> a = [Link](9876)
>>> b = [Link]("54321.012345678987654321")
>>> a + b
Decimal('64197.012345678987654321'
Decimal Numbers
>>> 23 / 1.05
21.904761904761905
>>> print(23 / 1.05)
21.9047619048
>>> print([Link](23) / [Link]("1.05"))
21.90476190476190476190476190
Strings
• Strings are represented by the immutable str data type which holds a
sequence of Unicode characters.
• The str data type can be called as a Character encodings function to
create string objects
• The str() function can also be used as a conversion function, in which
case the first argument should be a string or something convertable
to a string, with up to two optional string arguments being passed,
one specifying the encoding to use and the other specifying how to
handle encoding errors.
• Python treats single quotes the same as double quotes.
• Python does not support a character type; these are treated as strings
of length one, thus also considered a substring.
Strings
• Example
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, [Link]) [MSC v.1600 32 bit (Intel)] on
win32

Type "copyright", "credits" or "license()" for more information.

>>> var1='hello';var2="world"

>>> var1 'hello'

>>> var2 'world'


>>>
Strings
• We can join two strings together by putting them side by side:
• 'Albert' 'Einstein'
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, [Link]) [MSC v.1600 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


>>> str="Albert"" ""Enistein"

>>> print(str)

Albert Enistein
>>>
Strings
Comparing Strings
• Strings support the usual comparison operators <, <=, ==, !=, >, and
>=. These operators compare strings byte by byte in memory
Slicing and Striding Strings
• Individual characters in a string, can be extracted using the item
access operator ([]). In fact, this operator is much more versatile and
can be used to extract not just one item or character, but an entire
slice (subsequence) of items or characters, in which context it is
referred to as the slice operator.
• First we will begin by looking at extracting individual characters. Index
positions into a string begin at 0 and go up to the length of the string
minus 1. But it is also possible to use negative index positions—these
count from the last character back toward the first.
Slicing and Striding Strings
• Given the assignment s = "Light ray",

• Negative indexes are surprisingly useful, especially -1 which always gives us


the last character in a string. Accessing an out-of-range index (or any index
in an empty string) will cause an IndexError exception to be raised.
Slicing and Striding Strings
The slice operator has three syntaxes:
• seq[start]
• seq[start:end]
• seq[start:end:step]
The seq can be any sequence, such as a list, string, or tuple. The start,
end, and step values must all be integers (or variables holding
integers).We have used the first syntax already: It extracts the start-th
item from the sequence. The second syntax extracts a slice from and
including the start-th item, up to and excluding the end-th item.
Slicing and Striding Strings
Given the assignment s = "The waxwork man",
Figure 2.2 shows some example slices for string s.

>>> s = s[:12] + "wo" + s[12:]


>>> s
'The waxwork woman'
Slicing and Striding Strings
Built-in String Methods
Built-in String Methods
Built-in String Methods
Built-in String Methods
Built-in String Methods

You might also like