0% found this document useful (0 votes)
4 views20 pages

python

The document provides an overview of the basics of Python programming, covering topics such as variables, data types, operators, and syntax. It highlights Python's features, including its interpreted nature, object-oriented programming support, and ease of learning, as well as its applications in various fields like web development and data science. Additionally, it includes instructions for installing Python and executing code from the command line.

Uploaded by

kaviyamanjari18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

python

The document provides an overview of the basics of Python programming, covering topics such as variables, data types, operators, and syntax. It highlights Python's features, including its interpreted nature, object-oriented programming support, and ease of learning, as well as its applications in various fields like web development and data science. Additionally, it includes instructions for installing Python and executing code from the command line.

Uploaded by

kaviyamanjari18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
Unit: BASICS OF PYTHON 10 hours BASICS : Python = Variables — Executing Python from the Command Line — Editing Python Files = Python Reserved Words - Basic Syntax-Comments — Standard Data Types — Relational Operators - Logical Operators — Bit Wise Operators — Simple Input and Output. About Python: Python is a powerful general- Purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossumduring 1985-1990. It is used in web development, data science, creating software prototypes, and so on. Features of python! Co Qe Language |= 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. J+ 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 pracessing to WWW browsers to games. Features Of Python é@ Portal © Preece ovee @ Interpreted © Classes @ werrratcrin @ Ederabe @ Object Oriented @ Embedded Easy-to-learn — Python has few keywords, simple structure, and a clearly defined syntax. This allows the 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. Abroad 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 Apart from the above- mentioned features, Python has a big list of good features, 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, CH, COM, pesenomee viii ea ActiveX, CORBA, and Java. GUI Programming - Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems. Scalable - Python provides a better structure and support for large programs than shell scripting. Applications of Pythor WEB APPLICATIONS® © canes © wen DEVELOPMENT WEB CRAWLER DATASCIENCE® (@ WEB FRAMEWORKS © MACHINE LEARNING ausittess @ COMPUTER VISION @ APPLICATIONS @ opcraTING SYSTEMS © CRYPTOGRAPHY UneuARcat ARTIFICIAL @ DEVELOPMENT renee © GUE BASED DESKTOP ‘@ DATA STRUCTURES APPLICATIONS PROTOTYPING @ Ne aad ss tas Peeters (2) Febru vat Reeder atin eS Re Oiateartincuts Business Applications ¢ _ m=) Software Development Cee UC ED et Tanta 2 ee Tee thon Tools and The following lists important tools and frameworks to develop different types of Python applications: Web Development: Django, Pyramid, Bottle, Tornado, Flask, web2py GUI Development: tkinter, PyObject, PyQt, PySide, Kivy, wxPython Scientific and Numeric: SciPy, Pandas, IPython Software Development: Buildbot, Trac, Roundup System Administration: Ansible, Salt, OpenStack TUTE ECON 5 oO Improved Productivity &) Interpreted Language ey Weak in Mobile = Dynamically Typed 7 ‘Computing & Free and Open Source © Vast Libraries Support Benefits of Python : demic Scientific bee ae ee —$_— nats lortion and Machine Learring ae ~~ Predictive Analytics Data Science _—— Yee’ Advanced Analytics Statistis — —— Python Versions: Version Release Date Python 0.9.0 February 1991 Python 1.0 January 1994 Python 2.0 October 2000 Python 2.7.0- EOL-Jan 2020 July 2010 Python 3 December 2008 Python 3.6 December 2016 Python 3.6.5 March 2018 Python 3.7.0 May 2018 Python 3.8 October 2019 Python 3.9 - Current Version October 2020 Python setup: Getting Python The most up-to-date and current source code, binaries, documentation, news, etc., Is available on the official website of Python https://www.python.org/ You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats. Installing Python Python distribution Is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Python on various platforms, Windows Installation Here are the steps to install Python on Windows machine. + Open a Web browser and go to httas://www.python.org/downloads/. «Follow the link for the Windows installer python-X¥Z.msifile where XYZ is the version you need to install. + To use this installer python-X¥Z.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. «Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Install Python 38.4 (32-bit) Variables are containers for storing data values. ‘Creating Variables > Python has no command for declaring a variable. > Avariable is created the moment you first assign a value to it. Example =5 yooh pend Variables do not need to be declared with print(y) any particular type, and can even change type after they have been set. Example, xis of type int x= "Sally" # xis now of type strprint(x) Casting If you want to specify the data type of a variable, this can be done with casting. Example xestr(3)_ #xwill bes" y=int(3) # ywill be 3 z=float(3) #2 will be 3.0 x=5 y= "John" print{type(x)) print{type(y)) we can get the data type of a variable with the type() function, Single or Double Quotes? String variables can be declared either by using single or double quotes: Example x= "John" itis the same as x= ohn! Variable Names: Variable names are case-sensitive. Example This will create two variables: a=4 A= "sally" #Awill not overwrite a ‘variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: + Avariable name must start witha letter or the underscore character + Avariable name cannot start with a number + Avariable name can only contain alpha- numeric characters and underscores (A-z, 0-9, and _) Example: Legal variable names: myvar = "John" my_var= "John" _my_var = "John" myVar= "John" legal variable my var + Variable names are case-sensitive (age, Ae MYVAR= "John" and AGE are three different variables) myvar2 = "John" Many Values to Multiple Variables Python allows you to assign values to multiple Variables in one line: Example % y,2= "Orange print(x) print(y) print(2) "Banana", "Cherry" Unpack a Collection One Value to Multiple Variables ‘And you can assign the same value to multiple variables in one line: Example print(x) print(y) print(z) 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"] xy, Z= fruits print(x) print(y) print(2) Output: Apple Banana Cherry Output Variables The Python print() function is often used to output variables. Example x= "Python is awesome” print(x) In the print() function, you output multiple variables, separated by a comma: Example x= "Python" "awesome" print(x, y, 2) You can also use the + operator to output multiple variables: Example x= "Python" is" z= "awesome" print(x + y +2) Notice the space character after "Python" ands", without them the result would be “Pythonisawesome* For numbers, the + character works as a mathematical operator: Example xe y=10 print(x + y) In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error: Example xe y= "John" print(x + y) ‘The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types: Example xes y= "John" print(x, y) Global Variables Variables that are created outside ofa function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside. Examplo Create a variable outside of a function, and use it inside the function x= "awesome" def myfunc(): print("Python is " + x) myfune() Ifyou 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(): print("Python is * + x) myfune() print("Python Is" +x) The global Keyword Normally, when you create a variable in used inside that function. To create a global variable inside a function, you can use the global keyword. lea function, that variable is local, and can only be Example Ifyou use the global keyword, the variable belongs to the global scope: def myfune(): global x x= "fantastic" myfunc() print("Python is " +x) Also, use the global keyword if you want to change a global variable inside a function. Example To change the value of a global variable inside a function, refer to the variable by using the global keyword: = Using of local = Using of global variable i ‘ploba” key word is used fo declare global def myfune(): variables erasie global x x= "fantastic" ‘rename’: fune_olobal py fune(): xis 50 myfune() ee Changed x92 Volue of xis 2 print iets x2 Print Changed x 10°. x print("Python is" + x) Brint‘Changed local nt’ x x=80 x=50 func(s) Ves fune() rint'x is stir Change cal 2 Print "Value of x ist. es Executing Python from the Command Line Python provides us the feature to execute the Python statement one by one at the interactive prompt. It is preferable in the case where we are concerned about the output of each line of our Python program. To open the interactive mode, open the terminal (or command prompt) and type python It will open the following prompt where we can execute the Python statement and check their impact on the console, LB python 383 Shan = 5x ‘Fle 64 Shell Debug Options Window Help Python 3.8.3 (tags/e3. Eel) 1 on wins? Type "help", "copyright", "credits" or “License ()" for more information. 20:18) (MSC v.1825 32 Bat (in 4 After writing the print statement, press the Enter key. LB Python 283 Shel - ao x Fie Edt Shell Debug Options Window Help Pyshon 3.8.3 (tags/v3.8.3:€f2c832, May 13 2020, 22120718) (NEC v.1826 32 bie (in * rel) on wins? Type "help", “copysighs", “eredice” or "License()" for nore information. >>> prine (tiello World") Helio Worle >>| Here, we get the message “Hello World Printed on the console. Editing Python Files Getting into Python: Start->alll Programs~>Python 3. Click File-->New type your python code save your file through File—>Save or Ctri#S Run your program by pressing FS Getting back to IDLE by pressing Ctrl+D Tout Celene Mowat Rat 1 ley Citar ttc Pagans hon phn py ie fat Fast Bun pom ndon Hep Se! perscal_detatla i: : /Users/adnin/AppData/Local/Programs/Fychon/Python310/pgl.py ===" Address:Bengalore, Karnataka, India rcbile_no:$000000001 College Mane:Nandha Arts and Science College Course Subjects : Molecular Geneties, Huan Fatholegy >>> ( po2.py -C/Usere/sdmin/AppData/Local/Programs/Pythor/Python30/pg2 py (2.10.1) File fit Format Run Options Window Help Get aadiP, Qt return B+ Q der suberace (P,Q)? return B= @ det multiply (P, @): return P*Q Ger aivadere, ot return P/Q (rriease (ta. Raa") (tb. Suberace™) (re. Mulsspiy") (ra. pavader) the cperation.*) choice = anput("Flease enter choice (a/ B/ ¢/ 4): ums ant (input (*Please ence: ene first nantes PUR? © int (Anpur ("Please enter the second munbes ” ™» Ae choice == nt (mum, "4%, mun ?, "=", add(nom i, mum 2)) <1if choice Se tbt: eint (num, " - *, num : sitt choice == "ctr Print (num, "+", nud, "=", mulesply(numl, mun2)) elit choice == ‘a'r Prine (num, */%, num?, "=", divide(nomt, mum 2)) etse: Print ("This i an anvalid anputm) =") suberace (oum_1, num_2)) wane RESTART: C1 /Usere/adnin/Appbata/Local/Prograns/Python/ Python310/pg2-bY ===" Please select the operation. a. Add b. surtract cc. Multiply a, Divide Please enter choice (a/ b/ c/ a): @ Please enter the first number 200 Please encer the second number: § 209 / 5 = 40.0 D “paPpy -C/sersladmin’ AppData/LecalPrograms/Pythor/Pythen310/pq3hpy(3.1010" - o x fle ft Format fun Options Window Help print(tiargest of TEREE numbers") Prine ( yn") ae ancGapuc (‘Enter fairer number + 4}) b= ant (anpas('Enter second number =") = ant(inpac('Enter chird number: *)) largest = 0 sf a> bend ‘aargest = 2 eurpoe largest = B suet aargest = ¢ print (*\a\asing TE. peane(r Princ Q@argest, "is the largest of three numbers.") ise") bias: print ( Jargest = (a sf (2 > Bons a> cp ese ( if tb >) else od) print (largest, cis the Largest of three nunbers.*) > (OLE shen 3.101 - oOo x Fie Et She Debug Options Window Help [reste 3.20.1 (tage/¥3.20., aepe4)) on win32 [Ture help", "eopyeaght™, Sereateat or tiicense()* for ore information. cazeta, Dec € 2021, 1810037) [HSC v.i829 €4 Bae ~ ——- pestant: C:/Users/adnin/Rppbata/Local/Prograns/eycnon/Pychon310/pg3.Py === Largeet of THREE nonners Enter first nusker : 78 Enter second summer $23 Enter third muxker 1 $87 useng conaiticnal OFerator aa che largest of encee curpers, Python Keywords Python keywords are special reserved | “gatse words that have specific meanings and purposes and can’t be used for| None anything but those specific purposes. These keywords are always avallable—you'll never have to import | and them into your code. = Python keywords are different from | “* Python's built-in functions and types. | assert The built-in functions and types are also always available, but they aren't | S¥8° as restrictive as the keywords in their usage. Tre An example of something you can’t do with Python keywords is assign something to them. If you try, then you'll get a SyntaxError. You won't get a SyntaxError If you try to assign something to a built-in function or type, but it still isn’t a good idea, For a more in-depth explanation of ways keywords can be misused, check out Invalid Syntax in Python: Common Reasons for SyntaxError. As ‘of Python 3.8, there are thirty-five keywords in Python. All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below Python Data Types: Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different thingsPython has the following data types built-in by default, in these categories: Text Type at 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 NoneType —_: NoneType Setting the Data Type In Python, the data type is set when you assign a value to a variable: Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 13 complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range (6) range x = {"name" : "John", “age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", frozenset "cherry"}) x = True boo! x = bytearray (5) bytearray x = None NoneTvoe x = biello” bytes x = memoryview (bytes (5)) memoryview Comments Python Comments can be used to > explain Python code. > make the code more readable. > prevent execution when testing code. In Python, there are two types of comments 1. Single-line Comments 2. Multi-li om Single-line Comments In Python, single-line comments are used for commenting out single lines of code. These comments start with a # symbol. The symbol is then followed by the text explaining the line of code. You can write these comments beside a line of code or above it. Example 1: it can also be used to prevent Python This is a comment from executing code: print("Hello, Korld!") Example 3: Example 2: tprint(*Hello, World! print("Hello, World!") #This is a print("cheers, Mate!") comment Multi Line Comments Multiline comments can be declared using two ways. You can specify these comments using "" (Triple single quotes) or """ (Triple double quotes). The quotes are mentioned at the beginning and at the end of the comments. This is a comment e furdtten in This is a comment ‘more than just one line written in print("Hello, World|") more than just one lil print("Hello, World!”) 7 Single line comment print (*Hello stechies') glo. Python program to explain b multiple line comment print (‘Hello*) Multi-line Comments Python program to explain multiple Line conment print (‘Hello") print (‘Hello Stechies') Python Operators Python Operators so Arithmetic | Comparison | Logical Assignment Bitwise Identity Membership Relational Operators: Comparison operators are used to compare two values. If returns the result as True or False! Suppose we have two variables a and b. If both values of both variables are equal to each other then it returns the result as True and if the values of both differ from each other then it returns False Operator Name Example = Double Equal Not Equal > Greater than < Less than Greater than or equal to <= Less than or equal to Logical Operators: Logical operators in Python are used in combining conditional statements. It also returns True or False based on conditions. It works on the principle of Logic of available logical operators in the below table. gates i.e. and, or, not. Find the x>3 «ee yeee3 yey<<3 Returns True if sequence with the xnot in y specified value is not present in the object Returns True if both variables are the same xis object isnot Returns True if both variables are not the xis not same object y Simple Input and Output How to Take Input from User in Python Sometimes a developer might want to take user input at some point in the program. To do this Python provides an input() function. Syntax: input('prompt') where prompt is an optional string that is displayed on the string at the time of taking input. Example 1: Python get user input with a message # Taking input from the user put("Enter your name: ") name = Output: Enter your name: #Output Hello, GFG print( Hello," + name) print(type(name)) Note: 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. For example, to convert the input to int or float we have to use the int() and float() method respectively. Example 2: Integer input in Python # Taking input from the user as integer num = int{input("Enter a number: “)) add=num+1 ‘Output: Enter a number: 25 # Output print(add) Display Output in Python : Python provides the print() function to display output to the standard output devices. ‘Syntax: print(value(s), sep= “4 end =n’, filesfile, flush=flush) Parameters: value(s) : Any value, and as many as you like. Will be converted to string before printed sep='separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default -"* end’: (Optional) Specify what to print at the end. Default : “\n" file : (Optional) An object with a write method. Default :sys.stdout flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False Returns: It returns output to the screen. Example: Python Print Output hon program to demonstrate # print() method utp: print(*GFG") ors #1 code for disabling the softspace feature SFG print('G', F,'G') In the above example, we can see that in the case of the 2nd print statement there is a space between every letter and the print statement always add a new line character at the end of the string, This is because after every character the sep parameter is printed and at the end of the string the end parameter is printed. Let's try to change this sep and end parameter. Example: Python Print output with custom sep and end parameter 4# Python program to demonstrate # print() method Output print("GFG", end ="@") GFG@GHFAG # code for disabling the softspace feature print('G',F,'G', sep="#") Formatting Output Formatting output in Python can be done in many ways. Let’s discuss them below Using formatted string literals We can use formatted string literals, by starting a string with f or F before opening quotation marks or triple quotation marks. in this string, we can write Python expressions between {and } that can refer to a variable or any literal value. Example: Python String formatting using F string # Declaring a variable Outp name = "Gfg" # Output Hello Gfg! How are you? (f Hello {name}! How are you?") Using format() We can also use format{) function to format our output to make it look presentable. The curly braces { } work as placeholders. We can specify the order in which variables occur in the —S— print('{0) {1} cost ${2}'.format(6, 'bananas', 1.74)) wf THO template Positional_arguments format() method 6 bananas cost $1.74 Example: Python string formatting using format() funetion # Initializing variables a=20 b=10 #addition sum=a+b # subtraction sub =a-b # Output print(’The value of a is {} and bis {}’format(a,b)) print('{2} is the sum of {0} and {1)'.format(a,b,sum)) print('{sub_value} is the subtraction of {value_a} and {value_b}\.format(value_a=a, value_b = b, sub_value = sub) Output: The value of ais 20 and bis 10 30 is the sum of 20 and 10 10 is the subtraction of 20 and 10

You might also like