25
Let’s really start Python SIG – PYA Class 2 – 29/9/15

if, while and for in Python

Embed Size (px)

Citation preview

Page 1: if, while and for in Python

Let’s really start

Python SIG – PYA Class 2 – 29/9/15

Page 2: if, while and for in Python

(Revision of) User input

• Complex programs = input + efficient computation + output

• raw_input, NOT input• raw_input – reads as string, so convert when

required (strongly typed, remember?)• Example:– var = raw_input(prompt)

Page 3: if, while and for in Python

‘print’ing

• print statements, parentheses in Py3; • But backported to 2; so print() works• Pretty flexible: print some_string, var works• Automatically adds newline• Use comma to suppress

Page 4: if, while and for in Python

Useful built-ins

• len()• range() (and xrange())• sum(), max(), min()• int(), float(), str()• dir() – use it to find list and string methods• Use help() to find out about them

Page 5: if, while and for in Python

(again) Read the documentation

• Online / Offline• Google• Stack Overflow• (xkcd?)• “Don’t have to memorise, only know how to

find what you need.”- Me (in last class)

Page 6: if, while and for in Python

Obligatory xkcd reference[1]

Page 7: if, while and for in Python

(Revision of)Boolean

• True / False (capitalization matters!)• >• <• ==• !=• >=• <=• is , is not (same as id())

Page 8: if, while and for in Python

if else elif

if SomethingThatEvaluatesToABoolean:# code

elif SomethingElseThatEvaluatesToABoolean:# code

else:# code

Page 9: if, while and for in Python

Other if structures

• nested if• elif ladders• Basically “forking the flow of program”• Hence called control flow

Page 10: if, while and for in Python

(Revision of)Strings

• Immutable• Single or double, they don’t care• Raw strings• Escape sequences• String slicing – string[start:stop:step]• We count from 0 (why?)• String methods

Page 11: if, while and for in Python

String formatting

• What is it? (Immutable)• %something - %d, %f, %s – ‘a = %d’ % (a)

• Prefer .format()• {} sufficient – numbers optional• More complex things possible

Page 12: if, while and for in Python

In-class assignment

Write a program that reads two numbers from the user, (converting them to integers if they are floating point numbers) and then prints their sum along with the user input in this format:‘enter number 1: ’ 5.67‘enter number 2: ’ 5.67‘You entered 5.67 and 5.67. Adding 5 and 5, sum is 10.’

Page 13: if, while and for in Python

In-class assignment[2]

Write a program that takes input of the form‘num1,num2,[any one of +-*/]’ as a stringand performs the given operation. In other words, your program is a simple calculator which can perform floating point arithmetic. Try making improvements like asking for no.of decimal digits to be displayed.

Page 14: if, while and for in Python

Solution required?

Page 15: if, while and for in Python

Explanation of solutions

• Essentially it is branching – splitting paths• Be careful with ‘else’ – executes

unconditionally• That’s why error handling – ‘try’• Interesting fact – anything you can code, can

be coded with whatever you know now! • (But incredibly tedious)

Page 16: if, while and for in Python

Why loops?

• Essential part of making our programs more complex.

• When do you use for loops?• When do you use while loops?• If (heh.) the while loop is a ‘moving’ if,

what is the for loop?

Page 17: if, while and for in Python

Loops

• for – for when you how many iterations• while - while you don’t know how many

iterations• while SomethingThatEvaluatesToABoolean:

# code• for loop syntax in Python– for iterVar in (x)range(iterNum):

# code

Page 18: if, while and for in Python

for loops can do more!

• What is this ‘in’ anyway? (different time complexity for different cases)

• for char in string• for line in text• for item in sequence– Example: for i in [1,’a’,3]:

print i# output: 1\na\n3

Page 19: if, while and for in Python

Confused / Want to know more?Let’s do help(‘for’) and see what

we can make of it!

Page 20: if, while and for in Python

Loop shortcuts:

• break – jumps out of nearest loop• continue – skips to top of nearest loop• In what situation can break be used?• In what situation can continue be used?

Page 21: if, while and for in Python

In-class assignment

• Input an angle as degrees. And find a trigonometric ratio based on users choice[out of sin, cos and tan]. Do this ‘n’ times, where ‘n’ was entered by the user initially. HINT : import math. (what is import, from..import .. ?) [3]

• Input two strings. One takes in login_ID and other password. It prints “login_ID is successful” if password is password. Else should show a fail message and keep prompting user for password.[3]

Page 22: if, while and for in Python

In-class assignment

Find the factorial of a given number. Don’t import math. Try to make your program break and fix all those cases. (recursive vs. iterative)[2]

Note that I said ‘number’. What if it user entersa string and then it leads to a TypeError?

Page 23: if, while and for in Python

To those who have finished:

• Try to make your calculator (assignment from earlier today) mimic a real life calculator more.

• That is, make it capable of storing the result of a calculation and asking the user what operation to do with that, and so on; until the user types ‘end’ or something.

Page 24: if, while and for in Python

Thanks!

Pranav S Bijapur, ECE, BMSCE, Bangalore

[email protected] Telegram - @pranavsb

Page 25: if, while and for in Python

References

• All “(Revision of)” slides were taken from class 1 presentation made by me on 11-9-15

• [1] – xkcd webcomic - https://xkcd.com/1425/• [2] – idea by Tarun Verma• [3] – modified form of something Tarun Verma

said