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

Basic Python Programs

This document provides an introduction to basic Python programs. It defines Python as a high-level programming language that is interpreted rather than compiled. It differentiates between programs and programming, and discusses the main datatypes in Python like integers, floats, and strings. It also covers key concepts like variables, expressions, keywords, operators, comments, and common errors like syntax errors and runtime errors. The document demonstrates writing simple Python code in IDLE and discusses important Python programming concepts like indentation, whitespace, and string formatting.

Uploaded by

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

Basic Python Programs

This document provides an introduction to basic Python programs. It defines Python as a high-level programming language that is interpreted rather than compiled. It differentiates between programs and programming, and discusses the main datatypes in Python like integers, floats, and strings. It also covers key concepts like variables, expressions, keywords, operators, comments, and common errors like syntax errors and runtime errors. The document demonstrates writing simple Python code in IDLE and discusses important Python programming concepts like indentation, whitespace, and string formatting.

Uploaded by

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

Introduction

Basic Python Programs


Objectives
• Define Python
• Install Python
• Differentiate Program from Programming
• Kinds of Error
• Coding in Python
• Datatypes
• Value, Variables, Expressions, Keywords, Operands,
Operators and Comments

2
Python!
● Python is an example of a high-level language

● Low-level languages(assembly languages or


machine languages) are the ones computer only
understands.

● Thus, a high-level language has to be processed;


taking some time.

3
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)
4
Python
• “Python is an experiment in how much
freedom program-mers need. Too
much freedom and nobody can read
another's code; too little and
expressive-ness is endangered.”
- Guido van Rossum

5
Installing Python
Windows: Mac OS X:
• Download Python from • Python is already installed.
http://www.python.org • Open a terminal and run python
• Install Python. or run Idle from Finder.
• Run Idle from the Start
Menu. Linux:
• Chances are you already have
Python installed. To check, run
python from the terminal.
Note: For step by step installation
instructions, see the web site. • If not, install from your
distribution's package system.
6
7
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

8
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

9
Interactive Shell
• Great for learning the language
• Great for experimenting with the library
• Great for testing your own modules
• Two variations:
 IDLE (GUI )
 python (command line)

10
IDLE Development Environment
• IDLE is an Integrated DeveLopment Environment for
Python, typically used on Windows
• Multi-window text editor with syntax highlighting, auto-
completion, smart indent and other.

11
Python Scripts
• When you call a python program from the command line
the interpreter evaluates each expression in the file
• Python also has mechanisms to allow a python program
to act both as a script and as a module to be imported
and used by another python program

12
Program
• A program is a sequence of instructions that specifies
how to perform a computation.
• The computation might be something mathematical,
such as solvinga system of equations or finding the
roots of a polynomial, but it can also be a symbolic
computation, such as searching and replacing text in a
document or (strangely enough) compiling a program.

13
Program Terminologies
input:
- Get data from the keyboard, a file, or some other device
output:
- Display data on the screen or send data to a file or other
device.
math:
- Perform basic mathematical operations like addition and
multiplication.
conditional execution:
- Check for certain conditions and execute the appropriate
sequence of statements.
repetition:
- Perform some action repeatedly, usually with some variation.14
Programming
Programming is a complex process, and because it is
done by human beings, it often leads to errors.

Programming errors are called bugs

Process of tracking them down and correcting them is


called debugging .

15
Three Kinds of Error
• Syntax errors
• Runtime errors
• Semantic errors

16
Syntax Error
• Syntax errors - not follow the syntax of the
program

 Syntax refers to the structure of a program and the


rules about that structure.

17
Runtime Errors
• occurs once your program runs

• These errors are also called exceptions because


they usually indicate that something exceptional
(and bad) has happened.

18
Semantic Errors
• the program you wrote is not the program you wanted
to write
• If there is a semantic error in your program, it will run
successfully, in the sense that the computer will not
generate any error messages, but it will not do the right
thing.

19
Code in IDLE

>>>x = 34 - 23 # A comment.
>>>y = “Hello” # Another one.
>>>z = 3.45
>>>if z==3.45 or y=="Hello":
x = x + 1
y = y + “ World” # String concat.
print(x)
print(y)
20
Understand the Code
• Indentation matters to code meaning
 Block structure indicated by indentation
• First assignment to a variable creates it
 Variable types don’t need to be declared.
 Python figures out the variable types on its own.
• Assignment is = and comparison is ==
• For numbers + - * / % are as expected
 Special use of + for string concatenation and % for string
formatting (as in C’s printf)
• Logical operators are words (and, or, not) not symbols
• The basic printing command is print 21
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

hello.py
1 print("Hello, world!")

22
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 '

swallows.py
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it together.")
4 print('African or "European" swallows?')

23
Basic Datatypes
• Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
• Floats
x = 3.456
• Strings
 Can use “” or ‘’ to specify with “abc” == ‘abc’
 Unmatched can occur within the string: “matt’s”
 Use triple double-quotes for multi-line strings or strings than
contain both ‘ and “ inside of them:
“““a‘b“c”””
24
Whitespace
• Whitespace is meaningful in Python: especially
indentation and placement of newlines
• Use a newline to end a line of code
 Use \ when must go to next line prematurely
• No braces {} to mark blocks of code, use consistent
indentation instead
 First line with less indentation is outside of the block
 First line with more indentation starts a nested bloc
• Colons start of a new block in many constructs, e.g.
function definitions, then clauses 25
Comments
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the first line of
a new function or class you define
• Development environments, debugger, and other tools
use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive integer and
returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
26
Comments
• Syntax:
# comment text (one line)

swallows2.py
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?')

27
Assignment
• Binding a variable in Python means setting a name to hold
a reference to some object
 Assignment creates references, not copies
• Names in Python do not have an intrinsic type, objects
have types
 Python determines the type of the reference automatically based
on what data is assigned to it
• You create a name the first time it appears on the left side
of an assignment expression:
x = 3

• A reference is deleted via garbage collection after any names


bound to it have passed out of scope 28
Naming Rules
• Names are case sensitive and cannot start
with a number. They can contain letters,
numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or, pass,
print, raise, return, try, while 29
Naming Conventions
The Python community has these recommend-ed
naming conventions
•joined_lower for functions, methods and, attributes
•joined_lower or ALL_CAPS for constants
•StudlyCaps for classes
•camelCase only to conform to pre-existing
conventions
•Attributes: interface, _internal, __private
30
Assignment Statement
•You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
•Assignments can be chained
>>> a = b = x = 2 31
Accessing Non-Existent Name
• Accessing a name before it’s been properly created (by
placing it on the left side of an assignment), raises an
error
>>> y

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
32
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.
hello3.py
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() 34
Values
• A value is one of the fundamental things — like a letter
or a number — that a program manipulates
• These values are classified into different classes, or
data types:
 4 is an integer
 "Hello, World!" is a string
• Python has a function called type which can tell the data
type of a value >>> type (“Hello World”)
<class 'str'>
>>> type (17)
<class ‘int'> 35
Values

>>> type (3.2)


<class 'float'>
>>> type (“17”)
<class 'str'>
>>> type (“3.2”)
<class 'str'>

36
Variables
• A variable is a name that represents a value
stored in the computer memory
 Used to access and manipulate data stored in
memory
 A variable references the value it represents

37
Rules in Naming Variable
• Variable name cannot be a Python key word
• Variable name cannot contain spaces
• First character must be a letter or an
underscore
• After first character may use letters, digits, or
underscores
• Variable names are case sensitive
38
Variables
• Assignment statement: used to create a variable and
make it reference data
 General format is variable = expression
 Example: age = 29
 Assignment operator: the equal sign (=)
 In assignment statement, variable receiving value must be on
left side
 Variable name should not be enclosed in quote marks
 You can only use a variable if a value is assigned to it

39
Variables
• Declaring
 no type is written; same syntax as assignment
Java Python
int x = 2; x = 2
x++; x = x + 1
System.out.println(x); print(x)

x = x * 8; x = x * 8
System.out.println(x); print(x)

double d = 3.2; d = 3.2


d = d / 2; d = d / 2
System.out.println(d); print(d) 40
Variables
• Assignment statement gives a value to a variable
>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159
• Interpreter evaluate a variable
>>> message
"What's up, Doc?"
>>> n
17
>>> pi
3.14159 41
Statement
• A statement is an instruction that the Python interpreter
can execute

Assignment Statement
x = 2
x = x + 2 Assignment with expression
print x Assignment Statement

42
Expression
• An expression is a combination of values,
variables, operators, and calls to function

>>> 1 + 1
2
>>> len(“hello”)
5
43
Expressions
• Arithmetic is very similar to Java
 Operators: + - * / % (and ** for exponentiation)
 Precedence:
()
**
* / %
+ -
 Integers vs. real numbers

44
Expressions: Summary of Operators

• no increment ++ or decrement -- operators (must


manually adjust by 1)

45
Operators and Operands
• Operators are special symbols that represent
computations like addition and multiplication.

• The values the operator uses are called operands.

46
Expressions
>>> 1 + 1
2
>>> 1 + 3 * 4 - 2
11
>>> 7/2
3.5
>>> 7//2
3
>>> 10**5
100000 47
Programming
1. Write a program that will computes the area of the
circle
 Area = 𝜋𝑅2
2. Write a program to prompt the user for hours
and rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
48
Assigning Input
• How can we let users (not programmers) input values?
• In Python, input is accomplished via an assignment
statement combined with a built-in function called input

<variable> = input(<prompt>)
• When Python encounters a call to input, it prints
<prompt> (which is a string literal) then pauses and
waits for the user to type some text and press the
<Enter> key
49
Assigning Input

>>>name = input("Enter your name: ")


Enter your name: Ana
>>>print("Hello ", name)
Hello Ana

• Notice that whatever the user types is then stored as a


string 50
Assigning Input
• What happens if the user inputs a number?
>>>number=input("Enter a number: ")
Enter a number: 3
>>>number
‘3’
• How can we force an input number to be stored as a
number and not as a string?
 We can use the built-in eval function, which can be “wrapped
around” the input function
51
Assigning Input

>>>number=eval(input("Enter a number: "))


Enter a number: 3
>>>number
3 Now an int (no single quotes)!

52

You might also like