Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 1 Python is easy to learn easy to use Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. Python is a powerful programming language ideal fo r scripting and rapid application development. It is used in web development , AI Artificail Intelligence , Control of (hardware , robotics and electronics ) such as designing a programs for Arduino controlllers , it is a scientific and mathematical compu ting (Orange, SymPy, NumPy) to desktop graphical user Interfaces (Pygame, Panda3D) there are many other libraries which you can use in artificial intelligence (AI) , Data science (DS) Machine Learning (ML) and Deep Learning (DL) applications , more librari es such as PyQT5 for GUI it includes 620 classes and abou 6000 functions ., T Kinter it is a GUI tool kit , WX Python this is a wrapper for WX widgets ( which is written in C++) it is for GUI too , you can download it from http://wxpython.org , Kivy for creating mobile applications it is used with HTML5 , Pyforms it includes video player , web browser and open GL , Pyfirmata it allows serial communication between a program and a pc it is used for Arduino controllers . Hi story of Python Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula - 3, C, C++, Algol - 68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the inst itute, although Guido van Rossum still holds a vital role in directing its progress. This tutorial introduces you to the basic concepts and features of Python 3. After reading the tutorial, you will be able to read and write basic Python programs, and expl ore Python in depth on your own. This tutorial is intended for people who have knowledge of other programming languages and want to get started with Python quickly. Python for Beginners If you are a programming newbie, we suggest you to visit: 1. Python Programming - A comprehensive guide on what's Python, how to get started in Python, why you should learn it, and how you can learn it. 2. Python Tutorials - Follow sidebar links one by one. Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 2 3. Python Examples - Simple examples for beginners to follow. What's covered in this tutorial? Run Python on your computer Introduction (Variables, Operators, I/O, ...) Data Structures (List, Dictionary, Set, ...) Control Flow (if, loop, break, ...) Run Python on Your computer You do not need to install Python on you r computer to follow this tutorial. However, we recommend you to run Python programs included in this tutorial on your own computer. Run Python on Windows or install Anaconda and then run it af ter that we run spider Run Python on MacOS Python Introduction Let's write our first Python program, "Hello, World!". It's a simple program that prints Hello World! on the standard output device (screen) "Hello, World!" Program print("Hello, World!") When you run the program, the output will be: Hello, World! In this program, we have used the built - in print() function t o print Hello, world! string. Variables and Literals A variable is a named location used to store data in the memory. Here's an example: a = 5 Here, a is a variable. We have assigned 5 to variable a Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 3 We do not need to define variable type in Python. You can do something like this: a = 5 print("a =", 5) a = "High five" print("a =", a) Initially, integer value 5 is assigned to the variable a . Then, the string High five is assigned to the same variable. By the way, 5 is a numeric literal and "High five" is a string literal. When you run the program, the output will be: a = 5 a = High five Visit Python Variables, Constants and Literals to learn more. Operators Operators are special symbols that carry out operations on operands (variables and values). Let's talk about arithmetic and assignment operators in this part. Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc. x = 14 y = 4 # Add two operands print('x + y =', x+y) # Output: x + y = 18 # Subtract right operand from the left print('x - y =', x - y) # Output: x - y = 10 # Multiply two operands Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 4 print('x * y =', x*y) # Outpu t: x * y = 56 # Divide left operand by the right one print('x / y =', x/y) # Output: x / y = 3.5 # Floor division (quotient) print('x // y =', x//y) # Output: x // y = 3 # Remainder of the division of left operand by the right print('x % y =', x%y) # Out put: x % y = 2 # Left operand raised to the power of right (x^y) print('x ** y =', x**y) # Output: x ** y = 38416 Assignment operators are used to assign values to variables. You have already seen the use of = operator. Let's try some more assignment opera tors. x = 5 # x += 5 ---- > x = x + 5 x +=5 print(x) # Output: 10 # x /= 5 ---- > x = x / 5 x /= 5 print(x) # Output: 2.0 Other commonly used assignment operators: - = , *= , %= , //= and **= Visit Python Operators to learn about all operators in detail. Get Input from User In Python, you can use input() function to take input from user. For example: inputSt ring = input('Enter a sentence:') print('The inputted string is:', inputString) Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 5 When you run the program, the output will be: Enter a sentence: Hello there. The inputted string is: Hello there. Python Comments There are 3 ways of creating comments in Py thon. # This is a comment """This is a multiline comment.""" '''This is also a multiline comment.''' To learn more about comments and docstring, visit: Python Comments Type Conversion The process of converting the value of one data type (integer, string, float, etc.) to another is called type conversion. Python has two types of type conversion. Implicit Typ e Conversion Implicit conversion doesn't need any user involvement. For example: num_int = 123 # integer type num_flo = 1.23 # float type num_new = num_int + num_flo Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 6 print("Value of num_new:",num_new) print("datatype of num_new:",type(num_new)) When you run the program, the output will be: Value of num_new: 124.23 datatype of num_new: datatype of num_new: <class 'float'> Here, num_new has float data type because Python always converts smaller data type to larger data type to avoid the loss of data. Here is an example where Python interpreter cannot implicitly type convert. num_int = 123 # int type num_str = "456" # str type print(num_int+num_str) When you run the program, you will get TypeError: unsupported operand type(s) for +: 'int' and 'str' How ever, Python has a solution for this type of situation which is know as explicit conversion. Explicit Conversion In case of explicit conversion, you convert the datatype of an object to the required data type. We use predefined functions like int() , float() , str() etc. to perform explicit type conversion. For example: num_int = 123 # int type num_str = "456" # str type # explicitly converted to int type num_str = int(num_str) print(num_int+num_str) To lean more, visit Python type conversion Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 7 Python Numeric Types Python supports integers, floating point numbers and complex numbers. They are defined as int , float and complex class in Python. In addition to that, booleans: True and False are a subtype of integers. # Output: <class 'int'> print(type(5)) # Output: <class 'float'> print(type(5.0)) c = 5 + 3j # Output: <class 'complex'> print(type(c)) To learn more, visit Python Number Types Python Data Structures Python offers a range of compound datatypes often referred to as sequences. You will learn about those built - in types in this section. Lists A list is created by placing all the items (elements) insid e a square bracket [] separated by commas. It can have any number of items and they may be of different types (integer, float, string etc.) # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed data types Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 8 my_list = [1, "Hello ", 3.4] You can also use list() function to create lists. Here's how you can access elements of a list. language = ["French", "German", "English ", "Polish"] # Accessing first element print(language[0]) # Accessing fourth element print(language[3]) You use the index operator [] to access an item in a list. Index starts from 0. So, a list having 10 elements will have index from 0 to 9. Python also allows negative indexing for its sequences. The index of - 1 refers to the last item, - 2 to the second last item and so on. Check these resources for more information about Python lists: Python lists (slice, add and remove item etc.) Python list methods Python list comprehension Tu ples Tuple is similar to a list except you cannot change elements of a tuple once it is defined. Whereas in a list, items can be modified. Basically, list is mutable whereas tuple is immutable. language = ("French", "German", "English", "Polish") print(lan guage) You can also use tuple() function to create tuples. You can access elements of a tuple in a similar way like a list. Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 9 language = ("French ", "German", "English", "Polish") print(language[1]) #Output: German print(language[3]) #Output: Polish print(language[ - 1]) # Output: Polish You cannot delete elements of a tuple, however, you can entirely delete a tuple itself using del operator. languag e = ("French", "German", "English", "Polish") del language # NameError: name 'language' is not defined print(language) To learn more, visit Python Tuples String A string is a sequence o f characters. Here are different ways to create a string. # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple li nes my_string = """Hello, welcome to the world of Python""" print(my_string) Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 10 You can access individual characters of a string using indexing (in a similar manner like lists and tuples). str = 'programiz' print('str = ', str) print('str[0] = ', s tr[0]) # Output: p print('str[ - 1] = ', str[ - 1]) # Output: z #slicing 2nd to 5th character print('str[1:5] = ', str[1:5]) # Output: rogr #slicing 6th to 2nd last character print('str[5: - 2] = ', str[5: - 2]) # Output: am Strings are immutable. You cannot chan ge elements of a string once it is assigned. However, you can assign one string to another. Also, you can delete the string using del operator. Concatenation is probably the most common string operation. To concatenate strings, you use + operator. Similarl y, the * operator can be used to repeat the string for a given number of times. str1 = 'Hello ' str2 ='World!' # Output: Hello World! print(str1 + str2) # Hello Hello Hello print(str1 * 3) Check these resources for more information about Python strings: Python Strings Python String Methods Python String Formatting Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 11 Sets A set is an unordered collection of items where every element is unique (no duplicates). Here is how you create sets in Python. # set of inte gers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3)} print(my_set) You can also use set() function to create sets. Sets are muta ble. You can add, remove and delete elements of a set. However, you cannot replace one item of a set with another as they are unordered and indexing have no meaning. Let's try commonly used set methods: add() , update() and remove() # set of integers my _set = {1, 2, 3} my_set.add(4) print(my_set) # Output: {1, 2, 3, 4} my_set.add(2) print(my_set) # Output: {1, 2, 3, 4} my_set.update([3, 4, 5]) print(my_set) # Output: {1, 2, 3, 4, 5} my_set.remove(4) print(my_set) # Output: {1, 2, 3, 5} Let's tryout some commonly used set operations: Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 12 A = {1, 2, 3} B = {2, 3, 4, 5} # Equivalent to A.union(B) # Also equivalent to B.union(A) print(A | B) # Output: {1, 2, 3, 4, 5} # Equivalent to A.intersection(B) # Also equivalent to B.intersection(A) print (A & B) # Output : {2, 3} # Set Difference print (A - B) # Output: {1} # Set Symmetric Difference print(A ^ B) # Output: {1, 4, 5} More Resources: Python Sets Python Set Methods Python Frozen Set Dictionaries Dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. For example: # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed ke ys my_dict = {'name': 'John', 1: [2, 4, 3]} Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 13 You can also use dict() function to create dictionaries. To access value from a diction ary, you use key. For example: person = {'name':'Jack', 'age': 26, 'salary': 4534.2} print(person['age']) # Output: 26 Here's how you can change, add or delete dictionary elements. person = {'name':'Jack', 'age': 26} # Changing age to 36 person['age'] = 36 print(person) # Output: {'name': 'Jack', 'age': 36} # Adding salary key, value pair person['salary'] = 4342.4 print(person) # Output: {'name': 'Jack', 'age': 36, 'salary': 4342.4} # Deleting age del person['age'] print(person) # Output: {'name': 'Jack', 'salary': 4342.4} # Deleting entire dictionary del person Table of differences of list , tuple set and dictionary Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 14 Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 15 Numpy Array Vs Python List More resources: Python Dictionar y Python Dictionary Methods Python Dictionary Comprehension Python range() range () returns an immutable sequence of numbers between the given start integer to the stop integer. Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 16 print(range(1, 10)) # Output: range(1, 10) The output is an iterable and you can convert it to list, tuple, set and so on. For example: numbers = range(1, 6) print(list(numbers)) # Output: [1, 2, 3, 4, 5] print(tuple(numbers)) # Output: (1, 2, 3, 4, 5) print(set(numbers)) # Output: {1, 2, 3, 4, 5} # Output: {1: 99, 2: 99, 3: 99, 4: 99, 5: 99} print(dict.fromkeys(numbers, 99)) We have omitted optional step pa rameter for range() in above examples. When omitted, step defaults to 1. Let's try few examples with step parameter. # Equivalent to: numbers = range(1, 6) numbers1 = range(1, 6 , 1) print(list(numbers1)) # Output: [1, 2, 3, 4, 5] numbers2 = range(1, 6, 2 ) print(list(numbers2)) # Output: [1, 3, 5] numbers3 = range(5, 0, - 1) print(list(numbers3)) # Output: [5, 4, 3, 2, 1] Python Control Flow Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 17 if...else Statement The if...else statement is used if you want perform different action (run different code) on different condition. For example: num = - 1 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") # Output: Negative number There can be zero or more elif parts, and the else part is optional. Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 18 Mo st programming languages use {} to specify the block of code. Python uses indentation. A code block starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. Ge nerally, four whitespace is used for indentation and is preferred over tabs. Let's try another example: if False: print("I am inside the body of if.") print("I am also inside the body of if.") print("I am outside the body of if") # Output: I am outsid e the body of if. Before you move on to next section, we recommend you to check comparison operator and logical operator Also, check out Python if...else in detail. Loops Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 19 while Loop Like most programming languages, while loop is used to iterate over a bl ock of code as long as the test expression (condition) is true . Here is an example to find the sum of natural numbers: n = 100 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter print("The sum is", sum) Fundamentals of Python edition 1 Collected & Edited By Mr. Osama Ghandour 20 # Output: The sum is 5050 In Python, while loop can have optional else block that is executed if the condition in the while loop evaluates to False . However, if the loop is terminated with break statement, Python interpreter ignores the else block. To learn more, visit Python while Loop for Loop In Python, for loop is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iter ating over a sequence is called traversal. Here's an example to find the sum of all numbers stored in a list. numbers = [6, 5, 3, 8, 4, 2] sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum) # Output: The sum is 28 Notice the use of in operator in the above example. The in operator returns True if value/variable is found in the sequence. In Python, for loop can have optional else block. The else part is executed if the items in the sequence used in for loop exhaus ts. However, if the loop is terminated with break statement, Python interpreter ignores the else block. To learn more, visit Python for Loop break Statement