Download presentation
Presentation is loading. Please wait.
1
Intro to Programming using Python Lecture #1
Yosef Mendelsohn With many thanks to Dolores Kalayta for the original version of these notes.
2
Python development environment
3
Getting started with Python
Install Python on your computer The latest release of Python version 3 Download the Python software from: Select the appropriate installer for your operating system (Windows, Linus/Unix, Mac OS X) Find and click on the IDLE shortcut
4
The Python shell Whether in Command Window or IDLE, Python is waiting for us to “say” something >>> (this is the Python prompt) In this mode, Python will instantaneously INTERPRET our statements and return an “answer” This is known as "interactive mode". As opposed to 'script mode' Interactive mode means that each statement is executed once you hit 'enter' Open IDLE in Windows This is the Python interactive Shell (IDE integrated development environment); the interpreter that translates and runs Python. >>> is the Python prompt. The interpreter uses the prompt to indicate that it is ready for instructions. Type The interpreter evaluated the expression and replied 17.3 and on the next line gave a new prompt, by indicating it is ready for more input. Script Mode: Alternatively, we can write a program in a file and use the interpreter to execute the contents of a file. Such a file is called a script. Scripts have the advantage that as they are files, they can be saved to disk, sent to others, collaborated on, etc. For example: we can create a file named ‘test.py’ By convention, files that contain Python programs have names that end in .py Click File Open file; Type print(‘this program adds two numbers’) print ( ) We could then go to a command prompt (more on this later) and type: python test.py and the entire script would be executed
5
Open IDLE What are the expected results for: >>> >>> 5 – 1.3 >>> 5 * 1.3 >>> 5 / 1.3 >>> > Note the unusual result… >>> 2 ** 3 > this is known as a "floating point error". We will discuss this later in the course. Most of these operators are familiar. Note that '**' gives you an exponent calculation
6
Arithmetic expressions, data types and functions
Some Python language basics Using Python to evaluate algebraic expressions Examine the core data types: integer and float numbers Operations on numbers and notation used Built- Functions
7
Data Types / Python Numeric values Integer Floating point
Values without a decimal point Python data type int Floating point Values with a decimal point Python data type float Every values has a specific “data type”. For examples, numbers are classified as integer or floating-point Numeric values with a decimal point are known as floats Numeric values without a decimal point are classified as integer Groups of text are known as strings. We make text a string by putting it in quotes (single or double quotes) All of the following are strings: “hello how are you?” “John Smith” “I am 35 years old” “q” “ “
8
Numerical Operations / Symbols
Addition + Subtraction - Multiplication * Division (returns float) / Division Quotient (returns int) // Division Remainder (returns int) % Exponentiation ** Review above: symbols used to perform operation. Use * (asterisk) the ‘x’ to indicate multiplication Open IDLE and do 3 + 4 returns 7; add 2 integers returns an integer 3 – 4 returns -1; subtract 2 integers returns an integer 6 * 6 returns 36; multipy 2 integers return an integer 5 / 3 returns float data type; the result of division, even between two ints is always a float 4 / 2 returns 2.0 5 // 3 returns 1 int quotient 5 % 3 returns 2 int remainder 4 % 2 returns 0 4 % 3 returns 1 6 * 6 returns 36 6.0 * 6.0 returns 36.0 6 * 6.0 return 36.0 6 * 6 * 6 * 6 * 6 = returns 7776 that is really 65 6 ** 5 returns 7776 6 *** 5 returns a syntax error Remainder division is also known as modulus operator Do not forget about the // and % operators --> they turn out to be surprisingly useful at times!
9
Operator precedence () ** * / // % + -
() ** * / // % + - Operators with the same precedence are evaluated from left-to-right. Use IDLE for exploring and experimenting with expressions like this. What does (4-1) + 2 * 3 ** 2 evaluate to? Operations are: parentheses, addition, multiplication, exponent. Order is: Parentheses, THEN exponent THEN multiplication THEN addition What does (4-1) + 2 * 3 ** 2 evaluate to?
10
Result Data Type DT Op Result DT int + - * / float // % **
Float arithmetic Float operator float returns float e.g. 3.0/2.0 = 1.5 Float operator int returns float e.g. 3.0/2 = 1.5 Try in IDLE 2/3 = so int/int = float 2//3 = 0 integer division, returns the quotient int//int = int 2%3 = 2 the remainder int, int%int = int 2.0%3.0 = 2.0 float 3.5 // 2.4 = 1.0 3.5 % 2.4 = 11 this is what it should be; python gives you 1.1 floating point arithmetic is an issue in all languages – do not go there All operations between floats always result in a float If an expression contains ints and there is at least one float, the result is always a float This information may seem pedantic, but it's not! Be sure that you are clear on the concept.
11
Practice For each of the following expressions predict the result and it’s data type; then execute the expression in IDLE to determine if you prediction is correct.idle 4 + 2 6 * 7 – 9/3 6 * 7 – 3 2.5 / (1 + 4) * 3 – 10/5 ( ) * (3 – 10/5) Answers: 4 + 2 = 6 = 6.0 6 * 7 – 9/3 = 39.0 6 * 7 – 3 = 39 2.5 / (1 + 4) = 0.5 * 3 – 10/5 = 28.2 ( ) * (3 – 10/5) = 14.2
12
Built-in functions abs(x) Returns the absolute value of a number
float(x) Returns a floating point number constructed from a number format(value [, format_spec]) Convert a value to a “formatted” representation, as controlled by format_spec int(x) Returns an integer value constructed from a number min (arg1, arg2,…) Returns the smallest of two or more arguments max(arg1, arg2,…) Returns the largest of two or more arguments round(number[, ndigits]) Returns the floating point value number rounded to ndigits after the decimal point Many more at – The Python language has a number of functions and types built into it that are always available. (i.e. we do not need to "import") More in 'import' later Python is "case sensitive". That is, round(3.4) will work. Round(3.4) will not. abs(-10.0) = 10.0 abs (-10) = 10 min ( 2, 4, -4, 0) = -4 max (2, 4, -4, 0) = 4 max ( 2, 4.0, 4, -4, 0) = 4.0 float(10) = 10.0 Int(10.6) --> Error Examples
13
Python Standard Library
This is a standard library of functions that are present with every installation of Python. As your programming needs become more advanced, you may need to install additional libraries separately. Python has many, many built-in functions as part of the standard library. Because there are so many functions, we organize them into groups calls 'modules'. In order to use functions that are in a certain module, we must first import that module. For example, if we wanted to use some more advanced mathematical functions that live in a module called 'math', we would first type: import math Numeric and Mathematical Modules math fractions random >>> import math >>> math.pi >>> The Python Standard Library consists of functions and classes organized into components called modules. Each module contains a set of functions and/or classes related to a particular application domain. In idle >>> import math In addition to functions such as log (logarithm), factorial, trigonometric functions, etc, some modules also include constants. For example, >>> math.pi Want to calculate the area of a circle Area = 𝜋𝑟^2 Type into IDLE pi * 5 ** 2 NameError - name ‘pi’ is not defined Use math library import math math.pi * (5 ** 2) Thought question: Do we need the parentheses above? Answer: No…. why not? Try it: The area of a circle is pi * radius2 Suppose you have r=5, get Python to output the area. Solution is in the PPT notes.
14
Variables
15
Variables Suppose we performed a complex calculation in Python and we wanted to SAVE the result for future use In order to do that we need to have a “container” in memory where we can store our piece of data Such “containers” are called variables
16
Variables In the code below, we have two variables, one that holds a value in pounds, and a second that holds a value in kilograms. pounds = 163 kilograms = pounds / 2.2 print(kilograms) dollars = 50 euros = dollars*0.84 print(euros) Try it: Create a variable called 'dollars' and assign it a value of 50. Then create a variable called 'euros' and assign it a value of dollars*0.84, and output the result. Solution is in the notes below.
17
Variables: assignment statements
Formula for calculating compound interest A is the value after t periods P is the principal amount (initial investment) r is the annual nominal interest rate ( not reflecting the compounding) n is the number of times the interest is compounded per year t is the number of years the money is invested If an amount of $5,000 is deposited into a savings account at an annual interest rate of 1%, compounded monthly, the value of the investment after 10 years can be calculated as follows Type into IDLE first with using only the A variable Then type in using intermediate variables. Do in Idle first without and then with variables. >>> A = 5000 * ( ) ** (12*10) A = Let's round it: round(A, 2) Now try it with variables: P = 5000 r = 1/100 = .01 n = 12 t = 10 A = P * (1 + r/n) ** (n*t) Must type in variables before the formula print (A) --> or $ balance = round(A,2) --> round to 2 decimal places print(‘The investment balance after 10 years is ‘, balance) We will learn more about the print() function as we progress. Given: n = 12 months, t = 10 years, P = 5000, r = 1/100 Write a line of code to determine the value and assign it to the variable ‘A’
18
Try it in IDLE without variables
19
Try it in IDLE using variables
20
Variables: assignment statements
We have done the following in memory for each variable: An object (container) was created for the variables For the first variable, we put a label “n” on the object The type label of the object 'n' is int The number 12 was stored as this object n 12 t 10 r .01 Recall: everything must be in main memory before it can be executed by the cpu. These values will stay in memory until we close(quit) Idle Main Memory P 5000 A What is the type for label A?
21
Legal Python variable names
A variable name a.k.a. identifier, can be made up of Letters Digits The underscore character _ Can not begin with a digit Can be as long as you want Variable names are case sensitive EVERYTHING in Python is case sensitive! MyStuff and mystuff are entirely different variables Awareness of case sensitivity in Python is very important! Most commonly used programming languages are case sensitive
22
Reserved words Besides variable names, that we make up, there are other words that are used in Python These special identifiers are called “reserved words”. They are words that already have a predefined meaning / usage in Python A reserved word cannot be used as an identifier (e.g. as a variable name)
23
Python reserved words and as assert break class continue def del elif
else except false finally for from global if import in is int lambda none nonlocal not or pass raise return true try while with yield
24
Multi-word variable names
There are two conventions for names with multiple words: Using underscore as delimiter shoe_size Using “camelCase” capitalizing the initial of the second (third,…) word shoeSize You can choose one style and stick with it Be consistent within each program
25
Python program As you saw, we can enter multiple statements in IDLE, each statement is executed when you hit (enter/return). Now let’s turn this into a program. We write a program in a file and use the interpreter to execute the contents of the file. Such a file is called a script. Working directly in the interpreter is convenient for testing short bits of code because you get immediate feedback. Think of it as scratch paper used to help you work out problems. Anything longer than a few lines should be put into a script. Let’s write a program that adds 2 numbers
26
Go to IDLE Click File New File
If you have not already saved the program, click OK and give this file a name. When you click save the program will execute Create a folder named Python and place it in a location that is easy for you to get to. By convention files that contain Python programs have names that end with .py. I will use c:\myPythonPrograms\ FirstProgram as my file name. Click save and the program wi
27
IDLE Shell The output is returned to the IDLE Shell 3 + (-12)
Returns -9
28
Variables: assignment statements
Formula for calculating compound interest A is the value after t periods P is the principal amount (initial investment) r is the annual nominal interest rate ( not reflecting the compounding) n is the number of times the interest is compounded per year t is the number of years the money is invested Now, let’s write a program that does this calculation. Open a new file, save as compound_interest.py Given: n = 12 months, t = 10 years, p = 5000, r = 1/100
29
compound_interest_v1.py RESULTS:
Save as compound_interest_v1.py RESULTS: ======= RESTART: C:\Users\ymendels\Dropbox\401\compound_interest_v1.py ======= The investment balance is The interest amount is >>>
30
Practice Problem You scored x/100, y/100, z/100 on homework
What is your total homework percentage? See notes: ( x + y + z)/300 (x + y + z) - Min (x, y z) /200 leave this for a homework exercise: The instructor drops the lowest homework score; what is your homework percentage?
31
Create algorithm We want the program to use 3 variables and calculate the average percentage Step 1: Assign a value to score_1 Step 2: Assign a value to score_2 Step 3: Assign a value to score_3 Step 4: Calculate Average by summing the scores and dividing by total possible points Step 5: Multiply Average by 100 to get percentage Step 6: Print percentage Save your program Prepare your test criteria: i.e. the 3 scores you want to use Calculate the results manually. Run your program; Does your program results match your predicted results. ## Calculate average percentage of 3 homework scores score_1 = 100 score_2 = 85 score_3 = 87 average = (score_1 + score_2 + score_3)/300 percentage = average * 100 print('The average percent is', percentage)
32
Strings In addition to number and Boolean values, Python supports string values ( i.e. non-numeric values)
33
Strings A string value is represented as a sequence of characters enclosed within quotes A string value can be assigned to a variable. String values can be manipulated using string operators and functions + is the string concatenation operator String and generally enclosed in single quotes, but double quotes are acceptable. Double quotes are necessary if you have a single quote within the string For example print (“That’s all folks”)
34
Explicit conversion of int to string
Adding two or more strings together to make a longer string is known as concatenation This is used a lot in programming Only string data can be concatenated To change an int data type to a string use str() Example: >>> age = 16 >>> print('Adam is ' + age + ' years of age') TypeError: must be str, not int >>> print ('Adam is ' + str(age) + ' years of age') Adam is 16 years of age >>> age = 16 >>> print ('Adam is ' + age + ' years of age') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print ('Adam is ' + age + ' years of age') TypeError: must be str, not int >>> print ('Adam is ' + str(age) + ' years of age') Ad Adam is 16 years of age There are many, many more operations and functions for strings,
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.