Uploaded by hajidalkindi417

Python Fundamentals: An Introduction to Programming

advertisement
(Lecture 2)
Python – Fundamentals
Based on Several sources
-- Dr. Kenneth A. Lambert Lectures
-- MIT edX lecture
-- https://www.w3schools.com/python/
Python – Overview
❖ Interpreted, but also compiled to bytecode
Python Interpreter has two modes: (1) Interactive Mode, (2) Script Mode
❖ Dynamic, for example:
❖ Types are bound to values, not to variables
❖ Objects (values) have a type, but variables do not
❖ Function and method lookup is done at runtime
❖ Strongly typed at runtime, not compile-time
❖ Highly structured - Statements, functions, classes, modules, and packages
enable us to write large, well structured applications
❖ Indented block structure - "Python is pseudocode that runs"
Example: Python Program
# Python program to check if
# given number is prime or not
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
11 is a prime number
Python – Overview
❖ Automatic garbage collection
❖ Compared with other languages (e.g. C/C++, Java, Perl, Tcl, and Ruby),
Python excels at development speed, execution speed, clarity and
maintainability
❖ Some Varieties of Python:
❖ CPython – Standard Python 2.x implemented in C
❖ Jython - Python for the Java environment http://www.jython.org/
❖ PyPy – Python with a JIT compiler and stackless mode http://pypy.org/
❖ Stackless – Python with enhanced thread support and micro-threads etc.
http://www.stackless.com/
❖ IronPython – Python for .NET and the CLR http://ironpython.net/
What can Python do?
❖ Python can be used on a server to create web applications
❖ Python can connect to database systems. It can also read and modify
files
❖ Python can be used to handle big data and perform complex
mathematics
❖ Python is used to implement machine learning solutions
❖ Python can be used for rapid prototyping, or for production-ready
software development
Why Python?
❖ Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
❖ Python has a simple syntax similar to the English language
❖ Python has syntax that allows developers to write programs with fewer
lines than some other programming languages
❖ Python runs on an interpreter system, meaning that code can be executed
as soon as it is written. This means that prototyping can be very quick
❖ Python can be treated in a procedural way, an object-orientated way or a
functional way
Python programs
❖ A Python Program (or script) is a sequence of definitions and commands
❖ Definitions are evaluated and commands are executed by Python interpreter in a
shell
❖ A shell is a program that takes commands typed by the user and calls the operating system to
run those commands
❖ Command (or statement) instructs the interpreter to do something
❖ Recall: An Interpreter is a program which translates your code into
machine language and then executes it line by line
❖ We can use Python Interpreter in two modes:
❖ Interactive Mode
❖ Script Mode
Python programs
❖ Python Interactive Mode (shell mode)
❖ Python interpreter waits for you to enter command. When you type the
command, Python interpreter goes ahead and executes the command, then
it waits again for your next command
❖ Read-Evaluate-Print-Loop
Read an expression
Evaluate it
Print the result
❖ >>> is known as prompt string or chevron prompt. It simply means that
Python shell is ready to accept your commands
❖ Python Shell is great for testing small chunks of code. However, the
statements you enter in the Python shell are not saved anywhere
https://www.python.org/shell/
Python programs
❖ Script Mode
❖ This mode is used to execute Python program (script) stored in a file
❖ Python scripts have the extension .py
❖ For example: helloWorld.py
❖ We can use any text editing software to write a Python script file
❖ We just need to save it with the .py extension
❖ But using an IDE (Integrated Development Environment) can make our life
a lot easier
https://www.onlinegdb.com/online_python_interpreter
Python programs
❖ Script Mode
❖ IDLE is Python’s Integrated Development and Learning Environment:
❖ Coded in 100% pure Python
❖ Cross-platform: works mostly
the same on Windows, Unix,
and Mac OS X
❖ Includes Python shell
window with colorizing of
code input, output, and error
messages
❖ In this course, we are going to use PyCharm
Objects
❖ At heart, programs will manipulate data objects
❖ Each object has a type that defines the kinds of things programs can
do to it
❖ Objects are:
❖ Scalar (i.e. cannot be subdivided), or
❖ Non-scalar (i.e. have internal structure that can be accessed)
Scalar Objects
❖ int – used to represent integers, e.g., 5 or 10082
❖ float – used to represent real numbers, e.g., 3.14 or 27.0
❖ bool – used to represent Boolean values True and False
❖ The built in Python function type returns the type of an object
>>> type(3)
<type ‘int’>
>>> type(3.0)
<type ‘float’>
Expressions
• Constant: Fixed values
print(123)
• Reserved Words:
for, if, false
• Variables:
x = 23
Expressions
❖ Objects and operators can be combined to form expressions, each of which
denotes an object of some type
❖ The syntax for most simple expressions is:
<object> <operator> <object>
Expressions
❖Basic Operations: Arithmetic
Symbol
Meaning
Example
+
Addition or concatenation x + y
-
Subtraction
x-y
*
Multiplication
x*y
Division
x / y or x // y
%
Remainder
x%y
**
Exponentiation
x ** y
/ or //
Reminder %
Expressions
Operators on ints and floats
❖ i + j (sum – if both are ints, result is int. If either is float, result is float)
❖ i - j (difference)
❖ i * j (product)
❖ i / j (division – result is always float)
❖ i % j (remainder – result is always int)
❖ i ** j (i raised to the power of j)
Expressions – Examples
>>> 3 + 5
8
>>> 3.14 * 20
62.8
>>> (2 + 3) * 4
20
>>> 2 + 3 * 4
14
Precedence
❖ Parentheses define sub-computations –‘ complete these to get values
before evaluating larger expression
❖ (2**2 + 3) * 4 + 5 // 2
❖ Operator precedence:
❖ In the absence of parentheses (within which expressions are first
reduced), operators are executed left to right, first using **, then (),
then * and /, and then + and -
Comparison operators
Comparison operators on ints and floats
❖
❖
❖
❖
❖
❖
i
i
i
i
i
i
> j (returns True if i is strictly greater than j)
>= j (returns True if i is strictly greater than or equals to j)
< j (product)
<= j
== j (returns True if i is equal to j)
!= j (returns True if i is not equal to j)
Comparison operators
❖ a and b (returns True a and b are both True)
❖ a or b (returns True if at least one is True)
❖ not a (returns True if a is False and returns False if a is True)
Type conversions (type casting)
❖ We can often convert an object of one type to another, by
using the name of the type as a function
❖ float(13) # has the value of 13.0
❖ int(2.35) # has the value of 2
Simple means of abstraction
❖ While we can write arbitrary expressions, it is useful to give names
to values of expressions, and to be able to reuse those names in
place of values
❖ pi = 3.14159
❖ radius = 11.2
❖ area = pi * (radius**2) #Assignment statement
❖ a = 3.14159
❖ b = 11.2
❖ c = a * (b**2)
Binding variables and values
❖ The statement pi=3.14159 assigns
the name pi to the value of the
expression to the right of the =
❖ Think of each assignment statement as
creating a binding between a name and
a value stored somewhere in the
computer
❖ We can retrieve the value associated
with a name or variable by simply
invoking that name
Non-scalar objects
❖ We will see many different kinds of compound objects
❖ The simplest of these are strings, objects of type str
❖ Literals of type string can be written using single or double
quotes
❖ 'a’
❖ “R12a”
❖ “345” # this is a string that contains the characters 3, 4, and 5
Operators on strings
>>> 3 * ‘B’
‘BBB’
>>> ‘c’ + ‘4’
‘c4’
>>> ‘a’ + str(5)
‘a5’
>>> len(‘Python’)
6
More operations on
strings will be presented
in an upcoming lecture
Variables
❖ A Variable is a named piece of memory that can store a value
❖ Variables make programs more readable and maintainable
❖ Any variable can name any thing
❖ 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
Variables
❖ Assignment statement: Stores a value into a variable
❖ Syntax:
variable_name = value
❖Examples:
a = 25
test = True
weight = 33.5
val = “this is a string”
❖ A variable that has been given a value can be used in expressions.
a * 2 is 50
Variables
❖ Variables do not need to be declared with any particular type
and can even change type after they have been set
Variables
x = 10
x = x + 1
y = y + x
# x begins as 10
# x is reset to 11
# Error! Can't find value of y
❖ When Python sees a variable in an expression, it must be able
to look up its value
❖ If a variable has no established value, the program halts with an
error message
Variables – 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
❖Variable names must begin with a letter or the underscore (_)
character
❖ They can only contain alpha-numeric characters and underscores (Az, 0-9, and _ )
❖ A variable name cannot start with a number
❖ Variables cannot contain spaces
❖ Python is case-sensitive
Output variables
❖ The Python print statement is often used to output variables
❖ Syntax:
❖ print (“Message”)
❖ print (Expression)
❖ print (Item1, Item2, ..., ItemN)
❖Examples
print(5 * 100)
# Prints 500
print(5 * “a”)
# Prints aaaaa
Output variables
❖ To combine both text and a variable, Python uses the +
character:
❖ The + character can be used to add a variable
to another variable
Output variables
❖ For numbers, the + character works as a mathematical operator
❖ Combining a string with a number with the + character will
return an error
Output variables
>>> print('The value of 3+4 is', 3+4)
The value of 3+4 is 7
>>> print('A', 1, 'XYZ', 2)
A 1 XYZ 2
❖ There is an optional argument
called end that you can use to
keep the print function from
advancing to the next line
print('this is', end=' ')
print('good')
Input of Text
❖ The input function prints its string argument and waits for
user input
input('Enter your name: ')
❖ The function then returns the string of characters entered at
the keyboard
Input of numbers
❖ When a number is expected, you must convert the input string
to a number
❖ When an integer is expected, you must convert the input string to an
int
int(input('Enter your age: '))
❖ When a real number (with a decimal point) is expected, you must
convert the input string to a float
float(input('Enter your height: '))
Simple Assignment Statements
❖ The = operator evaluates the expression to its right and sets the
variable to its left to the resulting value
❖ We use variables to retain data for further use
❖ Note: The = operator does not mean equals in Python
name = input('Enter your name: ')
income = float(input('Enter your income: '))
Program Flow
➢ Sequential
➢ Conditional
➢ Loops and repeat
➢ Store and retrieve
Commenting in Python
❖ When working with any programming language, you include comments
in the code to notate your work
❖ In Python, there are two ways to annotate your code
❖ Single-line comments are created by beginning a line with #
❖ Python ignores text from # to the end of line
x = 10
x = x + 1
# x begins as 10
# x is reset to 11
❖ Multiple lines comments are created by adding a delimiter “”” on each
end of the comment
""" This is an example of
multiple lines comment of
Python! """
Practical examples and
exercises
Python Shell mode – Exercises
❖ Declare the variables a, b, and c with the values 12, 25.3, and 12.7 respectively
❖ Display the types of a and b
❖ Calculate a raised to the power of 3
❖ Cast the value of c to an integer value
❖ Calculate the average of a, b, and c
❖ Print on the screen I am calculating the average of three numbers
❖ Print on the screen The average of 12, 25.3, and 12.7 is …. (the script
must display the correct value of the average of a, b, and c
❖ Ask the user to input a number and store it in a variable called d
❖ Display on the screen The value of c = 12.7
Python Script mode – Exercises
Exercise 1 – Write a Python program that declares the variables a=12, b=33,
c=23.4, and d=10.17. The program will do the following operations:
- Calculate and display the sum of a, b, c, and d
- Calculate and display the average of a, b, c, and d
- Calculate and display the result of b/a
- Calculate and display the result of c/a
- Calculate and display the result of b%7
Python Script mode – Exercises
Exercise 2 – Write a Python program that computes the total and the
average of two numbers that the user enters
Exercise 3 – Write a Python program that converts a temperature in Celsius
given by the user to Fahrenheit (Hint: F = 9/5*C+32)
Python Script mode – Exercises
Exercise 4 – Print a box like the one below.
*******************
*******************
*******************
*******************
Exercise 5 – Print a box like the one below.
*******************
*
*
*
*
*******************
Python Script mode – Exercises
Exercise 6 – Print a box like the one below.
*
**
***
****
Exercise 7 – Write a Python program that computes and prints the
result of
512 - 282
47 *48 + 5
It is roughly 0.1017
Python Script mode – Exercises
Exercise 8 – What is printed by the following code fragment?
x1 = 2
x2 = 2
x1 = x1 + 1
x2 = x2 + 1
print(x1)
print(x2)
Exercise 9 – What will be the output of the following program?
x = 4
y = x + 1
x = 2
print(x, y)
Python Script mode – Exercises
Exercise 10 – Write a Python program that asks the user to enter a number
x. Print output x, 2x, 3x, 4x, and 5x, like below.
Enter a number: 7
7 14 21 28 35
Exercise 11 – Write a Python program that computes the perimeter and
area of a rectangle.
Exercise 12 – Write a Python program that accepts a number expressed in
feet (ft) then converts it to centimeter (cm).
Exercises
Exercise 13 – Write a Python program that asks the user to enter a number
then prints the square of the number.
Exercise 14 – It is a common practice in restaurants that customers pay tips,
in addition to the prices of ordered meals. We want to simulate this practice
in a very simple way. We assume that all the meals have the same price of
3.75. Write a Python program that asks the user to input the number of
meals he/she wants to pay as well as the tip (percent of the total price, such
as 10%) that he/she will pay. Display on the screen the total amount of tip as
well as the total price that the customer will pay.
Exercises
Exercise 15 – Write a Python program that accepts the user's first and last
name and print them in reverse order with a comma between them.
Enter your first name: Adam
Enter your last name: Smith
Your name is Smith, Adam
Exercise 16 – Write a Python program that accepts an integer (n) and
computes the value of n+nn+nnn.
Sample value of n is 5
Expected Result : 155
Exercises
Exercise 17 – Write a Python program that creates the following output:
To Evaluate a Circle
Enter the radius: 1.5
Circumference: 9.42478
Area: 7.06858
Exercise 18 – Write a Python program that asks the user to enter a number
of seconds then converts the seconds to hours and minutes and seconds.
Enter number of seconds: 12400
12400 seconds is 3 hour 26 minutes 40 seconds
Homework ☺
1. Download the app:
SpriteBox : Code Hour
2. Have fun!
SpriteBox is an educational video game
for learning software programming
concepts
Download