Python: common syntax

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

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

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

8. Control statements

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

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

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

Accelerating Information Technology Innovation

CSC Software I: Utilities and Internals. Programming in Python

Python Intro GIS Week 1. Jake K. Carr

Python Review IPRE

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Accelerating Information Technology Innovation

Python for Non-programmers

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Here n is a variable name. The value of that variable is 176.

Data Structures. Lists, Tuples, Sets, Dictionaries

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

Collections. Lists, Tuples, Sets, Dictionaries

cs1114 REVIEW of details test closed laptop period

Java Bytecode (binary file)

Add Subtract Multiply Divide

The current topic: Python. Announcements. Python. Python

Variables, expressions and statements

C++ for Python Programmers

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Algorithms and Programming I. Lecture#12 Spring 2015

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

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

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

Python Review IPRE

CS 1301 Exam 1 Answers Fall 2009

CS 115 Lecture 8. Selection: the if statement. Neil Moore

The C++ Language. Arizona State University 1

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

ENGR 101 Engineering Design Workshop

Flow Control: Branches and loops

Variables. Data Types.

Lists, loops and decisions

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Python for C programmers

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Types, lists & functions

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

CS 1301 Exam 1 Fall 2009

The Big Python Guide

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Basic Syntax - First Program 1

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions

Getting Started with Python

STSCI Python Introduction. Class URL

Full file at

Programming in C++ PART 2

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Part III Appendices 165

CS Advanced Unix Tools & Scripting

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Bioinformatics

Computer Programming : C++

Variable and Data Type I

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

Key Differences Between Python and Java

Variable and Data Type I

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Python for Non-programmers

Variables, Expressions, and Statements

Advanced Python. Executive Summary, Session 1

If Statements, For Loops, Functions

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Beyond Blocks: Python Session #1

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Fundamentals of Programming (Python) Getting Started with Programming

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

Some material adapted from Upenn cmpe391 slides and other sources

Section 2.2 Your First Program in Java: Printing a Line of Text

The Practice of Computing Using PYTHON

18.1. CS 102 Unit 18. Python. Mark Redekopp

Chapter 2: Introduction to C++

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Introduction to Python

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

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

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

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

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

PIC 16, Fall Variables, Dynamically-typed, Mutable, Immutable, Functions. Michael Andrews. October 1, Department of Mathematics UCLA

Typescript on LLVM Language Reference Manual

Lecture 3. Input, Output and Data Types

CMSC201 Computer Science I for Majors

Python - Variable Types. John R. Woodward

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Problem Solving for Intro to Computer Science

Python 1: Intro! Max Dougherty Andrew Schmitt

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

Introduction to Python (All the Basic Stuff)

Transcription:

Lab 09 Python!

Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable declarations (automatically interprets type based on what you assign it to) ny_string = hello Python has no ++ operator Review lecture slides for more details Use str[-1] to access the last element in a string

New things in Python raw_input() is how you extract from the input stream Raise to a power using ** Concatenation using + Multiplication using * Works on strings (see lecture slides!) Print is like cout but no << needed No endl needed to print a new line Add a comma to force output on the same line Comma adds a space between the two outputs

Python: common syntax No semicolons! No curly braces! No parentheses for loops and conditionals! Colons are used in python Scope is determined by indentation if x == 35: return True for index in my_str: # Do something iterating through my_str

if, elif, else Very similar, all logic is the same! not && and or name = Castiel if name == Dean or name == Sam : print hunter elif name == Castiel : print angel else: print demon

raw_input() Used for reading input from the user Reads until it hits an <enter> (like getline) Ignores leading and trailing white space Can directly store into a variable (remember: no type declaration!) print 'Please enter your name: ' # prompt your_name = raw_input() # Alternate way to use raw_input() and prompt your_name = raw_input('please enter your name: ')

Printing out variables name = 'Fred' print 'Hi there %s!' %name %s is for string %d is for int (double will get truncated) %f is for floats (if you want to save the decimals)

Printing out variables name = 'Fred' print 'Hi there {}!'.format(name) To use.format(), represent variables to be printed with {}! name = Diana age = 23 print {} is {} years old!.format(name, age)

Loops while condition: # do something for <variable> in <container>: # do something <variable> is a new variable used solely for the loop It takes on the value of, or refers to, each successive member in the container <container> is any type that holds other values You can t modify the elements of the container with this kind of loop

Looping through a container name_list = [ Austin, Erin, Jordan, Madison ] for name in name_list: name = bestta What will name_list look like after this code runs?

Looping through a container name_list = [ Austin, Erin, Jordan, Madison ] for name in name_list: name = bestta What will name_list look like after this code runs? [ Austin, Erin, Jordan, Madison ]

range() This function creates a list of values in the requested range range(n) creates a list of values from 0 to n-1 It can accept up to 3 parameters: range(start, stop, step) Function can accept 1 parameter (stop), 2 parameters (start, stop), or all 3 parameters stop value is NOT included in the range: [start, stop)

len() This function returns the number of elements in a list Use range(len(list_name)) to loop over a list and be able to modify values in the container Example: my_list = [ hello, world, it, is, me ] for i in range(len(my_list)): my_list[i] = x print my_list[i] # will always print x What will my_list look like after this code runs?

len() This function returns the number of elements in a list Use range(len(list_name)) to loop over a list and be able to modify values in the container Example: my_list = [ hello, world, it, is, me ] for i in range(len(my_list)): my_list[i] = x print my_list[i] # will always print x What will my_list look like after this code runs? [ x, x, x, x, x ]

User-defined functions No return type! Example: def add(a, b): sum = a + b return sum def main(): x = 3 y = 5 sum = add(x, y) print sum # output: 8

Python: pass by object reference In Python, variables are neither passed by value nor passed by reference Variables are just names that refer to objects Anytime a variable is set to an object, it is said to refer to that object (in memory) Look at lecture slides for more details! http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-asexplained-by-philip-k-dick/

Lists You can think of a list as an array that can also: Contain different data types Add elements to it, increasing length (does not have set size) Start out with any number of elements (no need to declare or decide on a size ahead of time) You can access elements with brackets [ ] just like with an array

Lists: which are valid? my_list = [] my_list = [73, 1, 33] my_list = [ name, hi, 3, 4.0]

Lists: which are valid? my_list = [] my_list = [73, 1, 33] my_list = [ name, hi, 3, 4.0] All are valid! Notice use of and, and different types in the same list

Slicing Specifies a portion of a container (list, tuple, string) Slice format: container[start:end] Other format options: container[1:] #means from index 1 to the end container[:5] #means from first index up to (but not including), index 5 negative index = relative to the back end of the object container[-3:-1] # means third to last index up to but not including last index

Slicing text = review discussion! print text[-4:] What does this print?

Slicing text = review discussion! print text[-4:] What does this print? ion!

Summary The while loop is familiar Two kinds of for loops: Container-based loop Range-based loop You can use range() to create a list of numbers, which can be used as indices List and strings can be looped over in the same way You can slice containers (strings, lists, and tuples) into pieces A list can contain different types A list of lists can work as a 2D array

Answer to a good question In Python if you type: print EECS 183 print Is Awesome! All in one line what prints?

Answer to a good question In Python if you type: print EECS 183 print Is Awesome! All in one line what prints? This is a runtime error

Answer to a good question (2) If you pass in variables to a function, but they aren t the types the function is expecting, for instance: def sum(x,y): sum = x + y return sum If 3 and yes are passed into the function what will happen? A runtime type error that happens when a string and an int are added TypeError: cannot concatenate str and int objects

Answer to a good question (3) Using range and len together allows you to modify the container range() gives you the indices to loop over a container len() gives you the number of elements in a container However, this is not true of strings - they are immutable (can t be changed) To modify a string you need to make new string variable and append what you want from the original string to it

Notes on a good question (4) You cannot modify the container at all in a normal container-based for loop You CAN modify the variable But modifying the variable that is holding each value of the container will not modify the container

Review Lecture Slides for Python! For Python: You should become familiar with the new things you can do with it If you are working on Creative AI you have already been writing python code! Otherwise it is great to know another programming language Fun Fact: Reddit is written in python! Feel Free to ask any questions! It is confusing at first but it comes very easily as you keep working with it!

Python Practice Question Define a main function Read into a variable pswrd from the user, printing the prompt Password please Concatenate a 2 and a & on the end Print out each letter of the password separated by a space using a loop Create a variable called hide_pswrd Set each letter in the password to x for hide_pswrd and print this new hidden_pswrd

Python Practice Question def main(): pswrd = raw_input( password please: ) pswrd += 2& for k in pswrd: print k, hide_pswrd = for j in pswrd: hide_pswrd += 'x' print hide_pswrd