[go: up one dir, main page]

0% found this document useful (0 votes)
124 views8 pages

1 PDF

Uploaded by

abcdef b
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)
124 views8 pages

1 PDF

Uploaded by

abcdef b
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/ 8
ee pie ; 1.2. TOKENS IN pyTHON ' The smallest individual unitin ora exical unit. . a5 following tOKeNS = (i) Wentifiers (Names) .s known as a Tokert program is knowr ryan (ii) Literals Keywords x (@) Punctuators # A sample Python program for a1_in range(1,_¢1@) 4 if a%2 Keio eras cgi oporators identitors Figure 1.1. Some tokens in a Python program. Let us revise our understanding of tokens. 1.2.1 Keywords Keywords are predefined words with special meaning to the language compiler or interpreter. These are reserved for special purpose and must not be used as normal identifier names. Python programming language contains the following keywords : False assert del for in or None break elif from is pass True class else _~—global_-—‘lambda raise and continue except if nonlocal return as def finally import not try 1.2.2 Identifiers (Names) COMPUTER SCIENCE WITH PYTHON _ bat! The smallest individual unit iq program is known a 3 Token», 2 lexical unit. punetuators A keyword is a word having! special meaning reserved by programming language. while with yield Identifiers are the names given to different parts of the program viz, variables, objects, classes, functions, lists, dictionaries and so forth, ‘The naming rules for Python identifiers can be summarized as follows : © Variable names must only be a non-keyword word with no spaces in between. ‘© Variable names must be made up of onl numbers, and underscore (_). ein ee Variable names cannot begin with a number, they can contain numbers. although Scanned with CamScanner - Chopter 1 : PYTHON REVISION TOUR The following are some followi The following are some invalid identifiers : valid identifiers : yfsiie-_areg 9.94 DATA-REC contin speci characte - hyphen) NYFILE —_ps ae (other than A~Z, a2 and _ (underscore) ) “cHk FILE13 Starting with a digit 727029 _H)I3_IK aes reserved keyword My. file contains special character dot (. ) 1.2.3 Literals/Values Literals are data items that have a fixed/constant value. Python allows several kinds of literals, which are being given below. (i) String Literals A string literal is a sequence of characters surrounded by quotes (single or double or triple quotes). String literals can either be single line strings or multi-line strings. © Single line strings must terminate in one line ie,, the closing quotes should be on the same line as that of the opening quotes. (See below) ‘© Multiline strings are strings spread across multiple lines. With single and double quotes, each line other that the concluding line has an end character as \ (backslash) but with triple quotes, no backslash is needed at the end of intermediate lines. (see below) : oe Text = "Helo Word ig >>> Text2 = "Hello\ world“ Mtitine sing Text3="''Hello«—_____ [No backslash needed World''* In strings, you can include non-graphic characters through escape sequences. Escape sequences are given in following table : Escape What it does Escape What it does sequence | __[Non-graphic character] sequence [Non-graphic character] \ Backslash (\) \r Carriage Return (CR) y Single quote () \t Horizontal Tab (TAB) g yuble quote (” \ ux, Character with 16-bit hex value ‘ a xxx (Unicode only) (BEL) \Usooexexx | Character with 32-bit hex value ‘ ace xxxxx00x (Unicode only) \b ASCII Backspace (BS) Ww ASCII Vertical Tab (VT) \e ASCII Formfeed (FF) \ooo Character with octal value 000 \n New line character \xhh Character with hex value hh \Niname) | Character named name in the Unicode database (Unicode only) Scanned with CamScanner PUTER SCIEN : 4 compur CE WITH Prt (ii) Numeric Literals Numeric literals are numeric values and these can be one of the following types : (a) int (Signed integers) often «: numbers with no decimal point. The integer literals can be writt © Decimal form : an integer beginning with digits 1-9. $+ 1234, 4100 ete, Octal form : an integer beginning with Oo (zero followed by letter 0) e, Here do remember that for Octal, 8 and 9 are invalid digits ® Hexadecimal form : ai OXAF ete. Here remember that valid digits/letters for hexadecit AF alled just integers or ints, are positive or Negative in 8 0085, 007746 1 integer beginning with Ox (zero followed by letter x) eg, 0, imal numbers are 09 a9 : i 5 Present real numbers _ having fractional parts. These can be write, Parts are number, Exponent form e.g., 0.1765, 3.62, 6C4 ete 13.0, .75, 7. ete. or in vin fractional form eg., (i) Boolean Literals A Boolean literal in Python is used to represer true) or False (Bool nt one of the two Boolean values ie., True: (Boolean lean false). A Boolean literal can either have value as True or as False, () Special Literal None Python has one sp ecial literal, which is None. The value, None literal is used to indicate absence of 1.2.4 Operators Operators are tokens that trigger some “omPutation /action when applied to variables and other objects in an expression, The operators can be arithmetic operators 1%," operators (<<, >>), identity operators (is, operators (and, or), assignment oper: arithmetic-assignment operators (/=, +=, *,1N), bitwise operators (&, 6, |), shift iS not), relational operators CG <>5, !=), logical ator (), membership operators (in, not in), and 1h hen, , IIa), 5 1.2.5 Punctuators Programming languages to organize sentence Structures, and indicate the rhythm and emphasis of expressions statements, and program Most common Punctuators of Python programming language are : “"ANOTIO@ c= Scanned with CamScanner Chopter 1: PYTHON REVISION TOUR 1.3 BAREBONES OF A PYTHON PROGRAM A Python program may contain various elements such as comments, statements, expressions ete. Let us talk about the basic structure of a Python program: ft This program shows a program’ s components. y /ox# Definition of function Seevou() follows oo def SeeYou( re (begin with #) print ("Time to say Good Bye 11") a # Main program-code follows now Statements SS Expressions _S print (a+3) a oo # colonmeans it’s a block = print ("Value of ‘a! was more than 15 initially.") Inline comments Indentation <<" (comment beginning “a print ("Value of 'a!was 15 or less initially.") ——// Function call : ——> seevou() # calling above defined function SeeYou) ‘As you can see that the above sample program contains various components like : © Expressions, which are any legal combination of symbols that represents a value. © Statements, which are programming instructions. © Comments, which are the additional readable information to clarify the source code. Comments can be single line comments, that start with * and multi-line comments that can be either triple-quoted strings or multiple # style comments. © Functions, which are named code-sections and can be reused by specifying their names (function calls). © Block(s) or suite(s), which is a group of statements which are part of another statement or a function. All statements inside a block or suite are indented at the same level. 1.4 VARIABLES AND ASSIGNMENTS Variables represent labelled storage locations, whose values can be manipulated during program run, In Python, to create a variable, just assign to its name the value of appropriate type. For example, to create a variable namely Student to hold student's name and variable age to hold student's age, you just need to write somewhat similar to what is shown below : Student ="Jacob! Scanned with CamScanner COMPUTER SCIENCE WITH pyro, ~My these values as shown below, 1 ereate labels referring (0 python will i pernall student | —]}-———-|_“8¢08 es 1.4.1, Dynamic Typing a nPython, as you have learnt, a variable is defined by assigning to it some value (oF a partcua, type such string etc.). For instance, after the statement + type su s X=10 numeric, s referring to a value of integer type. Jue of some other type to variable x, Python will not We can say that variable 3 Later in your program, if you reassign a val complain (no error will be raised), e.g. arcu X=10 print(X) A variable pointing to a value of * " 2 certain type, can be made to X= "Hello World point to a value/object of print (x) different type. This is called Dynamic Typing. Above code will yield the output as : 16 Hello World So, you can think of Python variables as labels associated with objects (literal values in our case here) ; with dynamic typing, Python makes a label refer to new value with new assignment (Fig, 1.2). Following figure illustrates it. x= 10 x | —————+|_ int:10 X= Hello wore” = x [| ) For example, name = input (‘What is your name ?") isplay the prompt as : ‘The above statement Haney 1: name = input("uhat is your name ?*) Scanned with CamScanner - COMPUTER SCIENCE Witt py, TH Z ON The input() function always returns a value of String type. Python offers two functions; and float() to be used with input() to convert the values received through input() ie in 7 float types. You can : 3 © Read in the value using input() function. © And then use int() or float) function with the read value to change the type of input vy to int or float respectively. a You can also combine these two steps in a single step too, ie, as : = int( input( ) ) = float( input( end = “\n’ or })§ “objects means it can be one or multiple comma separated objets to be printed, Let us consider some simple examples first : print ("hello") #astring print (17.5) #anunber print (3,14159*(r*r)) # the result of a calculation, which will # be performed by Python and then printed # out (assuming that some number has been # assigned to the variable r) print ("T\’n", 12+5,"yearsold.") #multiple conma separated expressions - Scanned with CamScanner CChoptor | : PYTHON REVISION TOUR Jr The print statement has a number of features : © it auto-converts the items to strings ie, if you are printing a numeric value, it will automatically convert it into equivalent string and print it ; for numeric expressions, it first evaluates them and then converts the result to string, before printing. ‘© it inserts spaces between items automatically because the default value of sep argument (separator character) is space(’ ’ ). Consider this code : Four different string objects with no m, "amit .) Ase in te are bing int print (“Hy", “name”, will print My name is Amit. ee But the oxput line has automatically spaces inserted in between shen because defaul sep characteris a space ‘You can change the value of separator character with sep argument of print() as per this: The code : print ("My", "name", "is", "Anit.", sep='...") will print = ag This time the print) separate he items My. name, .is...amit, ith ner sep character whch B © it appends a newline character at the end of the line unless you give your own end argument. Consider the code given below : print ("My name is Amit.”) print ("I am 16 years old") Jt will produce output as : My name is amit. I am 16 years old Ifyou explicitly give an end argument with a print() function then the print() will print the line and end it with the string specified with the end argument, and not the newline character, ¢g., the code print("My name is Amit. ", end = ‘$?) print ("I am16 years old. ") This time the print( ) end she lie with given end will print output as : s Lacie Be carte, hic is ere Ad because i was net Mymname As Amit. $1 am 16 years old. —newtine, nt linus vine from here itl | J 1.1 rte program to input a number and print its cube roar . num = float (input( ‘Enter a number: ')) num_cube = num * num * num print(*The cube of", num, ‘is’, nun_cube) Scanned with CamScanner

You might also like