Lecture - 2: Basics of Python PDF

Summary

This document provides notes on core Python concepts, covering various aspects such as variable declarations, naming conventions, and data types. The explanations include relevant examples and real-world application scenarios.

Full Transcript

Chapter - 2 Basics of Python Outline ▪ Comments ▪ Variables ✓Variable names ✓Assign multiple values ✓Local and global variable ✓Output variable ▪ Data type ▪ Operators ▪ Conditionals Comments ▪ Python has commenting capability for the purpose of in-code documentat...

Chapter - 2 Basics of Python Outline ▪ Comments ▪ Variables ✓Variable names ✓Assign multiple values ✓Local and global variable ✓Output variable ▪ Data type ▪ Operators ▪ Conditionals Comments ▪ Python has commenting capability for the purpose of in-code documentation. ▪ Comments start with a #, and Python will render the rest of the line as a comment: """ Example: This is a comment #This is a python written in more than just one comment. line print("Hello, World!") """ print("Hello, World!") Introduction Python Python Syntax ▪ Python syntax can be executed by writing directly in the Command Line: print("Hello, World!") Python Indentation ▪ Indentation refers to the spaces at the beginning of a code line. ▪ Python uses indentation to indicate a block of code. if 5 > 2: print("Five is greater than two!") Introduction Python The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. Example Variable ▪ In Python, variables are created when you assign a value to it: ▪ Python has no command for declaring a variable. ▪ Variables are containers for storing data values. ▪ A variable is a name that identifies a location in computer memory to store data. ▪ Why ✓to reuse names instead of values ✓easier to change code later Creating Variable Example: x = 5 x = 6 # x is of type int y = "John" x = "Sally" # x is now of type str print(x) print(x) print(y) If you want to specify the data type of a variable, this can be done with casting. x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 Creating Variable Get the Type You can get the data type of a variable with the type() function. Example x=5 y = "John" print(type(x)) print(type(y)) Creating Variable Single or Double Quotes? String variables can be declared either by using single or double quotes: Example x = "John" # is the same as x = 'John' Creating Variable Case-Sensitive Variable names are case-sensitive. Example This will create two variables: a = 4 A = "Sally" #A will not overwrite a Rules of naming variables ✓An identifier can be a combination of letters (a–z, or A–Z), numbers (0–9), and underscores (_). ✓It must begin with a letter (a–z or A–Z) or underscore (_). ✓In Python, identifiers are case-sensitive, so x and X are different identifiers. ✓Identifiers can be of any length. ✓User-defined identifiers cannot be the same as words reserved by the Python language ▪ Examples of Reserved words in the Python and, def, elif, finally, etc. Full list https://docs.python.org/3/reference/lexical_analysis.html#keywords Variable Names Example Example Legal variable names: Illegal variable names: myvar = "John" 2myvar = "John" my_var = "John" my-var = "John" _my_var = "John" my var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" Multi Words Variable Names Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable: Camel Case Each word, except the first, starts with a capital letter: myVariableName = "John" Pascal Case Each word starts with a capital letter: MyVariableName = "John" Snake Case Each word is separated by an underscore character: my_variable_name = "John" Variables an assignment binds name to value. this is done by using the assignment operator =. student = ‘Abel’ grade = 89 student Abel grade 89 Multiple assignment student, grade = ‘Abel’, 89 Assign Multiple Values Many Values to Multiple Variables Python allows you to assign values to multiple variables in one line: Example: your own Python Serve x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) Assign Multiple Values One Value to Multiple Variables And you can assign the same value to multiple variables in one line: Example x = y = z = "Orange" print(x) print(y) print(z) Assign Multiple Values Unpack a Collection If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking. Example: Unpack a list: fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z) Output Variables The Python print() function is often used to output variables. Example:: You can also use Example the + operator to x = "Python " x = "Python is awesome" output multiple y = "is " variables: z = "awesome" print(x) print(x + y + z) In the print() function, you Example: x = "Python" output multiple variables, y = "is" separated by a comma: z = "awesome" print(x, y, z) Output Variables In the print() function, when you try The best way to output multiple to combine a string and a number variables in the print() function is to with the + operator, Python will separate them with commas, which give you an error: even support different data types: Example: Example: x = 5 x = 5 y = "John" y = "John" print(x + y) print(x, y) Global Variables Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables. Global variables can be used by everyone, both inside of functions and outside. Example: Create a variable outside of a function, and use it inside the function x = "awesome" def myfunc(): print("Python is " + x) myfunc() Global Variables If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value. Example Create a variable inside a function, with the same name as the global variable x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x) Variables In python variables are dynamically typed. ✓no need to declare its type before a variable is introduced. ✓Its type is determined by the value assigned to it. ✓Its type might change later. a 5 This is possible in python python a=5 a = ‘python’ Variables You can check the type of a variable using type() function. a=5 type(a) will return int. We can convert the value of a variable into another type using specific built-in functions, such as int(), float(), str() Data type: Built-in Data Types Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default. built-in Data Type Example Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType Data type Getting the Data Type You can get the data type of any object by using the type() function: Example: Print the data type of the variable x: x = 5 print(type(x)) Data type: Setting the Data Type In Python, the data type is set when you assign a value to a variable: Example Data Type Example Data Type x = "Hello World" str x = {"name" : "John", "age" : 36} dict x = 20 int x = {"apple", "banana", "cherry"} set x = 20.5 float x = frozenset({"apple", "banana"}) frozenset x = 1j complex x = True bool x = ["apple", "banana"] list x = b"Hello" bytes x = ("banana", "cherry") tuple x = bytearray(5) bytearray x = range(6) range x = memoryview(bytes(5)) memoryview x = None NoneType Python Numbers There are three numeric Variables of numeric types types in Python: are created when you assign int a value to them: float Example complex a = 4 # int b = 3.41 # float c = 3j # complex To verify the type of any object in Python, use the type() function: Example print(type(a)) print(type(b)) print(type(c)) Python Numbers Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. Example integers: x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) Python Numbers Float, or "floating point number" is a number, positive or negative, containing one or more decimals. Example floats: Float can also be scientific numbers with x = 1.10 an "e" to indicate the power of 10. y = 1.0 z = -35.59 Example floats: x = 35e3 y = 12E4 print(type(x)) z = -87.7e100 print(type(y)) print(type(z)) print(type(x)) print(type(y)) print(type(z)) Python Numbers Complex: Type Conversion You can convert from one type to another with Complex numbers are the int(), float(), and complex() methods: written with a "j" as the Example Convert from one type to another: imaginary part: x = 1 # int y = 2.8 # float z = 1j # complex Example Complex: #convert from int to float: x = 3+5j a = float(x) y = 5j b = int(y) #convert from float to int: z = -5j c = complex(x) #convert from int to complex: print(a) print(type(x)) print(b) print(type(y)) print(c) print(type(z)) print(type(a)) print(type(b)) print(type(c)) Python Numbers Random Number Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: Example Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1, 10)) Casting: Specify a Variable Type Example Integers: Example Floats: x = int(1) # x will be 1 x = float(1) # x will be 1.0 y = int(2.8) # y will be 2 y = float(2.8) # y will be 2.8 z = int("3") # z will be 3 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2 Example Strings: x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0' Python Booleans Booleans represent one of two values: True or False. Boolean Values In programming you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer: Python Booleans Example Example Print a message based on whether the print(10 > 9) condition is True or False: print(10 == 9) a = 200 b = 33 print(10 < 9) if b > a: print("b is greater than a") else: print("b is not greater than a") Python Booleans Evaluate Values and Variables The bool() function allows you to evaluate any value, and give you True or False in return, Example Example Evaluate two variables: Evaluate a string and a x = "Hello" number: y = 15 print(bool("Hello")) print(bool(x)) print(bool(15)) print(bool(y)) Python Booleans Functions can Return a Boolean You can execute code based on the You can create functions that Boolean answer of a function: returns a Boolean Value: Example Example Print "YES!" if the function returns Print the answer of a True, otherwise print "NO!": function: def myFunction() : return True def myFunction() : return True if myFunction(): print("YES!") print(myFunction()) else: print("NO!") Python Operators Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values: Example: print(3 + 2) Python divides the operators in the following groups: Arithmetic operators Identity operators Assignment operators Membership operators Comparison operators Bitwise operators Logical operators Operators Arithmetic operators used on numbers i + j ->> sum i - j ->> difference if both are ints, result is int if either or both are floats, result is float i * j ->> product i / j ->> division result is float i ** j ->> power i % j ->> the remainder when i is divided by j i // j ->> floor division Operators Operators Precedence rules Exponent operation (*) has the highest precedence. Unary negation (−) is the next. Multiplication (*), division (/), floor division (//), and modulus operation (%) have the same precedence and will be evaluated next unary negation. Addition (+) and subtraction (−) are next, with the same precedence. Example >>> 12 + 3 * 21 75 ((23 + 32) // 6 - 5 * 7 / 10) * 2 ** 3 Operators Comparison operators used to compare two objects. i>j i >= j i True if both are True i or j => True if either or both are True Logical expressions are often used in if and while statements Operators Assignment operators Used to store data in variables for later use. i=j i += j -> i = i + j i -= j -> i = i - j i *= j -> i = i * j i /= j -> i = i / j i %= j -> i = i % j i //= j -> i = i // j i **= j -> i = i ** j Operators Python Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operators Python Membership Operators Membership operators are used to test if a sequence is presented in an object: Operators: Python Bitwise Operators Bitwise operators are used to compare (binary) numbers: Control flow : Conditionals Programs doesn’t always go sequentially. ✓Jump ✓Branch We might want to run a statement or a block of statements only under certain conditions. We use the if statement for this purpose. Conditionals An if statement can be followed by 0 or n elif and/or 0 or 1 else statements. has a value True or False evaluate expressions in that block if is True Conditionals In Python indentation is important That is how you denote blocks of code. Questions 1. Explain the Specific Data Type in python with an example 2. What are the data types 3. What will the following code output? of the following values? a = 15 a) 42 b=4 b) 3.14 print(a // b) c) "Hello, World!“ print(a % b) d) True print(a ** b) Questions 4. Which of the following variable names are valid in Python? my_var 2ndVar Price$ class 5. What happens when you run the following code? x = "10" x = "10“ y = 20 y = 20 print(x + y) print(int(x) + y)

Use Quizgecko on...
Browser
Browser