Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Lesson 1b Introduction To Python

Uploaded by

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

Lesson 1b Introduction To Python

Uploaded by

jemutaijemimah
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Introduction to Python

Setting Up the Python Environment .


A First Python Program

Notes/Homework
1. Install Python. You can get the latest version at www.python.org.

Linux and OS X users: You should already have Python installed – to test this, run the command
python in console mode. Note that the first line tells you the version number: you may want to
upgrade your installation if you have a version earlier than 2.3.

Windows users: Grab the windows installer from the Downloads section. After installation, you
can run the IDLE (Python GUI) command from the Start menu.
1. Reading. Read 1.1-1.2, 1.8-1.9, and chapter 2 from the textbook.

2. Writing Programs. Recall that a program is just a set of instructions for the computer to execute.
Let’s start with a basic command:

print x: Prints the value of the expression x, followed by a newline.


print x: Prints the value of the expression x, followed by a newline.

Program Text:

print “Hello World!”

print “How are you?”

Output:

Hello World!

How are you?

(The compiler needs those quotation marks to identify strings – we’ll talk about this later.) Don’t
worry, we’ll be adding many more interesting commands later! For now, though, we’ll use this to
have you become familiar with the administrative details of writing a program.

Write a program that, when run, prints out a tic-tac-toe board.

Linux and OS X users: To write your program, just create a text file with the contents of
the program text (e.g. the program text above.) To run your program (pretend its
named first_print.py), use the command python first_print.py at the shell.

Windows users: The best way to program in Windows is using the IDLE GUI (from the shortcut
above.) To create a new program, run the command File->New Window (CTRL+N) – this will
open up a blank editing window. In general, save your program regularly; after saving, you
can hit F5 to run your program and see the output.

Make sure to write your program using the computer at least once! The purpose of this question
is to make sure you know how to write programs using your computing environment; many
students in introductory courses experience trouble with assignments not because they have
trouble with the material but because of some weird environment quirk.

You can write the answer to the question in the box below (I know its hard to show spaces while writing
– just do your best)

Program Text:
Interpreter Mode. Python has a write-as-you-go mode that’s useful when testing small snippets of code.
You can access this by running the command python at the shell (for OS X and Linux) or by starting the
IDLE GUI (for Windows) – you should see a >>> prompt. Try typing a print command and watch what
happens.

You’ll find that its much more convenient to solve a lot of the homework problems using the interpreter.
When you want to write an actual, self-contained program (e.g. writing the game tic-tac-toe), follow the
instructions in section 3 above.

5. Variables. Put simply, variables are containers for storing information. For example:
Program Text:

a = “Hello World!” print a

Output:

Hello World!

The = sign is an assignment operator which says: assign the value “Hello World!” to the variable a.

Program Text:

a = “Hello World!” a = “and goodbye..” print a

Output:

and goodbye..

Taking this second example, the value of a after executing the first line above is “Hello World!”, and
after the second line its “and goodbye..” (which is what gets printed)
In Python, variables are designed to hold specific types of information. For example, after the first com-
mand above is executed, the variable a is associated with the string type. There are several types of in-
formation that can be stored:

Boolean. Variables of this type can be either True or False.


Integer. An integer is a number without a fractional part, e.g. -4, 5, 0, -3.
Float. Any rational number, e.g. 3.432. We won’t worry about floats for today.
String. Any sequence of characters. We’ll get more in-depth with strings later in the week.

Python (and many other languages) are zealous about type information. The string “5” and integer 5 are
completely different entities to Python, despite their similar appearance. You’ll see the importance of
this in the next section.

Write a program that stores the value 5 in a variable a and prints out the value of a, then stores the
value 7 in a and prints out the value of a (4 lines.)

Program Text:

Expected Output:

57

6. Operators. Python has the ability to be used as a cheap, 5-dollar calculator. In particular, it supports
basic mathematical operators: +, -, *, /.

Program Text:

a= 5+7 print a

Output:

12

Variables can be used too.

Program Text:

a= 5 b=a+7 print b
Output:

12

Expressions can get fairly complex.

Program Text:

a = (3+4+21) / 7 b = (9*4) / (2+1) -6 print (a*b)-(a+b)

Output:

14

These operators work on numbers. Type information is important – the following expressions would
result in an error.

“Hello” / 123 “Hi” + 5 “5” + 7 The last one is especially important! Note
that Python just sees that 5 as a string – it has no concept of it possibly being a number.

Some of the operators that Python includes are Addition, Subtraction, Multiplication. a+b, a-b, and a*b re-
spectively. Integer Division. a/b. Note that when division is performed with two integers, only the quo-
tient is returned (the remainder is ignored.) Try typing print 13/6 into the interpreter Exponentiation
b
(a ). a ** b.

Operators are evaluated using the standard order of operations. You can use parentheses to forcecer-
tain operators to be evaluated first.Let’s also introduce one string operation.

Concatenation. a+b. Combines two strings into one. “Hel” + “lo” would yield “Hello” Another exam-

ple of type coming into play! When Python sees a + b, it checks to see what type a and b
are. If they are both strings Output: _______________________________________
then it concatenates the
two; if they are both integers
it adds them; if one isa string
and the other is an integer, it
returns an error.Write the
output of the following lines
of code (if an error would re-
sult, write error):
print 13 + 6
print 2 ** 3 Output: _______________________________________
print 2 * (1 + 3) Output: _______________________________________
print 8 / 9 Output: _______________________________________
print “13” + “6” Output: _______________________________________
print “13” + 6 Output: _______________________________________
Python is a widely used
general-purpose, high level
programming language. It
was initially
designed by Guido van
Rossum in 1991 and
developed by Python
Software Foundation. It
was mainly developed for
emphasis on code
readability, and its syntax
allows programmers
to express concepts in
fewer lines of code.
Python is a programming
language that lets you
work quickly and integrate
systems more
efficiently.
There are two major
Python versions- Python 2
and Python 3.
• On 16 October 2000,
Python 2.0 was released
with many new features.
• On 3rd December 2008,
Python 3.0 was released
with more testing and
includes new
features.
Beginning with Python
programming:
1) Finding an Interpreter:
Before we start Python
programming, we need to
have an interpreter to
interpret and run our
programs. There are
certain online interpreters
like
https://ide.geeksforgeeks.o
rg/,
http://ideone.com/ or
http://codepad.org/ that can
be used to start Python
without installing
an interpreter.
Windows: There are many
interpreters available
freely to run Python scripts
like IDLE
(Integrated Development
Environment) which is
installed when you install
the python
software from
http://python.org/download
s/
2) Writing first program:
# Script Begins
Statement1
Statement2
Statement3
# Script Ends
Differences between scripting language and programming language:
Why to use Python:
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python
3. It’s free (open source)
Downloading python and installing python is free and easy
4. It’s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. Numeric, NumPy, sciPy)
 Automatic memory management
5. It’s Portable
 Python runs virtually every major platform used today
 As long as you have a compatible python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
 This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.

Installation:
There are many interpreters available freely to run Python scripts like IDLE (Inte-
grated
Development Environment) which is installed when you install the python soft-
ware
from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install.
Step 2: Download Python Executable Installer.
Step 3: Run Executable Installer.
Step 4: Verify Python Was Installed On Windows.
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
Working with Python
Python Code Execution:
Python’s traditional runtime execution model: Source code you type is trans-
lated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is auto-
matically
compiled, but then it is interpreted.
Source code byte code runtime

M.PY M.PYC PVM


Source code extension is .py
Byte code extension is .pyc (Compiled python code)
There are two modes for using the Python interpreter:
• Interactive Mode
• Script Mode

Running Python in interactive mode:


Without passing python script file to the interpreter, directly execute code to
Python prompt.
Once you’re inside the python interpreter, then you can start.
>>> print("hello world")
hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2]
>>> 2+3
5

The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the
python
interpreter uses to indicate that it is ready. If the programmer types 2+6, the inter-
preter
replies 8.
Running Python in script mode:
Alternatively, programmers can store Python script source code in a file with
the .py extension, and use the interpreter to execute the contents of the file. To exe-
cute the
script by the interpreter, you have to tell the interpreter the name of the file. For ex-
ample, if
you have a script name MyFile.py and you're working on Unix, to run the script
you have to
type:
python MyFile.py
Working with the interactive mode is better when Python programmers deal with
small
pieces of code as you can type and execute them immediately, but when the code is
more
than 2-4 lines, using the script for coding can help to modify and use the code in
future
Data types:
The data stored in memory can be of many types. For example, a student roll num-
ber is
stored as a numeric value and his or her address is stored as alphanumeric charac-
ters. Python
has various standard data types that are used to define the operations possible on
them and
the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlim-
ited
length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
PYTHON PROGRAMMING III YEAR/II SEM MRCET
7
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one
or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
PYTHON PROGRAMMING III YEAR/II SEM MRCET
8
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
1. Strings in Python are identified as a contiguous set of characters represented in
the
quotation marks. Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example:
print("hello").
>>> print("mrcet college")
mrcet college
>>> type("mrcet college")
<class 'str'>
PYTHON PROGRAMMING III YEAR/II SEM MRCET
9
>>> print('mrcet college')
mrcet college
>>> " "
''
If you want to include either type of quote character within the string, the simplest
way is to
delimit the string with the other type. If a string is to contain a single quote, delimit
it with
double quotes and vice versa:
>>> print("mrcet is an autonomous (') college")
mrcet is an autonomous (') college
>>> print('mrcet is an autonomous (") college')
mrcet is an autonomous (") college
Suppressing Special Character:
Specifying a backslash (\) in front of the quote character in a string “escapes” it
and causes
Python to suppress its usual special meaning. It is then interpreted simply as a lit-
eral single
quote character:
>>> print("mrcet is an autonomous (\') college")
mrcet is an autonomous (') college
>>> print('mrcet is an autonomous (\") college')
mrcet is an autonomous (") college
The following is a table of escape sequences which cause Python to suppress the
usual
special interpretation of a character in a string:
>>> print('a\
....b')
a....b
>>> print('a\
b\
c')
PYTHON PROGRAMMING III YEAR/II SEM MRCET
10
abc
>>> print('a \n b')
a
b
>>> print("mrcet \n college")
mrcet
college
Escape
Sequence
Usual Interpretation of
Character(s) After Backslash “Escaped” Interpretation
\' Terminates string with single quote opening delimiter Literal single quote (') character
\" Terminates string with double quote opening delimiter Literal double quote (") character
\newline Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash (\) character
In Python (and almost all other common computer languages), a tab character can
be
specified by the escape sequence \t:
>>> print("a\tb")
ab
List:
 It is a general purpose most widely used in data structures
 List is a collection which is ordered and changeable and allows duplicate mem-
bers.
(Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
 We can construct / create list in many ways.
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
PYTHON PROGRAMMING III YEAR/II SEM MRCET
11
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
Variables are nothing but reserved memory locations to store values. This means
that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can
be stored in the reserved memory. Therefore, by assigning different data types to
variables,
you can store integers, decimals or characters in these variables.
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 vari-
ables)
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.
The operand to the left of the = operator is the name of the variable and the oper-
and to the
right of the = operator is the value stored in the variable.
PYTHON PROGRAMMING III YEAR/II SEM MRCET
12
For example −
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
This produces the following result −
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are as-
signed to the
same memory location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b re-
spectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change
type after
they have been set.
PYTHON PROGRAMMING III YEAR/II SEM MRCET
13
x = 5 # x is of type int
x = "mrcet " # x is now of type str
print(x)
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Expressions:
An expression is a combination of values, variables, and operators. An expression
is
evaluated using assignment operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30
PYTHON PROGRAMMING III YEAR/II SEM MRCET
14
>>> x=10
>>> y=20
>>> c=x+y
>>> c
30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y
20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or
object is
an identifier.
Literals: These are language-independent terms in Python and should exist inde-
pendently in
any programming language. In Python, there are the string literals, byte literals, in-
teger
literals, floating point literals, and imaginary literals.
Operators: In Python you can implement the following operations using the corre-
sponding
tokens.
Operator Token
add +
subtract -
multiply *
Integer Division /

remainder %
Binary left shift <<
Binary right shift >>
and &
or \
Less than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Check equality ==
Check not equal !=

Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning
that the
whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In
python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line comment-
ing.
Example:

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py
30

You might also like