Python Programming By Prof. Pallavi Joshi
Python: • It is a General Purpose Programming Language Use: • Desktop App, Web App, Machine Learning App, Data Science App History: • 1991, Guido Van Rossum(GvR), Free Features: • Simple, Easy, Dynamically Typed Software: • Editor Notepad + Python Software(python.org) Coding: • Input(): to get input from user • Int(): to get integer from user • Float(): to get float from user • Print(): to print output on screen • Round(): to control fractional part
What is Python Variables? • Variable is a name that is used to refer to memory location. • Python variable is also known as an identifier and used to hold value. Rules for defining Variables: • The first character of the variable must be an alphabet or underscore ( _ ). • All the characters except the first character may be an alphabet of lower- case(a-z), upper-case (A-Z), underscore, or digit (0-9). • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *). • Identifier name must not be similar to any keyword defined in the language. • Identifier names are case sensitive; for example, my name, and MyName is not the same. • Examples of valid identifiers: a123, _n, n_9, etc. Declaring Variable and Assigning Value: • create a variable at the required time. • The equal (=) operator is used to assign value to a variable. • Example : a=50
Python Data Types • Variables can hold values, and every value has a data-type • Python is a dynamically typed language • do not need to define the type of the variable while declaring it • Example: a=5 , a holds integer value 5 a=10 b="Hi Python" c = 10.5 print(type(a)) print(type(b)) print(type(c)) Sample code to find data type <type 'int’> <type 'str’> <type 'float'>
Numbers: • Number stores numeric values. • integer, float, and complex values are Numbers data-type • type() function to know the data-type of the variable a=5 print("The type of a", type(a)) b=40.5 print("The type of b", type(b)) c=1+3j print("The type of c", type(c)) The type of a <class 'int’> The type of b <class 'float’> The type of c <class 'complex'> String: • string can be defined as the sequence of characters represented in the quotation marks. (“abc”) • the operator + is used to concatenate two strings • operator * is known as a repetition operator str1='hello javatpoint' #string str1 str2=' how are you' #string str2 print(str1[0:2]) #printing first two character u sing slice operator print(str1[4]) #printing 4th character of the s tring print(str1*2) #printing the string twice print(str1+str2) #printing the concatenation o f str1 and str2 he o hello javatpointhello javatpoint hello javatpoint how are you
Python Strings • Strings in python are surrounded by either single quotation marks, or double quotation marks. • Example: ‘Hello’ Or “Hello” Assign String to Variable a = "Hello" print(a) Multiline String(with three double quotes) a = """You can assign a multiline string to a variable by using three quotes.""" print(a) Multiline String(with three single quotes) a = '''You can assign a multiline string to a variable by using three quotes.''' print(a) Strings are Arrays • Python does not have a character data type, a single character is simply a string with a length of 1. a = "Hello, World!" print(a[1]) Looping through a string for x in "banana": print(x) b a n a n a
Strings Length a = "Hello, World!" print(len(a)) • The len() function returns the length of a string 13 Check String • To check if a certain phrase or character is present in a string, we can use the keyword in • Example: Check if "free" is present in the following text txt = "The best things in life are free!" print("free" in txt) True Example: Check if "expensive" is NOT present in the following text txt = "The best things in life are free!" print("expensive" not in txt) True
Python List • Lists are used to store multiple items in a single variable • Example: Create a Lists thislist = ["apple", "banana", "cherry"] print(thislist) ['apple', 'banana', 'cherry'] Access Items thislist = ["apple", "banana", "cherry"] print(thislist[1]) Range of index thislist = ["apple", "banana", "cherry" , "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) ['cherry', 'orange', 'kiwi'] Change list items • To change the value of a specific item, refer to the index number. thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) Change range of item value • Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon": thislist = ["apple", "banana", "cher ry", "orange", "kiwi", "m ango"] thislist[1:3] = ["blackcurrant", "waterme lon"] print(thislist) ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
Add list item • To add an item to the end of the list, use the append() method thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) ['apple', 'banana', 'cherry', 'orange'] Insert into list • To insert a list item at a specified index, use the insert() method thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) ['apple', 'orange', 'banana', 'cherry'] Extend List • To append elements from another list to the current list, use the extend() method thislist = ["apple", "banana", "cherr y"] tropical = ["mango", "pineapple", "pa paya"] thislist.extend(tropical) print(thislist) ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
Remove specified item • The remove() method removes the specified item. thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) ['apple', 'cherry'] thislist = ["apple", "banana", "cherry" ] thislist.pop(1) print(thislist) Remove specified index • The pop() method removes the specified index. ['apple', 'cherry'] Remove specified index • The del keyword also removes the specified index thislist = ["apple", "banana", "cherr y"] del thislist[1] print(thislist) ['apple', 'cherry']
Sort list Copy List Join List • List objects have a sort() method that will sort the list alphanumerically, ascending, by default thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist) ['banana', 'kiwi', 'mango', 'orange', 'pineapple'] • A copy of a list with the copy() method. • A copy of a list with the list() method thislist = ["apple", "banana", "cher ry"] mylist = thislist.copy() print(mylist) thislist = ["apple", "banana", "cher ry"] mylist = list(thislist) print(mylist) ['apple', 'banana', 'cherry'] • using the + operator • Using append() • Using extend() list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) for x in list2: list1.append(x) print(list1) list1.extend(list2) print(list1)
Python Tuples Tuple Items Access Tuple Items • Tuples are used to store multiple items in a single variable • A tuple is a collection which is ordered and unchangeable • Tuples are written with round brackets thistuple = ("apple", "banana", "cherry") print(thistuple) ('apple', 'banana', 'cherry') • Tuple items are ordered, unchangeable, and allow duplicate values. • Tuple items are indexed, the first item has index [0], the second item has index [1] etc. • ex. Allow duplicates thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) banana • access tuple items by referring to the index number, inside square brackets thistuple = ("apple", "banana", "cherry") print(thistuple[1]) ('apple', 'banana', 'cherry', 'apple', 'cherry')
Negative Indexing Range of Indexes Access Tuple Items • Negative indexing means start from the end. • -1 refers to the last item, - 2 refers to the second last item etc. thistuple = ("apple", "banana", "cherry") print(thistuple[-1]) cherry • specify a range of indexes by specifying where to start and where to end the range. • When specifying a range, the return value will be a new tuple with the specified items • The search will start at index 2 (included) and end at index 5 (not included). thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) banana • access tuple items by referring to the index number, inside square brackets thistuple = ("apple", "banana", "cherry") print(thistuple[1]) ('cherry', 'orange', 'kiwi')
Arithmetic Operator Operator Description + (Addition) add two operands. For example, if a = 10, b = 10 => a+b = 20 - (Subtraction) subtract the second operand from the first operand. If the first operand is less than the second operand, the value results negative. For example, if a = 20, b = 5 => a - b = 15 / (divide) It returns the quotient after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a/b = 2.0 * (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 80 % (reminder) It returns the reminder after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a%b = 0
Comparison Operator Operator Description == If two operands is equal != If operands is not equal. <= if first operand is smaller than or equal to second operand. >= if first operand is greater than or equal to second operand. > If the first operand is greater than the second operand. < If the first operand is less than the second operand.
Logical Operator Operator Description and The condition will also be true if the expression is true. If the two expressions a and b are the same, then a and b must both be true. or The condition will be true if one of the phrases is true. If a and b are the two expressions, then an or b must be true if and is true and b is false. not If an expression a is true, then not (a) will be false and vice versa.
Membership Operator Operator Description in Returns True if a sequence with the specified value is present in the object. Example: x in y not in Returns True if a sequence with the specified value is not present in the object Example: x not in y
Identity Operator Oper ator Description is Returns true if both variables are the same object. Example: x is y is not Returns true if both variables are not the same object. Example x is not y Operator Precedence Operat or Description () Parentheses ** Exponentiation * / Multiplication and division + - Addition and subtraction How to Remember: PREMDAS
If Condition Elif condition Else condition "if the previous conditions were not true, then try this condition". Example a = 33 b = 200 if b > a: print("b is greater than a") Example: a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") Example: a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") Indentation Example a = 33 b = 200 if b > a: print("b is greater than a")
While Loop • With the while loop we can execute a set of statements as long as a condition is true. • Example: your own Python Ser Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1 1 2 3 4 5 The Break statement • With the break statement we can stop the loop even if the while condition is true: • Example Exit the loop when i is 3: i = 1 while i < 6: print(i) if i == 3: break i += 1 1 2 3
The Continue Statement • With the continue statement we can stop the current iteration, and continue with the next. • Example Continue to the next iteration if i is 3: i = 0 while i < 6: i += 1 if i == 3: continue print(i) 1 2 4 5 6 The Else Statement • With the else statement we can run a block of code once when the condition no longer is true: • Example • Print a message once the condition is false: i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") 1 2 3 4 5 i is no longer less than 6
For Loop Looping Through a String • A for loop is used for iterating over a sequence • Example Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) apple banana cherry • Even strings are iterable objects, they contain a sequence of characters: • Example Loop through the letters in the word "banana": for x in "banana": print(x) b a n a n a
The break Statement The continue Statement • With the break statement we can stop the loop before it has looped through all the items: • Example Exit the loop when x is "banan": fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break apple banana • With the continue statement we can stop the current iteration of the loop, and continue with the next: • Example Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) apple cherry
1. n = int(input("Enter the number of rows")) 2. # outer loop to handle number of rows 3. for i in range(0, n): 4. # inner loop to handle number of columns 5. # values is changing according to outer loop 6. for j in range(0, i + 1): 7. # printing stars 8. print("* ", end="") 9. 10. # ending line after each row 11. print() This is the example of print simple pyramid pattern
GUI(Graphical User Interface) ● tkinter is a library for creating GUI in Python Coding ● Tk(): to create window ● mainloop(): to show window ● title(): to change title ● geometry(): “widthxheight +xpos+ypos” Widgets ● Label, Entry, Button Width Height YPos XPos
GUI(Graphical User Interface) from tkinter import * root= Tk() root.geometry("1000x300+300+200") root.mainloop() from tkinter import * root= Tk() root.mainloop()
from tkinter import * root= Tk() root.geometry("1000x300+300+200") root.configure(bg="Yellow") root.mainloop() from tkinter import * root= Tk() root.geometry("1000x300+300+200") root.configure(bg="Yellow") lab=Label(root, text="welcome to Python Lab") lab.pack() root.mainloop()
Sample Program(Label) from tkinter import * root= Tk() root.geometry("1000x300+300+200") root.configure(bg="Yellow") f=("Times New Roman",60,"bold") lab=Label(root, text="welcome to Python Lab", font=f, fg="red", bg="yellow") lab.pack(pady=100) root.mainloop()
Sample Program(Button) from tkinter import * root= Tk() root.title("App by me") root.geometry("1000x500+300+100") f=("Times New Roman",30,"bold") def show(): lab.configure(text="Welcome to Python Lab") btn=Button(root, text="Click me", font=f, command=show) btn.pack(pady=30) lab=Label(root, font=f) lab.pack() root.mainloop()
from tkinter import * root=Tk() root.title("App by Me") root.geometry("800x400+300+200") f=("Arial",30,"bold") lab=Label(root, text="Enter your name", font=f) lab.pack(pady=10) ent=Entry(root, font=f) ent.pack(pady=10) def show(): name=ent.get() msg="Good Afternoon " +name ans.configure(text=msg) btn=Button(root, text="click me", font=f, command=show) btn.pack(pady=10) ans=Label(root, font=f) ans.pack(pady=10) root.mainloop() Sample Program(Entry)
Problems Calculate Area Enter radius Result: RED Green Blue Change background colour when button click Calculate radius
Python Dictionaries
Accessing Items You can access the items of a dictionary by referring to its key name, inside square brackets: Python Dictionaries
OUTPUT: {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
ADD Item
Remove Item

Python Programming for basic beginners.pptx

  • 1.
  • 2.
    Python: • It isa General Purpose Programming Language Use: • Desktop App, Web App, Machine Learning App, Data Science App History: • 1991, Guido Van Rossum(GvR), Free Features: • Simple, Easy, Dynamically Typed Software: • Editor Notepad + Python Software(python.org) Coding: • Input(): to get input from user • Int(): to get integer from user • Float(): to get float from user • Print(): to print output on screen • Round(): to control fractional part
  • 3.
    What is PythonVariables? • Variable is a name that is used to refer to memory location. • Python variable is also known as an identifier and used to hold value. Rules for defining Variables: • The first character of the variable must be an alphabet or underscore ( _ ). • All the characters except the first character may be an alphabet of lower- case(a-z), upper-case (A-Z), underscore, or digit (0-9). • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *). • Identifier name must not be similar to any keyword defined in the language. • Identifier names are case sensitive; for example, my name, and MyName is not the same. • Examples of valid identifiers: a123, _n, n_9, etc. Declaring Variable and Assigning Value: • create a variable at the required time. • The equal (=) operator is used to assign value to a variable. • Example : a=50
  • 4.
    Python Data Types •Variables can hold values, and every value has a data-type • Python is a dynamically typed language • do not need to define the type of the variable while declaring it • Example: a=5 , a holds integer value 5 a=10 b="Hi Python" c = 10.5 print(type(a)) print(type(b)) print(type(c)) Sample code to find data type <type 'int’> <type 'str’> <type 'float'>
  • 5.
    Numbers: • Number storesnumeric values. • integer, float, and complex values are Numbers data-type • type() function to know the data-type of the variable a=5 print("The type of a", type(a)) b=40.5 print("The type of b", type(b)) c=1+3j print("The type of c", type(c)) The type of a <class 'int’> The type of b <class 'float’> The type of c <class 'complex'> String: • string can be defined as the sequence of characters represented in the quotation marks. (“abc”) • the operator + is used to concatenate two strings • operator * is known as a repetition operator str1='hello javatpoint' #string str1 str2=' how are you' #string str2 print(str1[0:2]) #printing first two character u sing slice operator print(str1[4]) #printing 4th character of the s tring print(str1*2) #printing the string twice print(str1+str2) #printing the concatenation o f str1 and str2 he o hello javatpointhello javatpoint hello javatpoint how are you
  • 6.
    Python Strings • Stringsin python are surrounded by either single quotation marks, or double quotation marks. • Example: ‘Hello’ Or “Hello” Assign String to Variable a = "Hello" print(a) Multiline String(with three double quotes) a = """You can assign a multiline string to a variable by using three quotes.""" print(a) Multiline String(with three single quotes) a = '''You can assign a multiline string to a variable by using three quotes.''' print(a) Strings are Arrays • Python does not have a character data type, a single character is simply a string with a length of 1. a = "Hello, World!" print(a[1]) Looping through a string for x in "banana": print(x) b a n a n a
  • 7.
    Strings Length a ="Hello, World!" print(len(a)) • The len() function returns the length of a string 13 Check String • To check if a certain phrase or character is present in a string, we can use the keyword in • Example: Check if "free" is present in the following text txt = "The best things in life are free!" print("free" in txt) True Example: Check if "expensive" is NOT present in the following text txt = "The best things in life are free!" print("expensive" not in txt) True
  • 8.
    Python List • Listsare used to store multiple items in a single variable • Example: Create a Lists thislist = ["apple", "banana", "cherry"] print(thislist) ['apple', 'banana', 'cherry'] Access Items thislist = ["apple", "banana", "cherry"] print(thislist[1]) Range of index thislist = ["apple", "banana", "cherry" , "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) ['cherry', 'orange', 'kiwi'] Change list items • To change the value of a specific item, refer to the index number. thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) Change range of item value • Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon": thislist = ["apple", "banana", "cher ry", "orange", "kiwi", "m ango"] thislist[1:3] = ["blackcurrant", "waterme lon"] print(thislist) ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
  • 9.
    Add list item •To add an item to the end of the list, use the append() method thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) ['apple', 'banana', 'cherry', 'orange'] Insert into list • To insert a list item at a specified index, use the insert() method thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) ['apple', 'orange', 'banana', 'cherry'] Extend List • To append elements from another list to the current list, use the extend() method thislist = ["apple", "banana", "cherr y"] tropical = ["mango", "pineapple", "pa paya"] thislist.extend(tropical) print(thislist) ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
  • 10.
    Remove specified item •The remove() method removes the specified item. thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) ['apple', 'cherry'] thislist = ["apple", "banana", "cherry" ] thislist.pop(1) print(thislist) Remove specified index • The pop() method removes the specified index. ['apple', 'cherry'] Remove specified index • The del keyword also removes the specified index thislist = ["apple", "banana", "cherr y"] del thislist[1] print(thislist) ['apple', 'cherry']
  • 11.
    Sort list CopyList Join List • List objects have a sort() method that will sort the list alphanumerically, ascending, by default thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist) ['banana', 'kiwi', 'mango', 'orange', 'pineapple'] • A copy of a list with the copy() method. • A copy of a list with the list() method thislist = ["apple", "banana", "cher ry"] mylist = thislist.copy() print(mylist) thislist = ["apple", "banana", "cher ry"] mylist = list(thislist) print(mylist) ['apple', 'banana', 'cherry'] • using the + operator • Using append() • Using extend() list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) for x in list2: list1.append(x) print(list1) list1.extend(list2) print(list1)
  • 12.
    Python Tuples TupleItems Access Tuple Items • Tuples are used to store multiple items in a single variable • A tuple is a collection which is ordered and unchangeable • Tuples are written with round brackets thistuple = ("apple", "banana", "cherry") print(thistuple) ('apple', 'banana', 'cherry') • Tuple items are ordered, unchangeable, and allow duplicate values. • Tuple items are indexed, the first item has index [0], the second item has index [1] etc. • ex. Allow duplicates thistuple = ("apple", "banana", "cherry", "apple", "cherry") print(thistuple) banana • access tuple items by referring to the index number, inside square brackets thistuple = ("apple", "banana", "cherry") print(thistuple[1]) ('apple', 'banana', 'cherry', 'apple', 'cherry')
  • 13.
    Negative Indexing Rangeof Indexes Access Tuple Items • Negative indexing means start from the end. • -1 refers to the last item, - 2 refers to the second last item etc. thistuple = ("apple", "banana", "cherry") print(thistuple[-1]) cherry • specify a range of indexes by specifying where to start and where to end the range. • When specifying a range, the return value will be a new tuple with the specified items • The search will start at index 2 (included) and end at index 5 (not included). thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) banana • access tuple items by referring to the index number, inside square brackets thistuple = ("apple", "banana", "cherry") print(thistuple[1]) ('cherry', 'orange', 'kiwi')
  • 14.
    Arithmetic Operator Operator Description +(Addition) add two operands. For example, if a = 10, b = 10 => a+b = 20 - (Subtraction) subtract the second operand from the first operand. If the first operand is less than the second operand, the value results negative. For example, if a = 20, b = 5 => a - b = 15 / (divide) It returns the quotient after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a/b = 2.0 * (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b = 80 % (reminder) It returns the reminder after dividing the first operand by the second operand. For example, if a = 20, b = 10 => a%b = 0
  • 15.
    Comparison Operator Operator Description ==If two operands is equal != If operands is not equal. <= if first operand is smaller than or equal to second operand. >= if first operand is greater than or equal to second operand. > If the first operand is greater than the second operand. < If the first operand is less than the second operand.
  • 16.
    Logical Operator Operator Description andThe condition will also be true if the expression is true. If the two expressions a and b are the same, then a and b must both be true. or The condition will be true if one of the phrases is true. If a and b are the two expressions, then an or b must be true if and is true and b is false. not If an expression a is true, then not (a) will be false and vice versa.
  • 17.
    Membership Operator Operator Description inReturns True if a sequence with the specified value is present in the object. Example: x in y not in Returns True if a sequence with the specified value is not present in the object Example: x not in y
  • 18.
    Identity Operator Oper ator Description is Returnstrue if both variables are the same object. Example: x is y is not Returns true if both variables are not the same object. Example x is not y Operator Precedence Operat or Description () Parentheses ** Exponentiation * / Multiplication and division + - Addition and subtraction How to Remember: PREMDAS
  • 19.
    If Condition Elifcondition Else condition "if the previous conditions were not true, then try this condition". Example a = 33 b = 200 if b > a: print("b is greater than a") Example: a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") Example: a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") Indentation Example a = 33 b = 200 if b > a: print("b is greater than a")
  • 20.
    While Loop • Withthe while loop we can execute a set of statements as long as a condition is true. • Example: your own Python Ser Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1 1 2 3 4 5 The Break statement • With the break statement we can stop the loop even if the while condition is true: • Example Exit the loop when i is 3: i = 1 while i < 6: print(i) if i == 3: break i += 1 1 2 3
  • 21.
    The Continue Statement •With the continue statement we can stop the current iteration, and continue with the next. • Example Continue to the next iteration if i is 3: i = 0 while i < 6: i += 1 if i == 3: continue print(i) 1 2 4 5 6 The Else Statement • With the else statement we can run a block of code once when the condition no longer is true: • Example • Print a message once the condition is false: i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") 1 2 3 4 5 i is no longer less than 6
  • 22.
    For Loop LoopingThrough a String • A for loop is used for iterating over a sequence • Example Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) apple banana cherry • Even strings are iterable objects, they contain a sequence of characters: • Example Loop through the letters in the word "banana": for x in "banana": print(x) b a n a n a
  • 23.
    The break StatementThe continue Statement • With the break statement we can stop the loop before it has looped through all the items: • Example Exit the loop when x is "banan": fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break apple banana • With the continue statement we can stop the current iteration of the loop, and continue with the next: • Example Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) apple cherry
  • 24.
    1. n =int(input("Enter the number of rows")) 2. # outer loop to handle number of rows 3. for i in range(0, n): 4. # inner loop to handle number of columns 5. # values is changing according to outer loop 6. for j in range(0, i + 1): 7. # printing stars 8. print("* ", end="") 9. 10. # ending line after each row 11. print() This is the example of print simple pyramid pattern
  • 25.
    GUI(Graphical User Interface) ●tkinter is a library for creating GUI in Python Coding ● Tk(): to create window ● mainloop(): to show window ● title(): to change title ● geometry(): “widthxheight +xpos+ypos” Widgets ● Label, Entry, Button Width Height YPos XPos
  • 26.
    GUI(Graphical User Interface) fromtkinter import * root= Tk() root.geometry("1000x300+300+200") root.mainloop() from tkinter import * root= Tk() root.mainloop()
  • 27.
    from tkinter import* root= Tk() root.geometry("1000x300+300+200") root.configure(bg="Yellow") root.mainloop() from tkinter import * root= Tk() root.geometry("1000x300+300+200") root.configure(bg="Yellow") lab=Label(root, text="welcome to Python Lab") lab.pack() root.mainloop()
  • 28.
    Sample Program(Label) from tkinterimport * root= Tk() root.geometry("1000x300+300+200") root.configure(bg="Yellow") f=("Times New Roman",60,"bold") lab=Label(root, text="welcome to Python Lab", font=f, fg="red", bg="yellow") lab.pack(pady=100) root.mainloop()
  • 29.
    Sample Program(Button) from tkinterimport * root= Tk() root.title("App by me") root.geometry("1000x500+300+100") f=("Times New Roman",30,"bold") def show(): lab.configure(text="Welcome to Python Lab") btn=Button(root, text="Click me", font=f, command=show) btn.pack(pady=30) lab=Label(root, font=f) lab.pack() root.mainloop()
  • 30.
    from tkinter import* root=Tk() root.title("App by Me") root.geometry("800x400+300+200") f=("Arial",30,"bold") lab=Label(root, text="Enter your name", font=f) lab.pack(pady=10) ent=Entry(root, font=f) ent.pack(pady=10) def show(): name=ent.get() msg="Good Afternoon " +name ans.configure(text=msg) btn=Button(root, text="click me", font=f, command=show) btn.pack(pady=10) ans=Label(root, font=f) ans.pack(pady=10) root.mainloop() Sample Program(Entry)
  • 31.
    Problems Calculate Area Enter radius Result: RED Green Blue Changebackground colour when button click Calculate radius
  • 33.
  • 34.
    Accessing Items You canaccess the items of a dictionary by referring to its key name, inside square brackets: Python Dictionaries
  • 36.
  • 37.
  • 38.