Scripting Languages. Python basics

Similar documents
Programming in Python 3

Key Differences Between Python and Java

Python for Informatics

Getting Started with Python

Python for Non-programmers

Variable and Data Type I

Extended Introduction to Computer Science CS1001.py Lecture 10, part A: Interim Summary; Testing; Coding Style

Fundamentals of Programming (Python) Getting Started with Programming

Variable and Data Type I

Introduction to Python

Not-So-Mini-Lecture 6. Modules & Scripts

Lecture 3. Strings, Functions, & Modules

Full file at

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

SCoLang - Language Reference Manual

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

>>> * *(25**0.16) *10*(25**0.16)

Algorithms and Programming I. Lecture#12 Spring 2015

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

The current topic: Python. Announcements. Python. Python

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Python Unit

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

ENGR 101 Engineering Design Workshop

MEIN 50010: Python Introduction

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Some material adapted from Upenn cmpe391 slides and other sources

Introduction to Python

Accelerating Information Technology Innovation

Ch.2: Loops and lists

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Expressions and Variables

MEIN 50010: Python Flow Control

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

egrapher Language Reference Manual

Accelerating Information Technology Innovation

Beyond Blocks: Python Session #1

Downloaded from Chapter 2. Functions

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Student Number: Instructor: Brian Harrington

Python Games. Session 1 By Declan Fox

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

DaMPL. Language Reference Manual. Henrique Grando

S206E Lecture 19, 5/24/2016, Python an overview

Introduction to Python

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

Basic Syntax - First Program 1

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

CIS192 Python Programming. Robert Rand. August 27, 2015

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

3. Java - Language Constructs I

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

from scratch A primer for scientists working with Next-Generation- Sequencing data Chapter 1 Text output and manipulation

CS 320: Concepts of Programming Languages

CSI33 Data Structures

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

EL2310 Scientific Programming

18.1. CS 102 Unit 18. Python. Mark Redekopp

Language Reference Manual

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

Chapter 2: Introduction to C++

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Lecture 1. Types, Expressions, & Variables

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Advanced Computer Programming

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

CSCE 110 Programming I

Python 1: Intro! Max Dougherty Andrew Schmitt

A Little Python Part 1. Introducing Programming with Python

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013

Basics of Java Programming

Getting Started Values, Expressions, and Statements CS GMU

Maciej Sobieraj. Lecture 1

Variables, Constants, and Data Types

Chapter 2 Getting Started with Python

CS 1110 Prelim 1 October 15th, 2015

Python Tutorial. Day 1

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

1007 Imperative Programming Part II

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python Programming: Lecture 2 Data Types

Program Fundamentals

Reserved Words and Identifiers

Python Programming Exercises 1

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Transcription:

Scripting Languages Python basics

Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> Trying out commands, data and making simple experiments: getting information on interpreter making simple computations using variables, text strings, lists, dictionaries, etc. loading and examining modules getting most-up-to-date help on everything

Numbers integers (unlimited length) or floats (64-bits) also: complex (but you won't need this now) integer division (//), modulo (%), power (**) automatic type conversion in mixed cases >>> 2 + 2 4 >>> 2 + 2.0 4.0 >>> 9 % 5 4 >>> 9 / 5 1.8 >>> 9 // 5 1 >>> 9.0 // 5 1.0 >>> 2**1024 1797693134862315907729305190789024733617976978942306 5727343008115773267580550096313270847732240753602112 0113879871393357658789768814416622492847430639474124 3777678934248654852763022196012460941194530829520850 0576883815068234246288147391311054082723716335051068 4586298239947245938479716304835356329624224137216 >>> 2.0**1024 Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: (34, 'Numerical result out of range') >>>

Numbers binary and hex numbers with prefixes: 0x, 0b integer only >>> 0b11111111 255 >>> 0xff 255 >>> 0xdeadbeef 3735928559 >>> 10 + 0x0A + 0b1010 30 >>> 0b11 * 0x11 51 >>> 2**0b1000 256

Logic Type Logic (boolean) type: True (1), False (0) Comparisons: ==, <, <=, >, >= Logic operators: and, or, not >>> 1 == 1 True >>> 2 > 3 False >>> False - True -1 >>> 1 == 2 or 2 <= 3 True >>> not(false) True

Type Check and Conversion check: type( ) conversion: int( ), float( ) fraction is lost in float int conversion >>> type(1) <class 'int'> >>> type(1.0) <class 'float'> >>> a = 9 / 5 >>> type(a) <class 'float'> >>> type(1j) <class 'complex'> >>> >>> a = 3 >>> 1 + float(a) 4.0 >>> b = 1.5 >>> 1 + int(b) 2 >>> float(int(3.3)) 3.0 >>> int(float(3.3)) 3

Names Names (similar to variables, but different): just labels, no type declaration needed letter first + anything forbidden: space,+,, *, /, ", ', &, $, ^, #, @,... case sensitive >>> a45 = 10 >>> 45a = 10 File "<stdin>", line 1 45a = 10 ^ SyntaxError: invalid syntax >>> _valid_name = 13 >>>

Naming Conventions lowercase lower_case_with_underscores UPPERCASE UPPER_CASE_WITH_UNDERSCORES CapitalizedWords mixedcase Capitalized_Words_With_Underscores

Assignments x_1 = (10 + y)*3.0 name assignment expression Name( variable ) case-sensitive Assignment operator: single = do not confuse with double '==' Expression names, values, operators operators priority: **,, */%,+ brackets -2 2 (-2) 2 >>> -2**2-4 >>> (-2)**2 4

Augmented Assignments Assign to existing name with operation: x += 1 may be faster than equivalent x = x + 1 >>> x += 1 >>> x = 2 >>> x *= 3 >>> x /= 4 >>> x %= 5 >>> x **= 6

Multiple Assignment Assign a single/many value to many variables >>> i = j = k = 0.0 >>> x, y, z = 1, 2, 3 >>> x, y = y, x the right-hand side of assignment is evaluated first >>> a,b = 1, 2 >>> a,b = b, a+b >>> a 2 >>> b 3! >>> a, b = 1, 2 >>> a = b >>> b = a+b >>> a 2 >>> b 4

Exercise Temperature conversion: write a 4-line program in python use names: c, k, f (Celsius, Kelvin, Fahrenheit) find the proper formula yourself c = 7 k =... f =... print(c, k, f)

Text Strings String: a sequence of any characters Strings are surrounded by matched: single quotes double quotes triple quotes (3-single or 3-double): >>> s = 'This is a valid string' >>> s = "This is a valid string" >>> s = '''This is a valid string''' >>> s = """This is a valid string"""

Text Strings Double quotes are allowed inside single-quoted strings Single quotes are allowed inside double-quoted strings Almost anything is allowed inside triple-quoted strings (also new-line breaks) >>> s = ' This is a valid string with " inside ' >>> s = " This is a valid string with ' inside " >>> s = '''This is a valid string... with ' and " and line breaks inside'''

String Operations For full list run: help(str) len(s) s1 + s2 s.isdigit() s.isalpha() s.upper() s.lower() and others >>> a = "Hello" >>> type(a) <class 'str'> >>> len(a) 5 >>> a.isdigit() False >>> a.isalpha() True >>> a.upper()+a.lower() 'HELLOhello'

String Slicing Numbered sequence string s="hello" position 01234 Substrings: [ ] first char at position 0 last char at position -1 access range with ":" 0:n means n chars, from 0 to n-1 position >>> x = "Hello world" >>> x[0] 'H' >>> x[0:4] 'Hell' >>> x[:4] 'Hell' >>> x[:] 'Hello world' >>> x[-1] 'd' >>> x[3:-1] 'lo worl' >>> x[-4:-1] 'orl' >>> x[-4:] 'orld'

String Formatting Gluing together strings and numbers string.format("pattern",args) {n} for argument placement and position d,f,s for int, float and string types >>> a = "I'm {0} and I'm {1}".format('John',20) >>> print(a) I'm John and I'm 20 >>> print("t={0:2d}c is {1:+.4f}K".format(1,274.15)) T= 1C is +274.1500K https://docs.python.org/3/library/string.html#format-specification-mini-language

Comments Comments start with hash # character Everything after # is ignored till the end of line Use meaningful comments in your code! # width w = 10 # length l = 20 # bad x = x + 1 # good x = x + 1 # increment x # add bias to x a = w * l # area

Decisions if-elif-else conditions are bool-type followed by colon : body instructions are indented (use 4-spaces) if cond: instr if cond: instr1 else: instr2 if a>0: print("positive") else: print("not positive") if cond1: instr1 elif cond2: instr2 else: instr3 if a>0: print("positive") elif a<0: print("negative") else: print("zero")

Conditional Loop while condition bool-type in the first line in Python there is no loop with condition at the end (nothing like do-while exists) body indented while cond : instr while i < j: i = i+1 j = j-1

Exercise: Factorial Factorial n! = n (n-1)...2 1 how far you can go with value of n? what is the best data type for result s? how many digits has 100! start n = s = n False print s stop n>1 True n = n-1 s = s*n

Loop control break, continue break immediate escape from the loop continue immediate start of the next cycle while cond1: if cond2: break instr a = 0 while a < 10: a = a + 1 if a**4 > 1000: break print(a, a**4) while cond1: if cond2: break instr a = 11 while a > -10: a = a - 1 if a==0: continue print(a, 1.0/a)

Exercise: Guest-It-Game start goal = while True: read guess if print elif print else print break goal= True False "got it" stop True guess guess>goal guess<goal True "too big" True "too big"

Getting Input for CLI s = input("prompt") print a "prompt" message and return input as text s.isdigit() make sure there are digits only n = int(s) convert to integer while True: s = input("number -> ") if not s.isdigit(): continue n = int(s)

Random values Add a library (module) and use function import random random.function() Read documentation Python 3 Standard Library 9. Numeric and Mathematical Modules 9.6. random Generate pseudo-random numbers random.randint(a, b) Return a random integer N such that a <= N <= b import random guess = random.randint(1,100)

Math functions Add a library (module) to your program import math Read documentation Python 3 Standard Library 9. Numeric and Mathematical Modules 9.2. math Mathematical functions import math x = math.sqrt(math.cos(2*math.pi/t)**2-1)