Docsity

Python study material, Lecture notes of C programming

Toggle sidebar
bg1
Python Programming
Introduction
Python is a widely used general-purpose, high level programming language. It was created by Guido van
Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an
emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines
of code.
Interesting fact: Python is named after the comedy television show Monty Python’s Flying Circus. It is not
named after the Python snake.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
Python is an open-source (free) programming language that is used in web programming, data science,
artificial intelligence, and many scientific applications. Learning Python allows the programmer to focus on
solving problems, rather than focusing on syntax. Its relative size and simplified syntax give it an edge over
languages like Java and C++, yet the abundance of libraries gives it the power needed to accomplish great
things.
Features of Python programming language
1. Readable: Python is a very readable language.
2. Easy to Learn: Learning python is easy as this is a expressive and high level programming language,
which means it is easy to understand the language and thus easy to learn.
3. Cross platform: Python is available and can run on various operating systems such as Mac, Windows,
Linux, Unix etc. This makes it a cross platform and portable language.
4. Open Source: Python is a open source programming language.
5. Large standard library: Python comes with a large standard library that has some handy codes and
functions which we can use while writing code in Python.
6. Free: Python is free to download and use. This means you can download it for free and use it in your
application. See: Open Source Python License. Python is an example of a FLOSS (Free/Libre Open Source
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Python study material and more Lecture notes C programming in PDF only on Docsity!

Python Programming Introduction Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code. Interesting fact : Python is named after the comedy television show Monty Python’s Flying Circus. It is not named after the Python snake. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions: Python 2 and Python 3. Both are quite different. Python is an open-source (free) programming language that is used in web programming, data science, artificial intelligence, and many scientific applications. Learning Python allows the programmer to focus on solving problems, rather than focusing on syntax. Its relative size and simplified syntax give it an edge over languages like Java and C++, yet the abundance of libraries gives it the power needed to accomplish great things. Features of Python programming language

  1. Readable: Python is a very readable language.
  2. Easy to Learn: Learning python is easy as this is a expressive and high level programming language, which means it is easy to understand the language and thus easy to learn.
  3. Cross platform: Python is available and can run on various operating systems such as Mac, Windows, Linux, Unix etc. This makes it a cross platform and portable language.
  4. Open Source: Python is a open source programming language.
  5. Large standard library: Python comes with a large standard library that has some handy codes and functions which we can use while writing code in Python.
  6. Free: Python is free to download and use. This means you can download it for free and use it in your application. See: Open Source Python License. Python is an example of a FLOSS (Free/Libre Open Source

Software), which means you can freely distribute copies of this software, read its source code and modify it.

  1. Supports exception handling: If you are new, you may wonder what is an exception? An exception is an event that can occur during program exception and can disrupt the normal flow of program. Python supports exception handling which means we can write less error prone code and can test various scenarios that can cause an exception later on.
  2. Advanced features: Supports generators and list comprehensions. We will cover these features later.
  3. Automatic memory management: Python supports automatic memory management which means the memory is cleared and freed automatically. You do not have to bother clearing the memory. Applications of Python There are so many applications of Python, here are some of the them. 1. Web development – Web framework like Django and Flask are based on Python. They help you write server side code which helps you manage database, write backend programming logic, mapping urls etc. 2. Machine learning – There are many machine learning applications written in Python. Machine learning is a way to write a logic so that a machine can learn and solve a particular problem on its own. For example, products recommendation in websites like Amazon, Flipkart, eBay etc. is a machine learning algorithm that recognises user’s interest. Face recognition and Voice recognition in your phone is another example of machine learning. 3. Data Analysis – Data analysis and data visualisation in form of charts can also be developed using Python. 4. Scripting – Scripting is writing small programs to automate simple tasks such as sending automated response emails etc. Such type of applications can also be written in Python programming language. 5. Game development – You can develop games using Python. 6. You can develop Embedded applications in Python. 7. Desktop applications – You can develop desktop application in Python using library like TKinter or QT. Program Structure: In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are some statements that can alter this behavior like conditional statements. Python statements are written in such a format that one statement is only written in a single line. The interpreter considers the ‘new line character’ as the terminator of one instruction. But, writing multiple statements per line is also possible that you can find below. Examples:

Example 1

print('Welcome to Geeks for Geeks') Output: Welcome to Geeks for Geeks

braces (‘{‘) is presumed to be incomplete until all matching parentheses, square brackets, and curly braces have been encountered. Until then, the statement can be implicitly cont inued across lines without raising an error. Examples:

Example 1 : The following code is valid

a = [ [1, 2, 3], [3, 4, 5], [5, 6, 7] ] print(a) Output: [[1, 2, 3], [3, 4, 5], [5, 6, 7]]

Example 2 : The following code is also valid

person_1 = 18 person_2 = 20 person_3 = 12 if ( person_1 >= 18 and person_2 >= 18 and person_3 < 18 ): print('2 Persons should have ID Cards') Output: 2 Persons should have ID Cards  Explicit Line Continuation - Explicit Line joining is used mostly when implicit line joining is not applicable. In this method, you have to use a character that helps the interpreter to understand that the particular statement is spanning more than one lines. Backslash () is used to indicate that a statement spans more than one line. The point is to be noted that” must be the last character in that line, even white-space is not allowed. See the following example for clarification

Example

x = 1 + 2 \

  • 5 + 6 \
  • 10 print(x) Output: 24 Comments in Python Writing comments in the code are very important and they help in code readability and also tell more about the code. It helps you to write details against a statement or a chunk of code. Interpreter ignores the comments and does not count them in commands. In this section, we’ll learn how to write comments in Python. Symbols used for writing comments include Hash (#) or Triple Double Quotation marks(“””). Hash is used in writing single line comments that do not span multiple lines. Triple Quotation Marks are used to write multiple line comments. Three triple quotation marks to start the comment and again three quotation marks to end the comment. Consider the following examples:

Example 1

####### This example will print Hello World print('Hello World') # This is a comment

Example 2

""" This example will demonstrate multiple comments """ """ The following a variable contains the string 'How old are you?' """ a = 'How old are you?' """ The following statement prints what's inside the variable a """ print(a) Note Do note that Hash (#) inside a string does not make it a comment. Consider the following example for demonstration.

Example

""" The following statement prints the string stored in the variable """ a = 'This is # not a comment #' print(a) # Prints the string stored in a White spaces The most common whitespace characters are the following: Character ASCII Code Literal Expression Space 32 (0x20) ‘ ‘ tab 9 (0x9) ‘\t’ newline 10 (0xA) ‘\n’ Whitespace is mostly ignored, and mostly not required, by the Python interpreter. When it is clear where one token ends and the next one starts, whitespace can be omitted. This is usually the case when special non-alphanumeric characters are involved. Examples:

Example 1

This is correct but whitespace can improve readability

a = 1-2 # Better way is a = 1 - 2 print(a)

Lines 1, 3, 5 are on same level Line 2 will only be executed if if condition becomes true. Line 4 will only be executed if if condition becomes false. """ Output: x > 5 x > 5 x > 5 x < 5 x < 5 The above program should be written as follows using the indentation x = 10 while(x != 0): if(x > 5): # Line 1 print('x > 5') # Line 2 else: # Line 3 print('x < 5') # Line 4 x - = 2 # Line 5 OUTPUT: x > 5 x > 5 x > 5 x < 5 x < 5 OUTPUT Function: Python provides numerous built-in functions that are readily available to us at the Python prompt. Some of the functions like input() and print() are widely used for standard input and output operations respectively. Python Output Using print() function We use the print() function to output data to the standard output device (screen). We can also output data to a file. The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen. Syntax print (object(s) , sep= separator , end= end , file= file , flush= flush ) Here, objects is the value(s) to be printed. The sep separator is used between the values. It defaults into a space character. After all values are printed, end is printed. It defaults into a new line. The file is the object where the values are printed and its default value is sys.stdout (screen). Here is an example to illustrate this. print(1, 2, 3, 4) print(1, 2, 3, 4, sep='*') print(1, 2, 3, 4, sep='#', end='&')

OUTPUT

Example print("Hello", "how are you?") OUTPUT Hello", "how are you? Example x = ("apple", "banana", "cherry") print(x) OUTPUT apple, banana, cherry Example Print two messages, and specify the separator: print("Hello", "how are you?", sep="---") OUTPUT Hello --- how are you? Example a = 5 print('The value of a is', a) OUTPUT The value of a is 5 #EXAMPLE print("Python is fun.") a = 5

Two objects are passed

print("a =", a) b = a

Three objects are passed

print('a =', a, '= b') OUTPUT Python is fun. a = 5 a = 5 = b In the above program, only objects parameter is passed to print () function (in all three print statements). Hence,  ' ' separator is used. Notice, the space between two objects in the output.  end parameter '\n' (newline character) is used. Notice, each print statement displays the output in the new line.  file is sys.stdout. The output is printed on the screen.  flush is False. The stream is not forcibly flushed.

This produces the following result − 100

John Multiple Assignment Python allows you to assign a single value to several variables simultaneously. For example − a = b = c = 1 Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example − a,b,c = 1,2,"john" Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c. Constants A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later. Assigning value to constant in Python In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words. Example : Declaring and assigning value to a constant PI = 3. GRAVITY = 9. Rules and Naming Convention for Variables and constants

  1. Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase ( A to Z ) or digits ( 0 to 9 ) or an underscore ( _ ). For example: snake_case MACRO_CASE camelCase CapWords
  2. Create a name that makes sense. For example, vowel makes more sense than v.
  3. If you want to create a variable name having two words, use underscore to separate them. For example: my_name current_salary
  4. Use capital letters possible to declare a constant. For example: PI G MASS SPEED_OF_LIGHT

TEMP

  1. Never use special symbols like !, @, #, $, %, etc.
  2. Don't start a variable name with a digit. Data Types A data type defines the type of data, for example 123 is an integer data while “hello” is a String type of data. The data types in Python are divided in two categories:
    1. Immutable data types – Values cannot be changed.
    2. Mutable data types – Values can be changed Immutable data types in Python are:
    3. Numbers
    4. String
    5. Tuple Mutable data types in Python are:
    6. List
    7. Dictionaries
    8. Sets 1. Numeric Data Type in Python Integer – In Python 3, there is no upper bound on the integer number which means we can have the value as large as our system memory allows.

    Integer number

    num = 100 print(num) print("Data Type of variable num is", type(num)) Output: 100 Data Type of variable num is Long – Long data type is deprecated in Python 3 because there is no need for it, since the integer has no upper limit, there is no point in having a data type that allows larger upper limit than integers. Float – Values with decimal points are the float values, there is no need to specify the data type in Python. It is automatically inferred based on the value we are assigning to a variable. For example here fnum is a float data type.

    float number

    fnum = 34. print(fnum) print("Data Type of variable fnum is", type(fnum)) Output: 34. Data Type of variable fnum is Complex Number – Numbers with real and imaginary parts are known as complex numbers. Unlike other programming language such as Java, Python is able to identify these complex numbers with the values. In the following example when we print the type of the variable cnum, it prints as complex number.

    complex number

Tuple is immutable data type in Python which means it cannot be changed. It is an ordered collection of elements enclosed in round brackets and separated by commas.

tuple of integers

t1 = ( 1 , 2 , 3 , 4 , 5 )

prints entire tuple

print(t1)

tuple of strings

t2 = ("hi", "hello", "bye")

loop through tuple elements

for s in t2: print (s)

tuple of mixed type elements

t3 = ( 2 , "Lucy", 45 , "Steve") ''' Print a specific element indexes start with zero ''' print(t3[ 2 ]) Output: (1, 2, 3, 4, 5) Hi Hello Bye 45

4. Python Data Type – List List is similar to tuple, it is also an ordered collection of elements, however list is a mutable data type which means it can be changed unlike tuple which is an immutable data type. A list is enclosed with square brackets and elements are separated by commas.

list of integers

lis1 = [ 1 , 2 , 3 , 4 , 5 ]

prints entire list

print(lis1)

list of strings

lis2 = ["Apple", "Orange", "Banana"]

loop through list elements

for x in lis2: print (x)

List of mixed type elements

lis3 = [ 20 , "Chaitanya", 15 , "BeginnersBook"] ''' Print a specific element in list indexes start with zero ''' print("Element at index 3 is:",lis3[ 3 ]) Output:

Apple Orange Banana Element at index 3 is: BeginnersBook

5. Python Data Type – Dictionary Dictionary is a collection of key and value pairs. A dictionary doesn’t allow duplicate keys but the values can be duplicate. It is an ordered, indexed and mutable collection of elements. The keys in a dictionary doesn’t necessarily to be a single data type, as you can see in the following example that we have 1 integer key and two string keys.

Dictionary example

dict = { 1 :"Chaitanya","lastname":"Singh", "age": 31 }

prints the value where key value is 1

print(dict[ 1 ])

prints the value where key value is "lastname"

print(dict["lastname"])

prints the value where key value is "age"

print(dict["age"]) Output: Chaitanya Singh 31 6. Python Data Type – Set A set is an unordered and unindexed collection of items. This means when we print the elements of a set they will appear in the random order and we cannot access the elements of set based on indexes because it is unindexed. Elements of set are separated by commas and enclosed in curly braces. Lets take an example to understand the sets in Python.

Set Example

myset = {"hi", 2 , "bye", "Hello World"}

loop through set

for a in myset: print(a)

checking whether 2 exists in myset

print( 2 in myset)

adding new element

myset.add( 99 ) print(myset) Output: Hello World 2 hi bye True {‘Hello World’, 2, 99, ‘hi’, ‘bye’}