1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators
Review What s wrong with this line of code? print( He said Hello ) What s wrong with this line of code? num_1 = 2 2 Is this a valid name for a python program? program.py Or Prog1.py What s wrong with this line of code? Number = input( please enter your name ) What would the following print: num = 2 Num2 = 2 print("he said "Hello, num") print("he said "Hello, 2); print("he said "Hello, num + num2);
3 Appropriate Comments Include a comment at the beginning of the program:! to explain what the program does! its key features! its supporting data structures! and any unique techniques it uses.! Extra credit (features)! Include your name! class section! Name of program! date!
4 Indentation and Spacing Indentation Is part of python structure will discuss this further when get to control structure and loops Spacing Use blank line to separate segments of the code.
5 Debugging is fixing Programming Errors A bug is an error in programming language lingo Syntax Errors Did not follow the rules of python (missing parenthesis or quotation marks) Detected by the compiler Runtime Errors Causes the program to abort (for example when you divide a number by 0) Logic Errors Produces incorrect result
6 DATA TYPE integers: the simplest data type in Java. Used to hold positive and negative whole numbers, e.g. 5, 25, -777, 1. floats: Used to hold fractional or decimal values, e.g. 3.14, 10.25. We will explore each one in detail later this semester. String: holds one or more character, e.g. Dream Girls, NYU ROCKS!, C
Naming Conventions choosing identifiers for variables and program names (when you are saving your programs) 7 Choose meaningful and descriptive names. For Variables, class names and methods: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computearea.
8 Variables
Variables (a label that points one data value that will be stored in memory (RAM) 9 Visual Representation sum = 0 sum 0 number1 = 3 number2 = 2 Number1 number2 3 2 sum = number1 + number2 What is the value of Sum after execution of the above statement? sum 5
10 Assignment Statements num = 1 radius = 1.0 letter = 'A' # Assign 1 to num; # Assign 1.0 to radius; # Assign 'A' to letter;
11 Program to print numbers and strings # Comment: my second program in python to print words, sentences and numbers # Comment: my name is Mickey Mouse - watch how I can say and print my name in Python name = "Mickey Mouse" print ("My name is ", name) # my age is 5 minutes - watch how I can say and print my age in Python age = 5 print ("my age is ", age, " minutes") # Now, I will print my name and age together in one sentence and display on the screen print ("My name is ", name, "\t my age is ", age, " minutes")
Program asking user to input() to data Data = input( tell user what data to input ) 12 # Third program in python- ask user to enter information and then print them to the screen # what is your name? let's ask for your name in python # use input() function to ask users to enter data (numbers, words, sentences) yourname = input("please tell me your name-- I would like to get to know you?") print ("hello, ", yourname) # lets use input() function to ask user for age? yourage = input("please tell me your age?") # use input() function to print user name and age? print ("your name is ", yourname, "\t your age is ", yourage)
Data Types in python 13 1) Numbers Integers: (int) whole numbers such as 130, -20, 27000 Will not hold any decimal value (20.30) width = - 20 height = 5*9 Floating-point numbers (float) price = 200.50 2) Text / Strings: str A sequence of characters (one or more characters) such as cat, c, and Python is fun!, A
14 Assignment Statements Assignments statements enable one to initialize variables or perform basic arithmetic. x = 2 y = 3 z = x + y Here, we simply initialize x and y and store their sum within the variable z.
15 Assignment Operator = Read the assignment operator as GETS not EQUALS! This is an assignment of what s on the right side of = to a variable on the left eg sum = integer1 + integer2 Read this as, sum gets integer1 + integer2 integer1 and integer2 are added together and stored in sum
Escape characters Backslash ( \ ) Indicates special characters be output Helpful when you are trying to format printed statements 16 Escape Description sequence \n Newline. Position the screen cursor at the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For example, print( "\"in quotes\"" ); displays "in quotes" Some common escape sequences.
More on print() in python using escape character / 17 ("NYU Rocks") NYU Rocks print('doesn\'t') doesn't print("doesn\'t") doesn't print ( "Yes," he said.') "Yes," he said. print("\"yes,\" he said.") "Yes," he said.
Arithmetic 18 Operator(s) * / % + - Operation(s) Order of evaluation (precedence) Multiplication Evaluated first. If there are several of this type Division of operator, they are evaluated from left to Remainder right. Addition Subtraction Evaluated next. If there are several of this type of operator, they are evaluated from left to right.
19 Operator precedence Arithmetic Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 Follows PEMDAS Parentheses Exponents Multiplication and Division, Addition and Subtraction
Arithmetic 20 Arithmetic calculations used in most programs Usage * for multiplication ( 2 * 3 = 6) / for division (5 / 2 yields 2.5) // same as division but without any decimal value (5 / 2 yields an integer 2) +, - ** for exponentiation ( 2 ** 3 = 8) % (the remainder of the division) 5 % 2 yields 1 5 / 2 yields an integer 2.5 5 // 2 yields an integer 2 3.0 / 2 yields a double value 1.5 5 % 2 yields 1 (the remainder of the division) Remainder operator % returns the remainder 7 % 5 evaluates to 2
Simple program to add two numbers 21 # Program will initialize variables and add two numbers # Specify values for num1 and num2 (initialization variables) num1 = 2 num2 = 3 # Adding two numbers and storing result in a variable called "sum" sum = num2 + num1 # Printing numbers and the sum of two numbers print("num1 has a value of ", num1) print("num2 has a value of ", num2) print("the sum of num1 + num2 is ", sum)
22 Simple program to add two numbers (entered by user) # wk2add2.py - Program to add two numbers # ask user to enter numbers. Any data entered using input() is considered text # You need to convert it from text to a number in order to be used mathematically snum1 = input ("please enter first number: ") snum2 = input ("please enter second number: ") # convert snum1 from text to a number (float). The new variable num1 will hold a number value now # Use float() to convert from a string (text) to numbers with decimal values num1 = float(snum1) # convert snum1 from text to a number (float). # The new variable num2 will hold a number value now # Use float() to convert from a string (text) to numbers with decimal values num2 = float (snum1) # Adding two numbers and storing result in a variable called "sum" # result will be in float since using one operand with float forces result to be in float # ensures no loss of data (decimal values) sum = num2 + num1 print("num1 has a value of ", num1) print("num2 has a value of ", num2) print("the Sum is", sum)
Basic Arithmetic Compute average for two numbers 23 # wk2_avg.py # Program asks for input from users (two numbers) and then compute average # # Numbers will be entered by user to makes programs more flexible # ask user to enter values for num1 and num2 (initialization variables) num1 = 50.5 num2 = 3 avg = (num2 + num1)/2 # Printing numbers and result print("num1 has a value of ", num1) print("num2 has a value of ", num2) print("the average is ", avg)!
Basic Arithmetic Compute average for two numbers entered by user # wk2avg.py - Program to compute average # ask user to enter numbers. Any data entered using input() is considered text 24 snum1 = input ("please enter first number: ") snum2 = input ("please enter second number: ") # Then, you need to convert from text to a number in order to be used mathematically # convert snum1 from text to a number (float). The new variable num1 will hold a number value now # Use float() to convert from a string (text) to numbers with decimal values num1 = float(snum1) # convert snum1 from text to a number (float). # The new variable num2 will hold a number value now # Use float() to convert from a string (text) to numbers with decimal values num2 = float (snum2) # Adding two numbers and storing result in a variable called "sum" sum = num2 + num1 # compute average avg = sum/2 print("number 1 is:", num1, ", Number 2 is:", num2, ". The average is:", avg)!
Basic Arithmetic division 25 # wk2_division2.py # Program divides two numbers # Specify values for num1 and num2 (initialize variables) num1 = 2 num2 = 3 # Dividing two numbers and storing result in a variable called "result" result = num2 / num1 # Printing numbers and their result print("num1 has a value of ", num1) print("num2 has a value of ", num2) print("the result of num1 / num2 is ", result) # Let's try this: result2 = num2 // num1 print("the result of num1 // num2 is ", result2)
Basic Arithmetic modulus division 26 # wk2_mod.py # Program to compute modulus division ( the remainder after division) # for example 5/2 = 2.5 and 5%2 = 1 # Specify values for num1 and num2 (initialization variables) num1 = 2 num2 = 3 # (% is the MOD operator) stores ONLY the remainder after division result = num2 % num1 # Printing numbers and their result print("num1 has a value of ", num1) print("num2 has a value of ", num2) print("the result of num1 % num2 is ", result)