Computer Programming CSC 1401 PDF
Document Details
Uploaded by Deleted User
Al Akhawayn University
Dr. Oumaima Hourrane
Tags
Related
- Lecture 1 - MUH101 Introduction to Programming - PDF
- Python Programming Notes PDF
- SYSC 2006 Lecture 2: Variables, Data Types, and Expressions PDF
- Python Programming Notes PDF
- Python Variable, Statement and Expression PDF
- CS 110: Computer Science Fundamentals Expressions and Arithmetics Lec06_expressions01 PDF
Summary
This document is a set of lecture notes for a Computer Programming course (CSC 1401) at Al Akhawayn University. It covers basic concepts like data types, expressions, and variables in Python, providing examples and explanations. The materials include practical questions to help practice what is being covered.
Full Transcript
Computer Programming CSC 1401 Instructor: Dr. Oumaima Hourrane Email: [email protected] School of Science and Engineering Module 4 Basic Data Concepts 2 Data types Data Manipulation: Programs process various forms of information. Different Forms of Data:...
Computer Programming CSC 1401 Instructor: Dr. Oumaima Hourrane Email: [email protected] School of Science and Engineering Module 4 Basic Data Concepts 2 Data types Data Manipulation: Programs process various forms of information. Different Forms of Data: Text (e.g., names, addresses) Numbers (e.g., age, salary) Dates and Times What is a Data Type? A category of data values that are related. Defines the operations that can be performed on the data. Computer Programming - CSC 1401 3 Data types in Python Automatic Type Inference: Python determines the data type based on the value. Computer Programming - CSC 1401 4 Data types in Python - Numeric Types Integers (int): Whole numbers without a decimal point. Stored exactly in memory. Suitable for counts, indices, and discrete quantities. Examples: -10, 0, 25, 1024 Floating-Point Numbers (float): Real numbers with a decimal point. Used for measurements, calculations requiring fractions. Examples: 3.1415, 0.0, -2.718 Computer Programming - CSC 1401 5 Expressions in Python An expression is a combination of values and operations that evaluates to a result. ➔ Simple Expressions: Literal values like 42 or 3.14. ➔ Complex Expressions: Calculations like (2 * 6) + (4 * 4) + 2. Components: Operands: The values (e.g., 2, 6). Operators: The symbols denoting operations (e.g., *, +). Computer Programming - CSC 1401 6 Evaluating Expressions Order of Operations: 1. Parentheses () 2. Exponents ** 3. Multiplication * and Division / 4. Addition + and Subtraction - Using Parentheses: Clarifies the intended order. Ensures accurate calculations. Example: result = (2 * 6) + (4 * 4) + 2 print(result) # Output: 34 Computer Programming - CSC 1401 7 Practical Question If you have: ○ Three packs of 5 items. ○ Five individual items. How many items do you have in total? Take a moment to write the expression and calculate the result. Computer Programming - CSC 1401 8 Practical Question Solution If you have: ○ Three packs of 5 items. ○ Five individual items. How many items do you have in total? Take a moment to write the expression and calculate the result Expression: total_items = (3 * 5) + 5 print(total_items) # Output: 20 Computer Programming - CSC 1401 9 Expressions - Operators and Operands Operator: A special symbol used to indicate an operation. Examples: +, -, *, / Operand: The values that operators act upon. Can be literals, variables, or other expressions. Example: 3 + 29 4*5 Computer Programming - CSC 1401 10 Practice Question Evaluate the expression without typing it into Python: (5 * 3) + (12 / 4) - 7 A) 11 B) 12 C) 13 D) 14 11 Practice Question Solution Evaluate the expression without typing it into Python: (5 * 3) + (12 / 4) - 7 A) 11 Calculations: B) 12 - (5 * 3) → 15 C) 13 - (12 / 4) → 3.0 D) 14 - 15 + 3.0 - 7 → 11.0 12 Literals Definition: A direct value in code. Integer Literals (int): 3, 482, -29434, 0 Float Literals (float): 298.4, 0.284, 207. (207.0),.2843 (0.2843). 2.3e4 → 23000.0 1e-5 → 0.00001 String Literals (str): 'abc', "hello", "I'm happy!", Empty string " " or ' ' Boolean Literals (bool): True, False Computer Programming - CSC 1401 13 Arithmetic Operators Computer Programming - CSC 1401 14 Arithmetic Operators - Mod operator Examples of % Mod Operator Computer Programming - CSC 1401 15 Special Cases with Division and Modulus Numerator Smaller than Denominator: Division: Result is 0. Modulus: Result is the numerator. Example: 7 // 10 # Output: 0 7 % 10 # Output: 7 Numerator is Zero: Both division and modulus return 0. Denominator is Zero: Results in a runtime error (ZeroDivisionError). Computer Programming - CSC 1401 16 Practice Question What is the output of the following code? print(20 % 3) print(20 // 3) A) 2 and 6 B) 1 and 6 C) 2 and 6.666... D) 1 and 6.666... 17 Practice Question Solution What is the output of the following code? print(20 % 3) print(20 // 3) A) 2 and 6 Calculation: B) 1 and 6 - 20 % 3 → Remainder of 20 / 3 → 2 C) 2 and 6.666… - 20 // 3 → Quotient of 20 / 3 without remainder → 6 D) 1 and 6.666... 18 Operator Precedence in Python Order of Operations: 1. Parentheses () 2. Exponentiation ** 3. Unary operators +, - 4. Multiplicative operators *, /, //, % 5. Additive operators +, - Remember: PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. Computer Programming - CSC 1401 19 Unary Operators Definition: Operators that act on a single operand. Examples: Unary Plus: +5 (no effect) Unary Minus: -8 (negates the value) Precedence: Higher than multiplicative operators. Example: 12 * -8 # Output: -96 Computer Programming - CSC 1401 20 Evaluating Complex Expressions Expression: 13 * 2 + 239 // 10 % 5 - 2 * 2 Steps: 1. Multiplications and Divisions: ○ 13 * 2 → 26 ○ 239 // 10 → 23 ○ 23 % 5 → 3 ○ 2*2→4 2. Additions and Subtractions: ○ 26 + 3 → 29 ○ 29 - 4 → 25 Result: The expression evaluates to 25. Computer Programming - CSC 1401 21 Mixing and Converting Types Implicit Conversion: Python automatically converts int to float when necessary. Example: 2 * 3.6 # Output: 7.2 (float) Explicit Conversion: Using int() and float() functions. Syntax: int(expression) float(expression) Computer Programming - CSC 1401 22 Type Conversion Examples Converting Float to Int: Truncates decimal part (does not round). Examples: int(4.75) # Output: 4 int(17.3) # Output: 17 int(3.14159) # Output: 3 Converting Int to Float: Adds a decimal point. Example: float(42) # Output: 42.0 Computer Programming - CSC 1401 23 Practice Question What is the result of the following code? result = int(5.99) + float(2) print(result) A) 7.99 B) 7.0 C) 8.0 D) 7 24 Practice Question Solution What is the result of the following code? result = int(5.99) + float(2) print(result) A) 7.99 Calculations: B) 7.0 - int(5.99) → 5 C) 8.0 - float(2) → 2.0 D) 7 - 5 + 2.0 → 7.0 (since one operand is float, result is float) 25 Summary Expressions: Combinations of operands and operators. Evaluated according to precedence rules. Operators: Arithmetic operators perform mathematical operations. Operator precedence affects evaluation order. Literals: Directly represent values in code. Include integers, floats, strings, booleans. Type Conversion: Implicit and explicit conversions between types. Use int() and float() for explicit conversion. Computer Programming - CSC 1401 26 Module 4 Variables 27 What is a Variable? Variable: A named location in memory that stores a value. Think of a variable as a container that holds data. Allows us to store, retrieve, and manipulate data in our programs. Computer Programming - CSC 1401 28 Why Use Variables? Avoid Redundancy: Store values that are used multiple times. Simplify code maintenance and readability. Flexibility: Easily change values in one place. Variables can be updated as the program runs. Computer Programming - CSC 1401 29 Defining Variables in Python Syntax: variable_name = expression Assignment Operator = : Evaluates the expression on the right. Stores the result in the variable on the left. Computer Programming - CSC 1401 30 Variable Naming Rules Must start with: A letter (a-z, A-Z) Or an underscore _ Can contain: Letters, digits (0-9), underscores Cannot contain: Spaces Special characters (e.g., !, @, #, $) Case-sensitive: age and Age are different variables. Computer Programming - CSC 1401 31 Variable Naming Conventions Use descriptive names: Good: subtotal, number_of_items Bad: x, y, z (unless context is clear) Use lowercase letters: Separate words with underscores: total_price, average_age Avoid using Python keywords: Such as print, def, if, else Computer Programming - CSC 1401 32 Examples of Variable Definitions Simple Assignment: subtotal = 30 + 22 + 17 + 46 Using Variables in Expressions: tax_rate = 0.1 taxes = subtotal * tax_rate total = subtotal + taxes Computer Programming - CSC 1401 33 Using Variables in Expressions Variables can be used in place of values: Once defined, they can be used in any expression. Example: subtotal = 115 print("Subtotal:", subtotal) print("Taxes:", subtotal * 0.1) print("Total:", subtotal * 1.1) Computer Programming - CSC 1401 34 Updating Variable Values Variables can be reassigned: weight = 195 weight = 180 # Updated value Important: Updating a variable does not automatically update other variables that depended on the old value. Computer Programming - CSC 1401 35 Incrementing and Decrementing Variables Incrementing: Increasing the value by a certain amount. Example: x = x + 1 # Increases x by 1 Decrementing: Decreasing the value by a certain amount. Example: y = y - 1 # Decreases y by 1 Computer Programming - CSC 1401 36 Shorthand Assignment Operators Simplify incrementing/decrementing: x += 1 is equivalent to x = x + 1 y -= 1 is equivalent to y = y - 1 Other Operators: *= for multiplication: x *= 2 (doubles x) /= for division: y /= 3 (divides y by 3) //= for integer division %= for modulus Computer Programming - CSC 1401 37 Practical Example: Basal Metabolic Rate (BMR) Formula for Men: bmr_male = 4.54545 * weight + 15.875 * height - 5 * age + 5 Formula for Women: bmr_female = 4.54545 * weight + 15.875 * height - 5 * age - 161 Variables Needed: weight in kilograms height in centimeters age in years Computer Programming - CSC 1401 38 Code Example: Calculating BMR # Define variables height = 70 # in inches weight = 195 # in pounds age = 40 # in years # Convert to metric units if necessary height_cm = height * 2.54 # inches to centimeters weight_kg = weight * 0.453592 # pounds to kilograms # Calculate BMR bmr_male = 4.54545 * weight_kg + 15.875 * height_cm - 5 * age + 5 bmr_female = 4.54545 * weight_kg + 15.875 * height_cm - 5 * age - 161 # Print results print("BMR for Male:", bmr_male) print("BMR for Female:", bmr_female) Computer Programming - CSC 1401 39 Code Example: Calculating BMR # Define variables height = 70 # in inches weight = 195 # in pounds age = 40 # in years # Convert to metric units if necessary height_cm = height * 2.54 # inches to centimeters weight_kg = weight * 0.453592 # pounds to kilograms # Calculate BMR bmr_male = 4.54545 * weight_kg + 15.875 * height_cm - 5 * age + 5 bmr_female = 4.54545 * weight_kg + 15.875 * height_cm - 5 * age - 161 # Print results print("BMR for Male:", bmr_male) print("BMR for Female:", bmr_female) Computer Programming - CSC 1401 40 Variable Reassignment Example Scenario: A person loses weight from 195 lbs to 180 lbs. Update Variable: weight = 180 # Update weight variable Recalculate BMR: weight_kg = weight * 0.453592 bmr_male = 4.54545 * weight_kg + 15.875 * height_cm - 5 * age + 5 print("Updated BMR for Male:", bmr_male) Computer Programming - CSC 1401 41 Important Note on Variable Reassignment Changing a variable does not automatically update other variables. Example: After weight is updated, bmr_male must be recalculated. Why? Variables store values, not formulas. Computer Programming - CSC 1401 42 Printing Multiple Values Using Commas: print("Your BMR is", bmr_male) Output: Your BMR is 1802.61275 Multiple Variables: print("Height:", height, "inches", "Weight:", weight, "pounds") Computer Programming - CSC 1401 43 Formatting Output Default Separator: Comma-separated values are printed with spaces. Custom Separator: print("Date:", year, month, day, sep="/") Output: Date:2021/1/20 Computer Programming - CSC 1401 44 Practical Question 1 Write code to calculate the total cost of items with a 10% tax rate. Items cost: $30, $22, $17, $46 Tasks: 1. Calculate the subtotal. 2. Calculate the taxes. 3. Calculate the total. 4. Print all results. Computer Programming - CSC 1401 45 Practical Question 2 Question: A person's age is 28. Calculate how many years until they turn 65. Print a message: "You will retire in X years." Task: Use variables and appropriate calculations. Computer Programming - CSC 1401 46 Practical Question 3 1. Define variables x = 10 and y = 5. 2. Increment x by 3 using shorthand operator. 3. Decrement y by 2 using shorthand operator. 4. Multiply x and y and print the result. Computer Programming - CSC 1401 47 Summary Variables store values for later use. Assignment uses the = operator. Variable names should be descriptive and follow naming rules. Variables can be updated, but dependent variables need to be recalculated. Printing allows multiple values and custom formatting. Computer Programming - CSC 1401 48 Q&A ⁉ For Further questions and inquiries please reach out! ([email protected]) Office Hours: MWF 1 pm to 2 pm Office Place: Bldg 8B, Room 205 49