Faculty of Engineering & Technology
Sankalchand Patel College of Engineering, Visnagar
Python Programming
(1ET2070201)
Unit-01
Introduction to Python
Content
• History of Python!
• Installation
• The basic elements of python
• Data types
• Operators
• Control Structures
• Strings
• Input
• Iteration
History of Python!
• Created in 1991 by Guido van Rossum (now at Google)
• Named for Monty Python
• Useful as a scripting language
• script: A small program meant for one-time use
• Targeted towards small to medium sized projects
• Used by:
• Google, Yahoo!, Youtube
• Many Linux distributions
• Games and apps (e.g. Eve Online)
Installing Python
Windows:
• Download Python from [Link]
• Install Python.
• Run Idle from the Start Menu.
Mac OS X:
• Python is already installed.
• Open a terminal and run python or run Idle from Finder.
Linux:
• Chances are you already have Python installed. To check, run python from the terminal.
• If not, install from your distribution's package system.
Interpreted Languages
• interpreted
• Not compiled like Java
• Code is written and then directly executed by an interpreter
• Type commands into interpreter and see immediate results
Java: Runtime
Code Compiler Computer
Environment
Python: Code Interpreter Computer
The Python Interpreter
• Allows you to type commands one-at-a-time and see results
• A great way to explore Python's syntax
• Repeat previous command: Alt+P
Programming in Script Mode
• Interactive mode gives you immediate feedback
• Not designed to create programs to save and run later
• Script Mode
• Write, edit, save, and run (later)
• Word processor for your code
• Save your file using the “.py” extension
Our First Python Program
• Python does not have a main method like Java
• The program's main code is just written directly in the file
• Python statements do not end with semicolons
[Link]
1 print("Hello, world!")
The print Statement
print("text")
print() (a blank line)
• Escape sequences such as \" are the same as in Java
• Strings can also start/end with '
[Link]
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it together.")
4 print('African or "European" swallows?')
Syntax Errors
• When the computer does not recognize the statement to be
executed, a syntax error is generated
• Analogous to a misspelled word in a programming language
• Bug
>>> print (“Game Over”)
SyntaxError: invalid syntax
Formatting Text
"format string" % (parameter, parameter, ...)
• Placeholders insert formatted values into a string:
• %d an integer
• %f a real number
• %s a string
• %8d an integer, 8 characters wide, right-aligned
• %08d an integer, 8 characters wide, padding with 0s
• %-8d an integer, 8 characters wide, left-aligned
• %12f a real number, 12 characters wide
• %.4f a real number, 4 characters after decimal
• %6.2f a real number, 6 total characters wide, 2 after decimal
>>> x = 3; y = 3.14159; z = "hello"
>>> print ("%-8s, %04d is close to %.3f" % (z, x, y))
hello , 0003 is close to 3.142
input
input : Reads a string from the user's keyboard.
• reads and returns an entire line of input *
>>> name = input("Howdy. What's yer name?")
Howdy. What's yer name? Paris Hilton
>>> name
'Paris Hilton'
input
• to read numbers, cast input result to an int or float
• If the user does not type a number, an error occurs.
• Example:
age = int(input("How old are you? "))
print("Your age is", age)
print(65 - age, "years to retirement")
Output:
How old are you? 53
Your age is 53
12 years to retirement
Comments
• Comment lines provide documentation about your program
• Anything after the “#” symbol is a comment
• Ignored by the computer
• Syntax:
# comment text (one line)
[Link]
1 # Suzy Student, CSE 142, Fall 2097
2 # This program prints important messages.
3 print("Hello, world!")
4 print() # blank line
5 print("Suppose two swallows \"carry\" it together.")
6 print('African or "European" swallows?')
Quotes and Strings
• Python provides other options for printing Strings
• A sequence of characters surrounded by “ “ or ‘ ‘
• the quotes inside other quotes!
"Program 'Game Over' 2.0"
• the triple quoted string!
"""
Game Over
"""
Expressions
• Arithmetic is very similar to Java
• Operators: + - * / % (and ** for exponentiation)
• Precedence: () then ** then * / % then + -
• Integers vs. real numbers
>>> 1 + 1
2
>>> 1 + 3 * 4 - 2
11
>>> 7 / 2
3
>>> 7.0 / 2
3.5
>>> 10 ** 6
1000000
Relational & Logical Operators
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
Operator Example Result
and (2 == 3) and (-1 < 5) False
or (2 == 3) or (-1 < 5) True
not not (2 == 3) True
Variables
• Declaring
• no type is written; same syntax as assignment
• Operators
• no ++ or -- operators (must manually adjust by 1)
Java Python
int x = 2; x = 2
x++; x = x + 1
[Link](x); print(x)
x = x * 8; x = x * 8
[Link](x); print(x)
double d = 3.2; d = 3.2
d = d / 2; d = d / 2
[Link](d); print(d)
Escape Sequences with Strings
• An escape sequence is a special sequence of characters that provide
more functionality to the displayed text.
• \\ Backslash, prints one backslash
• \’ Single quote, prints one single quote
• \” Double quote, prints one double quote
• \a Bell, sounds the system bell
• \b Backspace, moves the cursor back one space
• \n Newline, moves the cursor to the beginning of next line
• \t Horizontal tab, Moves cursor forward one tab stop
Types
• Python is looser about types than Java
• Variables' types do not need to be declared
• Variables can change types as a program is running
Value Java type Python type
42 int int
3.14 double float
"ni!" String str
bool
• Python's logic type, equivalent to boolean in Java
• True and False start with capital letters
>>> 5 < 10
True
>>> b = 5 < 10
>>> b
True
>>> if b:
... print("The value is true")
...
The value is true
>>> b = not b
>>> b
False
Repeating Strings
• Python strings can be multiplied by an integer.
• The result is many copies of the string concatenated together.
>>> "hello" * 3
"hellohellohello"
>>> print(10 * "yo ")
yo yo yo yo yo yo yo yo yo yo
>>> print(2 * 3 * "4")
444444
Strings and Integers
• ord(text) - Converts a string into a number.
• ord("a") is 97
• ord("b") is 98
• Uses standard mappings such as ASCII and Unicode.
• chr(number) - Converts a number into a string.
• chr(97) is "a"
• chr(99) is "c"
String Concatenation
• Integers and strings cannot be concatenated in Python.
• Workarounds:
str(value) - converts a value into a string
print(expr, expr) - prints two items on the same line
>>> x = 4
>>> print("Thou shalt not count to " + x + ".")
TypeError: cannot concatenate 'str' and 'int' objects
>>> print("Thou shalt not count to " + str(x) + ".")
Thou shalt not count to 4.
>>> print(x + 1, "is out of the question.")
5 is out of the question.
Strings
index 0 1 2 3 4 5 6 7
or -8 -7 -6 -5 -4 -3 -2 -1
character P . D i d d y
>>> name = "P. Diddy"
>>> name[0]
• Accessing character(s): 'P'
>>> name[7]
variable [ index ] variable [ 'y'
index1:index2 ] >>> name[-1]
'y'
>>> name[3:6]
'Did'
• index2 exclusive >>> name[3:]
• index1 or index2 can be 'Diddy'
>>> name[:-2]
omitted (goes to end of string) 'P. Did'
Slicing
• slice: A sub-list created by specifying start/end indexes
name[start:end] # end is exclusive
name[start:] # to end of list
name[:end] # from start of list
name[start:end:step] # every step'th value
>>> scores = [9, 14, 12, 19, 16, 18, 24, 15]
>>> scores[2:5]
[12, 19, 16]
>>> scores[3:]
[19, 16, 18, 24, 15]
>>> scores[:3]
[9, 14, 12]
>>> scores[-3:] index 0 1 2 3 4 5 6 7
[18, 24, 15]
value 9 14 12 19 16 18 24 15
index -8 -7 -6 -5 -4 -3 -2 -1
String Methods
Java Python
length len(str)
startsWith, endsWith startswith, endswith
toLowerCase, toUpperCase upper, lower,
isupper, islower,
capitalize, swapcase
indexOf find
trim strip
>>> name = "Martin Douglas Stepp"
>>> [Link]()
'MARTIN DOUGLAS STEPP'
>>> [Link]().startswith("martin")
True
>>> len(name)
20
String Splitting
• split breaks a string into tokens that you can loop over.
[Link]() # break by whitespace
[Link](delimiter) # break by delimiter
• join performs the opposite of a split
[Link](list of tokens)
>>> name = "Brave Sir Robin"
>>> for word in [Link]():
... print(word)
Brave
Sir
Robin
>>> "LL".join([Link]("r"))
'BLLave SiLL Robin
Splitting into Variables
• If you know the number of tokens, you can split them directly into
a sequence of variables.
var1, var2, ..., varN = [Link]()
• may want to convert type of some tokens: type(value)
>>> s = "Jessica 31 647.28"
>>> name, age, money = [Link]()
>>> name
'Jessica'
>>> int(age)
31
>>> float(money)
647.28
Indentation Blocks
• Code statement blocks in if structures (any control structure) need to
be indented
• tabbed or spaced inside
• improves readability
• determines what is the “True” block from other code
Whitespace Significance
• Python uses indentation to indicate blocks, instead of {}
• Makes the code simpler and more readable
• In Java, indenting is optional. In Python, you must indent.
[Link]
1 # Prints a helpful message.
2 def hello():
3 print("Hello, world!")
4 print("How are you?")
5
6 # main (calls hello twice)
7 hello()
8 hello()
if
if condition:
statements
• Example:
gpa = float(input("What is your GPA? "))
if gpa > 2.0:
print("Your application is accepted.")
if/else
if condition:
statements
elif condition:
statements
else:
statements
• Example:
gpa = float(input("What is your GPA? "))
if gpa > 3.5:
print("You have qualified for the honor roll.")
elif gpa > 2.0:
print("Welcome to Mars University!")
else:
print("Your application is denied.")
if ... in
if value in sequence:
statements
• The sequence can be a range, string, tuple, or list (seen later)
• Examples:
x = 3
if x in range(0, 10):
print("x is between 0 and 9")
if letter in "aeiou":
print("It is a vowel!")
The for Loop
for name in range(max):
statements
• Repeats for values 0 (inclusive) to max (exclusive)
>>> for i in range(5):
... print(i)
0
1
2
3
4
for Loop Variations
for name in range(min, max):
statements
for name in range(min, max, step):
statements
• Can specify a minimum other than 0, and a step other than 1
>>> for i in range(2, 6):
... print(i)
2
3
4
5
>>> for i in range(15, 0, -5):
... print(i)
15
10
5
for Loops and Strings
• A for loop can examine each character in a string in order.
for name in string:
statements
>>> for c in "booyah":
... print c
...
b
o
o
y
a
h
Nested Loops
• Nested loops are often replaced by string * and +
....1 Java
...2 1 for (int line = 1; line <= 5; line++) {
2 for (int j = 1; j <= (5 - line); j++) {
..3 3 [Link](".");
4 }
.4 5 [Link](line);
5 6 }
Python
1 for line in range(1, 6):
2 print((5 - line) * "." + str(line))
while Loops
while test:
statements
[Link]
1 # Sums integers entered by the user
2 # until -1 is entered, using a sentinel loop.
3 sum = 0
4 num = int(input("Type a number (-1 to quit)? "))
5
6 while n != -1:
7 sum += num
8 num = int(input("Type a number (-1 to quit)? "))
9
10 print("The total is", sum)
while / else
while test:
statements
else:
statements
• Executes the else part if the loop never enters
• There is also a similar for / else statement
>>> n = 91
>>> while n % 2 == 1:
... n += 1
... else:
... print(n, "was even; no loop.")
...
91 was even; no loop.
Concatenating Ranges
• Ranges can be concatenated with +
• Can be used to loop over a disjoint range of numbers
>>> range(1, 5) + range(10, 15)
[1, 2, 3, 4, 10, 11, 12, 13, 14]
>>> for i in range(4) + range(10, 7, -1):
... print(i)
0
1
2
3
10
9
8
Constants
• Python doesn't really have constants.
• Instead, declare a variable at the top of your code.
• All methods will be able to use this "constant" value.
[Link]
1 MAX_VALUE = 3
2
3 def print_top():
4 for i in range(MAX_VALUE):
5 for j in range(i):
6 print(j)
7 print()
8
9 def print_bottom():
1 for i in range(MAX_VALUE, 0, -1):
0 for j in range(i, 0, -1):
1 print(MAX_VALUE)
1 print()
1
2