Python Programming Fundamentals: A Comparison with Java and Key Concepts, Summaries of Programming Languages

This pdf notes helps you to learn about python programming language it's the is the 1st unit of JNTUK EEE students

Typology: Summaries

2022/2023

Available from 03/08/2023

mr-bt
mr-bt 🇮🇳

5

(1)

2 documents

1 / 84

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
UNIT-I Introduction: Introduction to Python, Program Development Cycle, Input,
Processing, and Output, Displaying Output with the Print Function, Comments,
Variables, Reading Input from the Keyboard, Performing Calculations, Operators. Type
conversions, Expressions, More about Data Output. Data Types, and Expression: Strings
Assignment, and Comment, Numeric Data Types and Character Sets, Using functions
and Modules. Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements,
Nested Decision Structures, Comparing Strings, Logical Operators, Boolean Variables.
Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total,
Input Validation Loops, Nested Loops.
Introduction to Python:
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently whereas
the other languages use punctuations.
It has fewer syntactical constructions than other languages. It was created by Guido van
Rossum during 1985 1990.
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 Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
History 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 institute, although Guido
van Rossum still holds a vital role in directing its progress.
Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python
2.7.11 is the latest edition of Python 2.
Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and preferably
only one -- obvious way to do it." Python 3.5.1 is the latest version of Python 3.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54

Partial preview of the text

Download Python Programming Fundamentals: A Comparison with Java and Key Concepts and more Summaries Programming Languages in PDF only on Docsity!

UNIT-I Introduction: Introduction to Python, Program Development Cycle, Input, Processing, and Output, Displaying Output with the Print Function, Comments, Variables, Reading Input from the Keyboard, Performing Calculations, Operators. Type conversions, Expressions, More about Data Output. Data Types, and Expression: Strings Assignment, and Comment, Numeric Data Types and Character Sets, Using functions and Modules. Decision Structures and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision Structures, Comparing Strings, Logical Operators, Boolean Variables. Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total, Input Validation Loops, Nested Loops.

Introduction to Python:

➢ Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently whereas the other languages use punctuations. ➢ It has fewer syntactical constructions than other languages. It was created by Guido van Rossum during 1985 – 1990. ➢ 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 Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. ➢ Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects. ➢ Python is a Beginner's Language: Python is a great language for the beginner level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.

History 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 institute, although Guido van Rossum still holds a vital role in directing its progress. ➢ Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is the latest edition of Python 2. ➢ Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2. The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules so that "There should be one -- and preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of Python 3.

Python's features include-

Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows a student to pick up the language quickly. ➢ Easy-to-read: Python code is more clearly defined and visible to the eyes. ➢ Easy-to-maintain: Python's source code is fairly easy-to-maintain. ➢ A broad standard library: Python's bulk of the library is very portable and cross platform compatible on UNIX, Windows, and Macintosh. ➢ Interactive Mode: Python has support for an interactive mode, which allows interactive testing and debugging of snippets of code. ➢ Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. ➢ Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. ➢ Databases: Python provides interfaces to all major commercial databases. ➢ GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. ➢ Scalable: Python provides a better structure and support for large programs than shell scripting. Apart from the above-mentioned features, Python has a big list of good features. A few are listed below- ❖ It supports functional and structured programming methods as well as OOP. ❖ It can be used as a scripting language or can be compiled to byte-code for building large applications. ❖ It provides very high-level dynamic data types and supports dynamic type checking. ❖ It supports automatic garbage collection. ❖ It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. Differences between other Programming Language and Python Python vs Java

  • In Python there is no need for semicolon and curly braces in the program as compared to Java which will show syntax error if one forgot to add curly braces or semicolon in the program.
  • Python code requires fewer lines of code as compare to Java to write the same program. For Example, Here is a code in Java
  • Python is dynamically typed that means one has to only assign a value to a variable at runtime, Python interpreter will detect the data type on itself as compare to Java where one has to explicitly mention the data type.
  • Python supports various type of programming models such as imperative, object-oriented and procedural programming as compare to Java which is completely based on the object and class-based programming models.

Input, Processing, and Output:

➢ There are several ways to deliver the output of a program. In Python, we use the print() function to output data to the screen. ➢ Sometimes we might want to take input from the user. We can do so by using the input() function. ➢ Python takes all the input as a string input by default. To convert it to any other data type, we have to convert the input explicitly. ➢ The main objective of a programming language is to make it interactive with the user and the audience. If you notice precisely, most of the software we use in real life needs input from a user, whether a search engine or a daily used app or even mail where we first input our mail id and password. ➢ In Python, we have many inbuilt functions that help obtain data from the user and then display the data after processing some particular logic in the code.

Python Output

In Python, we can simply use the print() function to print output. For example, print('Python is powerful')

Output: Python is powerful

Here, the print() function displays the string enclosed inside the single quotation. Syntax of print() In the above code, the print() function is taking a single parameter. However, the actual syntax of the print function accepts 5 parameters print(object= separator= end= file= flush=) Here,

  • object - value(s) to be printed

Example: Print Python Variables and Literals We can also use the print() function to print Python variables. For example, number = - 10. name = "Programiz"

print literals

print( 5 )

print variables

print(number) print(name) Output 5

Programiz Example: Print Concatenated Strings We can also join two strings together inside the print() statement. For example, print('Programiz is ' + 'awesome.') Output Programiz is awesome. Here,

  • the + operator joins two strings 'Programiz is ' and 'awesome.'
  • the print() function prints the joined string Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. For example, x = 5 y = 10 print('The value of x is {} and y is {}'.format(x,y)) Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).

Python Input

While programming, we might want to take the input from the user. In Python, we can use the input() function. Syntax of input() input(prompt) Here, prompt is the string we wish to display on the screen. It is optional. Example: Python User Input

using input() to take user input

num = input('Enter a number: ') print('You Entered:', num) print('Data type of num:', type(num)) Output Enter a number: 10 You Entered: 10 Data type of num: In the above example, we have used the input() function to take input from the user and stored the user input in the num variable. It is important to note that the entered value 10 is a string, not a number. So, type(num) returns . To convert user input into a number we can use int() or float() functions as: num = int(input('Enter a number: '))

  1. create a variable

  2. print the value

    We can also use the single-line comment along with the code. name = 'Eric Cartman' # name is a string Here, code before # are executed and code after # are ignored by the interpreter. Multi-line Comment in Python Python doesn't offer a separate way to write multiline comments. However, there are other ways to get around this issue. We can use # at the beginning of each line of comment on multiple lines. For example,

    This is a long comment

    and it extends

    to multiple lines

    Here, each line is treated as a single comment, and all of them are ignored. Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are generally used for multi-line strings. But if we do not assign it to any variable or function, we can use it as a comment. The interpreter ignores the string that is not assigned to any variable or function. Let's see an example, ''' This is also a perfect example of multi-line comments ''' Here, the multiline string isn't assigned to any variable, so it is ignored by the interpreter. Even though it is not technically a multiline comment, it can be used as one. Use of Python Comment 1. Make Code Easier to Understand

If we write comments in our code, it will be easier for future reference. Also, it will be easier for other developers to understand the code.

2. Using Comments for Debugging If we get an error while running the program, we can comment the line of code that causes the error instead of removing it. For example, print('Python')

print('Error Line )

print('Django') Here, print('Error Line) was causing an error so we have changed it to a comment. Now, the program runs without any errors. Python Variables, Constants and Literals Python Variables In programming, a variable is a container (storage area) to hold data. For example, number = 10 Here, number is the variable storing the value 10. Assigning values to Variables in Python As we can see from the above example, we use the assignment operator = to assign a value to a variable.

assign value to site_name variable

site_name = 'programiz.pro'

print(b) # prints 3. print(c) # prints Hello Run Code If we want to assign the same value to multiple variables at once, we can do this as: site1 = site2 = 'programiz.com' print(site1) # prints programiz.com print(site2) # prints programiz.com Run Code Here, we have assigned the same string value 'programiz.com' to both the variables site1 and site2. Rules for Naming Python Variables

  • 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
  • Create a name that makes sense. For example, vowel makes more sense than v.
  • If you want to create a variable name having two words, use underscore to separate them. For example: my_name current_salary
  • Python is case-sensitive. So num and Num are different variables. For example, var num = 5 var Num = 55 print(num) # 5 print(Num) # 55
  • Avoid using keywords like if, True, class, etc. as variable names. Python Constants A constant is a special type of variable whose value cannot be changed. In Python, constants are usually declared and assigned in a module (a new file containing variables, functions, etc which is imported to the main file). Let's see how we declare constants in separate file and use it in the main file, Create a constant.py :

    declare constants

    PI = 3. GRAVITY = 9. Create a main.py :

    import constant file we created above

    import constant print(constant.PI) # prints 3. print(constant.GRAVITY) # prints 9. In the above example, we created the constant.py module file. Then, we assigned the constant value to PI and GRAVITY. After that, we create the main.py file and import the constant module. Finally, we printed the constant value. Note : In reality, we don't use constants in Python. Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment.
  • The function input() returns a string. This can be stored in a variable (name)

  • The variable is then shown to the screen using the print() function.

  • By using formatted strings (the f in front), you can mix variables with text You can now give keyboard input, it will be stored in the variable name. Return type Any value you enter to input() is stored as a string str. You can confirm this by calling type() See the example below in the Python shell: >>> name = input("Enter name: ") Enter name: Alice >>> city = input("Enter city: ") Enter city: Wellington >>> type(name)

    >>> type(city) >>>

    Numbers do not have the type str. So they need to be explicitly converted to a numeric type like int or float. You can check the type of numeric variables too: >>> x = 3 >>> y = 2. >>> type(x)

    >>> type(y) >>>

How to get an Integer as the User Input? If you call the input() function, it returns plain text (string). So if you want to use integers , you have to convert the string to an int. To get an integer (whole number), you can do this:

get text input

inputText = input("What is x?")

convert text to number

x = int(inputText) Get integer user input on a single line: x = int(input("What is x? ")) You can get multiple variables from the user, and use them in your program. The program below gets variable x and variable y, and then sums and outputs them. x = int(input("Enter x: ")) y = int(input("Enter y: ")) sum = x + y print(f"Addition of {x} and {y} is {sum}") Take into account that if the user doesn’t actually enter an integer, this code will throw an exception. >>> x = int(input("What is x? ")) What is x? a Traceback (most recent call last): File "", line 1 , in

Input Exception Handling If the user enters invalid input or invalid input, Python can throw an exception. To handle this, you can use the code below: x = 0 try: x = int(input("What is x? ")) except: print("Invalid number.") Types of Python Operators Python language supports the following types of operators.

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators Let us have a quick look on all these operators one by one. Python Arithmetic Operators Python arithmetic operators are used to perform mathematical operations on numerical values. These operations are Addition, Subtraction, Multiplication, Division, Modulus, Expoents and Floor Division.

Operator Name Example

  • Addition 10 + 20 = 30
  • Subtraction 20 – 10 = 10
  • Multiplication 10 * 20 = 200 / Division 20 / 10 = 2 % Modulus 22 % 10 = 2 ** Exponent 4**2 = 16 // Floor Division 9//2 = 4 Example Following is an example which shows all the above operations: a = 21 b = 10

Addition

print ("a + b : ", a + b)

Subtraction

print ("a - b : ", a - b)

Multiplication

print ("a * b : ", a * b)

Division

print ("a / b : ", a / b)

Modulus

print ("a % b : ", a % b)