








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









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
Software), which means you can freely distribute copies of this software, read its source code and modify it.
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:
a = [ [1, 2, 3], [3, 4, 5], [5, 6, 7] ] print(a) Output: [[1, 2, 3], [3, 4, 5], [5, 6, 7]]
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
x = 1 + 2 \
####### This example will print Hello World print('Hello World') # This is a comment
""" 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.
""" 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:
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='&')
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
print("a =", a) b = a
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
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.
t1 = ( 1 , 2 , 3 , 4 , 5 )
print(t1)
t2 = ("hi", "hello", "bye")
for s in t2: print (s)
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.
lis1 = [ 1 , 2 , 3 , 4 , 5 ]
print(lis1)
lis2 = ["Apple", "Orange", "Banana"]
for x in lis2: print (x)
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.
dict = { 1 :"Chaitanya","lastname":"Singh", "age": 31 }
print(dict[ 1 ])
print(dict["lastname"])
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.
myset = {"hi", 2 , "bye", "Hello World"}
for a in myset: print(a)
print( 2 in myset)
myset.add( 99 ) print(myset) Output: Hello World 2 hi bye True {‘Hello World’, 2, 99, ‘hi’, ‘bye’}