Full Transcript

Introduction to Computers and Programming Dr. Majid Khonji Based on Dr. Shakti Singh’s Slides 1 What is a Computer 2 What is a Computer Data is a coll...

Introduction to Computers and Programming Dr. Majid Khonji Based on Dr. Shakti Singh’s Slides 1 What is a Computer 2 What is a Computer Data is a collection of raw facts or figures Information comprises of processed data to provide answers to who, what, where, and when type of questions Knowledge is the application of data and information to answer how part of the question Instructions are Commands given to the computer that tells what it must do |3 Block Diagram of a Computer |4 Computer System Computer System Hardware Software OS Applications Translator CPU I/O devices Memory ALU RAM Machine Assembly High Level Languages CU ROM Compiler Registers 2nd Memory Assembler Interpreter 5 Computer Main Components  Programs: A formal language, which comprises of a set of instructions for the computer  Software: A set of programs. It can range from system software (like operating systems) to application software (like word processors)  Hardware: It refers to the physical components of a computer, such as the processor, memory, motherboard, and input/output devices |6 What is a program? A formal language, which comprises a set of instructions that produce various kinds of output Programming languages consist of instructions for computers These instructions often implement a specific Muḥammad ibn Mūsā al-Khwārizmī algorithm ‫محمد بن موسى الخوارزمي‬ Born approximately 780, died between 835 and 850 Persian mathematician and astronomer from the Khorasan province of present-day Uzbekistan Implemented in a Programming Language The word algorithm is derived from his name 7 Different levels of Programming Languages |8 Programming Languages Machine Languages (Low Level Language) The language computer directly understands Each instruction is represented by a set of binary digits - 0’s and 1’s Machine dependent (Intel, Mac, Motorola) Examples 100100 010001 //Load 100110 010010 //Multiply 100010 010011 //Store 9 What is 0 and 1? Bit: The basic unit of information—0 or 1. Signals: 0 = off, 1 = on. All Data: Everything (text, images, sound) is binary. Core Logic: 0 and 1 power all computer functions Programming Languages Assembly Languages The language that is more understandable by human English-like abbreviations to represent the instruction, called mnemonic Each mnemonic directly corresponds to a single machine code instruction Needs assemblers to convert them to machine language Example ADD r1,10 LOAD r2,x CMP r1,r2 JMP 04003F3 11 Low Level and Assembly Language Opcode hex. Description of the Operation Mnemo. 0000 Halt. End of program execution HLT 0001 Load operand to accumulator LOA 0010 Store accumulator at designated address STI 0011 Add operand to accumulator ADD 0100 Subtract operand from accumulator SUB 0101 Multiply operand with accumulator MUL 0110 Divide accumulator by operand DIV 0111 Unconditional jump JMP 1000 Jump if accumulator = 0 JEZ 1001 Jump if accumulator > 0 JGZ 1010 Jump if accumulator < 0 JLZ 1100 Stack commands - 1101 Jump to subroutine JSR 1110 Return from subroutine RET 1111 Index commands - 12 Programming Languages: Low Level and Assembly Language Has a limited number of programming constructs More challenging and time-consuming to code, and difficult to debug (fix errors) Writing code at the processor level typically requires assembly language, which is specific to a processor architecture or family Commonly used in computer forensics, brute-force cyber-attacks, and occasionally in extreme debugging situations to identify specific issues, typically requiring highly specialized expertise | 13 Programming Languages: High Level Languages Example: Python, C, C++, Java, Rust and GoLang.. Understandable to human Uses common mathematical operations (+,-,*,/) Single statements to perform substantial tasks Fewer lines of code than Assembly language to perform a similar task Uses compilers/Interpreter and linkers | 14 Programming Languages: High Level Languages (Cont.) The code explains how a problem is to be solved rather than giving instructions on how the computer will provide a solution High-level languages can be used on a variety of different machines; however, they are not as efficient as low-level languages A few features that high-level languages have, which are not available in low-level languages: Selection and iteration constructs such as, IF..THEN.ELSE, FOR…ENDFOR, WHILE…ENDWHILE. Boolean operators such as AND, OR and NOT which enable complex conditional statements to be constructed. Identifiers using an unlimited number of alphabetic and numeric characters and some special characters Allow meaningful and sensible variable names. For example, firstName, lastName etc. Data structures such as arrays, lists, tuples and dictionaries (records). | 15 Different levels of Programming Languages Machine binary language Low-level assembly High-level | 16 Different levels of Programming Languages 17 Program Translators The computer does not understand your language! Source code refers to any program written in a high-level language. However, computers are incapable of understanding source code. Before it can be executed, source code must first be converted into a form that a computer can comprehend, which is known as Object code Translator is a program that converts source code into object code Generally, the types of translators are: | 18 What is a Compiler? 19 Compiler and Interpreter Java and C++ Python, BASIC, JavaScript, and Pascal | 20 What is an Assembler? An assembler translates assembly language into object code and is effectively a compiler for the assembly language but can also be used interactively like an interpreter Unlike compilers and interpreters, which generate several machine code instructions for each high-level instruction, assemblers generate only one machine code instruction for each assembly instruction. | 21 How to program? A Program is a set of ordered instructions to perform certain task Steps for writing a program Problem Analysis : Define the problem What is input(s), output(s), process Design a solution (algorithm and flowchart) Program Implementation (coding) Program Compiling (or interpretation) Program Execution and testing 22 How to program: Example Being an expert in programming, a math instructor contacts and asks you to design a software that solves a first order equation. 23 How to program: Example (cont) Problem analysis: 1. First order equation: ax + b = c 2. Input: a, b, c: three real numbers 3. Output x : the solution 4. Process: solve the equation: x = (c-b)/a 24 How to program: Example (cont) Design the solution: The algorithm 1. Ask the user to enter a, b, and c 2. Read a, b, and c 3. Compute x = (c-b)/a 4. Display x 25 How to program: Example (cont) Program Implementation (coding) Program Compiling / Interpretation Program Execution and testing We will see these later 26 Computer Memory Computer memory is an internal storage area in the computer used to store data and programs either temporarily or permanently No processing is done in the computer memory RAM is used for short-term, high- Primary memory Secondary memory speed data access Holds instructions and data Holds data not currently in ROM stores essential instructions while the program is use and provide long-term needed for starting up the system executing storage (RAM, ROM…) (Hard Drives…) Hard Drives are used for long-term data storage |27 Computer Memory |28 Data Representation Bit is a short form of binary digit. It is the smallest possible unit of data. In computerized data a bit can either be 0 or 1. Nibble is a group of four binary digits. Byte is a group of eight bits. A nibble is a half byte. Bits 0 through 3 are called the low order nibble, and bits 4 through 7 form the high order nibble Word is group of 2,4, 8 bytes is called a word, depending on the computer architecture. Bits 0 through 7 form the low order byte and bits 8 through 15 form the high order byte. | 29 Course Topics - 2 and 3 COSC 114 Introduction to Computing – Python Dr. Shakti Singh Fall 2024 Dr. Shakti Singh |1 Features of Python Simple Embeddable Easy to Learn Extensive Versatile Easy maintenance Free and Open Source Secure High-level Language Robust Interactive Multi-threaded Portable Garbage Collection Object Oriented Interpreted Dynamic Extensible Dr. Shakti Singh |2 Python IDE Note - Please follow instructions provided in Lab0 to install IDE for Python Dr. Shakti Singh |3 Syntax It refers to the rules and regulations for writing any statement in a programming language It does not have anything to do with the meaning of the statement A statement is syntactically valid if it follows all the rules It is related to the grammar and structure of the language Example – print(expression) - This is a valid syntax for using the print statement in Python print(expression - Not a valid syntax, it'll return a Syntax Error Dr. Shakti Singh |4 Semantics It refers to the meaning associated with the statement in a programming language It is all about the meaning of the statement which interprets the program easily Errors are handled at runtime Syntax refers to grammar, while Semantics refers to meaning Dr. Shakti Singh |5 Syntax vs Semantics x=3 The syntax for the code is correct, but the semantics is wrong, y='Cola' because it doesn't send a valid meaning. An integer can not be print(x/y) divided by a string. x=3 y=5 The semantics for the code is correct, but the syntax is wrong if x=y: print('x and y are equal) x=3 y=5 if x==y: The semantics and the syntax is correct print('x and y are equal') Dr. Shakti Singh |6 Syntax and Semantics Syntax Semantics Meaning Rules of any statement in the programming language. The meaning associated with any statement Error Generally encountered at the compile time. It is generally encountered at run time. Linguistics Order of words, determined writer’s style and grammar rules. Logical semantics and lexical semantics. Sensitivity Sensitive in most programming languages. Semantics are case-insensitive. Dr. Shakti Singh |7 Memory Management In python everything is an object and it’s a dynamically typed language Types are assigned based on the x = 10: x is assigned to 10 , the type of x is int (integer) value it is referring to unlike other x = "10": x is again reassigned to "10", but the type of x is str (string) programming languages Python memory manager is responsible for allocating and de-allocating the memory Memory has two parts - Stack Memory —all the methods/method calls , references are store in stack memory Heap Memory — all the objects are stored in heap Dr. Shakti Singh |8 Memory Management Dr. Shakti Singh |9 Memory Management a=1 b=10 print('id of a is',id(a),'and id of b is',id(b)) OUTPUT: id of a is 140706977407784 and id of b is 140706977408072 c=a print('id of a is',id(a),'and id of b is',id(b),'and id of c is',id(c)) OUTPUT: id of a is 140706977407784 and id of b is 140706977408072 and id of c is 140706977407784 Dr. Shakti Singh |10 Memory Management The process of de-allocating the memory or deleting the un-used objects so that it can be made available to other objects is called Garbage Collection Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero It periodically frees and reclaims blocks of memory that no longer are in use The job of the garbage collector is to keep track of the objects which can de-allocated Dr. Shakti Singh |11 Comparison to other programming languages Dr. Shakti Singh |12 Literal Constants  The value of a literal constant can be used directly in programs. For example, 7, 3.9, 'A', and "Hello" are literal constants  Numbers refers to a numeric value. You can use four types of numbers in Python program- integers, long integers, floating point, and complex numbers Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers are called long integers. For example, 535633629843 is a long integer Numbers like are 3.23 and 91.5E-2 are termed as floating-point numbers Numbers of a + bi form (like -3 + 7i) are complex numbers Dr. Shakti Singh |13 Literal Constants Examples: OUTPUT: print(10+7) 17 print(50+40-35) 55 print(12*10) 120 Dr. Shakti Singh |14 Literal Constants Strings A string is a group of characters Using Single Quotes ('): For example, a string can be written as 'HELLO' Using Double Quotes ("): Strings in double quotes are exactly same as those in single quotes. Therefore, 'HELLO' is same as "HELLO" Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You can use as many single quotes and double quotes as you want in a string within triple quotes Dr. Shakti Singh |15 Literal Constants Strings Examples: OUTPUT: Hello print('Hello', "Hello", '''Hello''') Hello Hello print('''Hello print("Hello How How Are Are You''') You") OUTPUT: Hello OUTPUT: How Error Are You Dr. Shakti Singh |16 Escape Sequences An escape sequence is a sequence of characters that, when used inside a character or string, does not represent itself but is converted into another character or series of characters that may be difficult or impossible to express directly, like newline (\n), tab (\t), and so on. Some characters (like ", \) cannot be directly included in a string. Such characters must be escaped by placing a backslash before them. Dr. Shakti Singh |17 Escape Sequences OUTPUT: print("Who's at the door?") Who's at the door? OUTPUT: print('Who's at the door?') Error OUTPUT: print('Who\'s at the door?') Who's at the door? Dr. Shakti Singh |18 Escape Sequences OUTPUT: print('Khalifa University') Khalifa University OUTPUT: print('Khalifa\tUniversity') Khalifa University OUTPUT: print('Khalifa \tUniversity') Khalifa University print('Khalifa\nUniversity') OUTPUT: Khalifa University Dr. Shakti Singh |19 Escape Sequences Dr. Shakti Singh |20 Raw Strings If you want to specify a string that should not handle any escape sequences and want to display exactly as specified, then you need to specify that string as a raw string. A raw string is specified by prefixing r or R to the string. OUTPUT: print('Who\'s at the door?') Who's at the door? OUTPUT: print(R'Who\'s at the door?') Who\'s at the door? Dr. Shakti Singh |21 Variables Variable means its value can vary. You can store any piece of information in a variable. Variables are nothing but just parts of your computer’s memory where information is stored. To be identified easily, each variable is given an appropriate name. First_Name=Fatima Last_Name=Ali year=2024 location=Abu Dhabi pi=3.14159265359 Dr. Shakti Singh |22 Identifiers Identifiers are names given to identify something. This something can be a variable, function, class, module or other object. For naming any identifier, there are some basic rules like: The first character of an identifier must be an underscore ('_') or a letter (upper or lowercase) The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or digits (0-9) Identifier names are case-sensitive. For example, myvar and myVar are not the same Punctuation characters such as @, $, and % are not allowed within identifiers Examples of valid identifier names : sum, __my_var, num1, r, var_20, First, etc. Examples of invalid identifier names : 1num, my-var, %check, Basic Sal, H#R&A, etc. Dr. Shakti Singh |23 Assigning or Initializing Values to Variables In Python, programmers need not explicitly declare variables to reserve memory space. The declaration is done automatically when a value is assigned to the variable using the equal sign (=). The operand on the left side of equal sign is the name of the variable and the operand on its right side is the value to be stored in that variable. Dr. Shakti Singh |24 Data Type Boolean Boolean is another data type in Python. A variable of Boolean type can have one of the two values- True or False. Like other variables, the Boolean variables are also created while we assign a value to them or when we use a relational operator on them. Dr. Shakti Singh |25 Data Type Boolean Examples: a=20 b=20 OUTPUT: True print(a==b) a=20 b=20 OUTPUT: False print(a>b) a='Khalifa' b='University’ OUTPUT: True print(a!=b) a='Khalifa' b='University’ OUTPUT: True print(ab) and (b>c) ; the whole expression is true only if both expressions are true. Example - a=4 b=5 print(a>1 and b>1) OUTPUT: True Dr. Shakti Singh |39 Logical Operators Logical OR operator is used to simultaneously evaluate two conditions or expressions with relational operators. If one or both the expressions of the logical operator is true, then the whole expression is true. For expression (a>b) or (b>c); the whole expression is true if either of the expressions is true. Example - a=4 b=5 print(a>1 or b>1) OUTPUT: True Dr. Shakti Singh |40 Logical Operators Logical NOT operator takes a single expression and negates the value of the expression. Logical NOT produces a zero (False) if the expression evaluates to a non-zero value and produces a 1 (True) if the expression produces a zero. # not True OUTPUT: a=5 OUTPUT: a = 5 5 False b=3 True b = not a 98895 False print(a!=b) print(a,b) 0 True # not True c = 98895 d = not c print(c,d) # not False e = 0 f = not e print(e,f) Dr. Shakti Singh |41 Membership and Identity Operators Python supports two types of membership operators–in and not in. These operators, test for membership in a sequence such as strings, lists, or tuples.  in Operator: The operator returns true if a variable is found in the specified sequence and false otherwise. For example, a in nums returns 1, if a is a member of nums.  not in Operator: The operator returns true if a variable is not found in the specified sequence and false otherwise. For example, a not in nums returns 1, if a is not a member of nums. Dr. Shakti Singh |42 Membership and Identity Operators a=[1,5,4] a=[1,5,4] a= 'Khalifa' print(5 in a) b=4 b= 'x' print(6 in a) if b in a: if b in a: print ('b is in a') print ('b is in a') if b not in a: if b not in a: print ('b is not a') print ('b is not a') OUTPUT: OUTPUT: OUTPUT: True b is in a b is not a False Dr. Shakti Singh |43 Membership and Identity Operators Identity Operators is Operator: Returns true if operands or values on both sides of the operator point to the same object and false otherwise. For example, if a is b returns 1, if id(a)is same as id(b) is not Operator: Returns true if operands or values on both sides of the operator does not point to the same object and false otherwise. For example, if a is not b returns 1, if id(a) is not same as id(b) Dr. Shakti Singh |44 Membership and Identity Operators a= 'Khalifa' a= 'Khalifa' a= 2000 b= 'x' b= 'Khalifa' b= 1000 if b is a: print(b is not a) print(b is not a) print ('b is a') if b is not a: print ('b is not a') OUTPUT: OUTPUT: OUTPUT: b is not a False True Dr. Shakti Singh |45 None and 0 None represents the absence of a value or a null value. It is often used to signify that a variable or function does not have a value or that a value is missing 0 represents the integer value zero. It is a numeric value and can be used in arithmetic operations and comparisons Dr. Shakti Singh |46 Operator Precedence Highest Lowest Dr. Shakti Singh |47 Associativity left-right associativity If two operators have the same precedence, then print(5*2//3) left-right associativity is followed print(3**2**2) OUTPUT: right-left associativity Except for exponentiation, which follows right-left 3 associativity 81 a = 10 b = 20 if not 10+10==b or a==40 and 70==80: OUTPUT: print('Yes') No elif a != b: print('No') Dr. Shakti Singh |48 Basic Data Type Declaration and their ranges Int -(2^31) to (2^31)-1 bits) Float (1 sign bit, 11bits exponent, 52 bits mantissa) Complex (64bit float) Boolean (1 bit) String (depends on available system memory) Dr. Shakti Singh |49 Output Formatting Strings using normal formatting Uni_name_1='Khalifa' Uni_name_2='University' Age=18 print('I study at',Uni_name_1,Uni_name_2,'and I am',Age,'years old.') print('I study at',Uni_name_1,Uni_name_2,'\nand I am',Age,'years old.') print('I study at',Uni_name_1,Uni_name_2,'\tand I am',Age,'years old.') OUTPUT: I study at Khalifa University and I am 18 years old. I study at Khalifa University and I am 18 years old. I study at Khalifa University and I am 18 years old. Dr. Shakti Singh |50 Output Formatting Strings can also be formatted using f-strings Uni_name_1='Khalifa' Uni_name_2='University' Age=18 # using f strings print(f'I study at {Uni_name_1} {Uni_name_2} and I am {Age} years old.') OUTPUT: I study at Khalifa University and I am 18 years old. Dr. Shakti Singh |51 Output Formatting Strings can also be formatted using.format() Uni_name_1='Khalifa' Uni_name_2='University' Age=18 # using format method print('I study at {} {} and I am {} years old.'.format(Uni_name_1,Uni_name_2,Age)) OUTPUT: I study at Khalifa University and I am 18 years old. Dr. Shakti Singh |52 Output Formatting Strings can also be formatted using.format() Uni_name_1='Khalifa' Uni_name_2='University' Age=18 # using format method print('I study at {0} {1} and I am {2} years old.'.format(Uni_name_1,Uni_name_2,Age)) OUTPUT: I study at Khalifa University and I am 18 years old. print('I study at {2} {0} and I am {1} years old.'.format(Uni_name_1,Uni_name_2,Age)) OUTPUT: I study at 18 Khalifa and I am University years old. Dr. Shakti Singh |53 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # %s accepts strings print("I study at %s" %('KU')) # %d accepts decimal print("I am %d years old" %(18)) print("I study at %s and I am %d years old" %('KU',18)) OUTPUT: I study at KU I am 18 years old I study at KU and I am 18 years old Dr. Shakti Singh |54 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # a number after % determines how many characters to print print("I study at %7s" %('KUAUH')) print("I am %7d years old" %(186)) # a number after the decimal determines precision print("I am %7.5d years old" %(186)) OUTPUT: I study at KUAUH I am 186 years old I am 00186 years old Dr. Shakti Singh |55 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # Other types of numbers OUTPUT: print('Floating number is: %f' %(5.1234)) Floating number is: 5.123400 print('Floating number is: %.10f' %(5.1234)) Floating number is: 5.1234000000 print('Floating number is: %20.10f' %(5.1234)) Floating number is: 5.1234000000 # Other types of numbers OUTPUT: print('Floating number is: %d' %(5.1234)) Floating number is: 5 print('Floating number is: %.10d' %(5.1234)) Floating number is: 0000000005 print('Floating number is: %20.10d' %(5.1234)) Floating number is: 0000000005 Dr. Shakti Singh |56 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # Other types of numbers print('Scientific number of 1000 is: %e' %(1000)) print('Scientific number of 1000 is: %.10e' %(1000)) print('Scientific number of 1000 is: %20.10e' %(1000)) OUTPUT: Scientific number of 1000 is: 1.000000e+03 Scientific number of 1000 is: 1.0000000000e+03 Scientific number of 1000 is: 1.0000000000e+03 Dr. Shakti Singh |57 Output Formatting and Operators Course Topic 3 COSC 114 Introduction to Computing Dr. Majid Khonji Based on Dr. Shakti Singh’s Slides 1 Last Lecture Input function Understanding data types Python Operators Today Quick Revision: Operators Expressions in Python Output Formatting Data Types and Their Size Data Type Description Size (Bytes) Size (Bits) int Integer numbers 4 bytes 32 bits float Floating-point numbers 8 bytes 64 bits complex Complex numbers 16 bytes 128 bits bool Boolean (True/False) 1 byte 8 bits str String (text data) Depends on the length - bytes Binary data Depends on the length - Ordered, mutable list Dynamic - sequence Ordered, immutable tuple Dynamic - sequence Unordered, unique set Dynamic - elements |4 sing type() Function in Python The type() function is used to determine the data type of a variable Syntax type(variable) Example x = 10 print(type(x)) # Output: y = 3.14 print(type(y)) # Output: |5 Operators in Python Definition: Operators are special symbols or keywords used to perform operations on variables and values Categories Assignment Operator Arithmetic Operators Comparison Operators |6 Arithmetic Operators |7 Logical Operators |8 Logical Operators X Y not X X and Y X or Y True True False True True True False False False True False True True False True False False True False False and or Note that (anything) will not be executed in both cases Logical Operators Logical AND operator is used to simultaneously evaluate two conditions or expressions with relational operators. If expressions on both the sides (left and right side) of the logical operator are true, then the whole expression is true. For expression (a>b) and (b>c) ; the whole expression is true only if both expressions are true. Example - a=4 b=5 print(a>1 and b>1) OUTPUT: True |10 Logical Operators Logical OR operator is used to simultaneously evaluate two conditions or expressions with relational operators. If one or both the expressions of the logical operator is true, then the whole expression is true. For expression (a>b) or (b>c); the whole expression is true if either of the expressions is true. Example - a=4 b=5 print(a>1 or b>1) OUTPUT: True |11 Logical Operators Logical NOT operator takes a single expression and negates the value of the expression. Logical NOT produces a zero (False) if the expression evaluates to a non-zero value and produces a 1 (True) if the expression produces a zero. # not True OUTPUT: a=5 OUTPUT: a = True True False b=3 True b = not a print(a!=b) print(a,b) # not True c = 98895 98895 False d = not c print(c,d) # not False e = 0 0 True f = not e print(e,f) |12 Bitwise Operators Similar to Logic operator, but at the bit level Bitwise operators perform operations at the bit level. These operators include bitwise AND (&), bitwise OR(|), bitwise XOR(^), and NOT(!) operators. Bitwise operators expect their operands to be of integers and treat them as a sequence of bits. The truth tables of these bitwise operators are given below. |13 Bitwise Operators a=2 b=3 OUTPUT: print(a,bin(a)) 2 0b10 print(b,bin(b)) 3 0b11 print(a&b,bin(a&b)) 2 0b10 a=2 b=3 OUTPUT: print(a,bin(a)) 2 0b10 print(b,bin(b)) 3 0b11 print(a|b,bin(a|b)) 3 0b11 |14 Pitfalls Python's weak typing has pitfalls, especially in the context of type conversions Example if 'False’: print("I'm here") ## Counter-intuitively works '5' * 3 # Outputs '555' Expressions in Python Expressions  What is an Expression?  An expression is a combination of values, variables, and operators that Python interprets and evaluates to produce a result  Main Types of Expressions:  Arithmetic expressions: Use arithmetic operators to perform mathematical calculations.  Example: 3+5*3  Logical expressions: Combine conditions to return Ture or False.  Example: 5 > 3 and 2 < 4  Bitwise Expressions  Evaluation:  Python evaluates expressions by following operator precedence rules to determine the order in which operations are executed. Operator Precedence Definition Operator precedence determines the order in which operations are performed in an expression when there are multiple operators Why it matters? Ensures accurate evaluation of expressions. Prevents ambiguity in complex expressions. Example: What is the output of 3 + 4 * 2? 13 (Multiplies 4 * 2 before adding 3) Operator Precedence Highest Lowest 19 Operator Precedence 5+Num*7 Which operation is performed first ? *, /, % are at a higher level of precedence than + and – If you want to impose a given operation to be executed first, use the parenthesis as follows: Example: (5 + Num1)* 7 Associativity left-right associativity If two operators have the same precedence, then left-right associativity is followed right-left associativity Except for exponentiation, which follows right-left associativity Examples - 21 Example Given a = 2, b = 3, c = 6 , Evaluate the following expressions: (a*2 > b and c < 10) True (c*b % 2) 0 (not True and True and False) False (True or True and False) True [ because and has higher precedence than or ] Output Formatting Strings in Python A string is a sequence of characters enclosed in quotes. Example: "Hello, World!" or 'Python’ Character representation in computer ASCII (American Standard Code for Information Interchange): ASCII is a character encoding standard that represents 128 characters using 7- bit binary numbers Includes English letters, digits, and common symbols. Example: 'A' -> 65 (ASCII value of 'A'). |25 Escape Sequences 26 Output Formatting: Normal Formatting Uni_name_1='Khalifa' Uni_name_2='University' Age=18 print('I study at',Uni_name_1,Uni_name_2,'and I am',Age,'years old.') print('I study at',Uni_name_1,Uni_name_2,'\nand I am',Age,'years old.') print('I study at',Uni_name_1,Uni_name_2,'\tand I am',Age,'years old.') OUTPUT: I study at Khalifa University and I am 18 years old. I study at Khalifa University and I am 18 years old. I study at Khalifa University and I am 18 years old. |27 Output Formatting: f-string Strings can also be formatted using f-strings Uni_name_1='Khalifa' Uni_name_2='University' Age=18 # using f strings print(f'I study at {Uni_name_1} {Uni_name_2} and I am {Age} years old.') OUTPUT: I study at Khalifa University and I am 18 years old. |28 Output Formatting:.format Strings can also be formatted using.format() Uni_name_1='Khalifa' Uni_name_2='University' Age=18 # using format method print('I study at {} {} and I am {} years old.'.format(Uni_name_1,Uni_name_2,Age)) OUTPUT: I study at Khalifa University and I am 18 years old. |29 Output Formatting:.format print('I study at {2} {0} and I am {1} years old.'.format(Uni_name_1,Uni_name_2,Age)) OUTPUT: I study at 18 Khalifa and I am University years old. |30 Output Formatting: % Operator Output formatting is done using modulo operator (used in many programming languages): %d and %f is used to output numbers and %s is used to output strings # %s accepts strings print("I study at %s" %('KU')) # %d accepts decimal print("I am %d years old" %(18)) print("I study at %s and I am %d years old" %('KU',18)) OUTPUT: I study at KU I am 18 years old I study at KU and I am 18 years old |31 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # a number after % determines how many characters to print print("I study at %7s" %('KUAUH')) print("I am %7d years old" %(186)) # a number after the decimal determines precision print("I am %7.5d years old" %(186)) OUTPUT: I study at KUAUH I am 186 years old I am 00186 years old |32 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # Other types of numbers OUTPUT: print('Floating number is: %f' %(5.1234)) Floating number is: 5.123400 print('Floating number is: %.10f' %(5.1234)) Floating number is: 5.1234000000 print('Floating number is: %20.10f' %(5.1234)) Floating number is: 5.1234000000 # Other types of numbers OUTPUT: print('Floating number is: %d' %(5.1234)) Floating number is: 5 print('Floating number is: %.10d' %(5.1234)) Floating number is: 0000000005 print('Floating number is: %20.10d' %(5.1234)) Floating number is: 0000000005 |33 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings # Other types of numbers print('Scientific number of 1000 is: %e' %(1000)) print('Scientific number of 1000 is: %.10e' %(1000)) print('Scientific number of 1000 is: %20.10e' %(1000)) OUTPUT: Scientific number of 1000 is: 1.000000e+03 Scientific number of 1000 is: 1.0000000000e+03 Scientific number of 1000 is: 1.0000000000e+03 |34 Output Formatting Output formatting is done using modulo operator : %d and %f is used to output numbers and %s is used to output strings Output- Output- Output- 35 Exercise Write a Python Program which performs the following Output Ask user 1 to enter First Name Second Name GPA Ask user 2 to enter the same fields Print the three fields of user 1, separated by tabs, then user 2 in a second line, separated by tabs Make sure First name takes 10 spaces, Second Name 10 spaces and GPA shows two decimal float numbers Solution Output f_name1 = input("1 Please enter your first name: ") s_name1 = input("1 Please enter your second name: ") GPA1 = float(input("1 Please enter your GPA: ")) f_name2 = input("2 Please enter your first name: ") s_name2 = input("2 Please enter your second name: ") GPA2 = float(input("2 Please enter your GPA: ")) print("Info:") print("%10s\t%10s\t%10s"%("F Name", "S Name","GPA")) print("-------------------------------------") print("%10s\t%10s\t%10.2f"%(f_name1, s_name1,GPA1)) print("%10s\t%10s\t%10.2f"%(f_name2, s_name2,GPA2)) Output Formatting with f-string f-string can also format output! f_name1 = input("1 Please enter your first name: ") s_name1 = input("1 Please enter your second name: ") GPA1 = float(input("1 Please enter your GPA: ")) f_name2 = input("2 Please enter your first name: ") s_name2 = input("2 Please enter your second name: ") GPA2 = float(input("2 Please enter your GPA: ")) print("Info:") print(f"{'F Name':10s}\t{'S Name':10s}\t{'GPA':10s}") print("-------------------------------------") print(f"{f_name1:10s}\t{s_name1:10s}\t{GPA1:10.2f}") print(f"{f_name2:10s}\t{s_name2:10s}\t{GPA2:10.2f}") Output Formatting with f-string Right alignment f_name1 = input("1 Please enter your first name: ") s_name1 = input("1 Please enter your second name: ") GPA1 = float(input("1 Please enter your GPA: ")) f_name2 = input("2 Please enter your first name: ") s_name2 = input("2 Please enter your second name: ") GPA2 = float(input("2 Please enter your GPA: ")) print("Info:") print(f"{'F Name':>10s}\t{'S Name':>10s}\t{'GPA':>10s}") print("-----------------------------------------------") print(f"{f_name1:>10s}\t{s_name1:>10s}\t{GPA1:>10.2f}") print(f"{f_name2:>10s}\t{s_name2:>10s}\t{GPA2:>10.2f}") Output Formatting with f-string Left alignment f_name1 = input("1 Please enter your first name: ") s_name1 = input("1 Please enter your second name: ") GPA1 = float(input("1 Please enter your GPA: ")) f_name2 = input("2 Please enter your first name: ") s_name2 = input("2 Please enter your second name: ") GPA2 = float(input("2 Please enter your GPA: ")) print("Info:") print(f"{'F Name':

Use Quizgecko on...
Browser
Browser