The document provides an introduction to Python programming, covering its history, syntax, and applications in various fields. It explains key concepts such as variables, data types, operators, conditional statements, and data structures like lists, tuples, sets, and dictionaries. Additionally, it includes examples and exercises to reinforce learning.
The document provides an introduction to Python programming, covering its history, syntax, and applications in various fields. It explains key concepts such as variables, data types, operators, conditional statements, and data structures like lists, tuples, sets, and dictionaries. Additionally, it includes examples and exercises to reinforce learning.
Introduction to Python print("5 is greater than 2") # Indentation is important
What is Python? here Python is a popular, high-level programming language Comments in Python known for its simplicity and readability. Comments are used to explain code and make it easier to It was created by Guido van Rossum and first released in understand. 1991. Single-line comments start with #. Example Python is widely used for web development, data # This is a single-line comment analysis, machine learning, automation, and more. print("Hello, World!") Why Learn Python? Python Variables Easy to Read and Write: Python’s syntax is Variables in Python do not require explicit declaration; straightforward, making it ideal for beginners. you can directly assign values. Example Versatile: Python can be used in various fields like web x=5 # Integer development, data science, artificial intelligence, and y = "Hello" # String software development. Python is dynamically typed, meaning you don’t need to Large Community and Libraries: Python has a vast specify the data type. community and numerous libraries like NumPy, Pandas, 5. Python Data Types and Django, which help in developing different kinds of Common data types include: applications. Integer: Whole numbers (e.g., 10) Applications of Python Float: Numbers with decimals (e.g., 10.5) Web Development: Frameworks like Django and Flask String: Text (e.g., "Hello") make it easy to build websites. Boolean: True or False Data Science: Libraries like Pandas, Matplotlib, and Basic Input and Output TensorFlow are widely used in data analysis and Output: You can display text using the print() function. machine learning. Example Automation: Python scripts can automate repetitive print("Hello, World!") tasks, making life easier for developers. Input: You can take input from the user using the input() Software Development: Python is used in building function. Example: desktop applications and games. name = input("Enter your name: ") Introduction to Python and Basic Syntax print("Hello, " + name) 1. How to Write and Run Python Code Basic Python Operators You can write Python code using a text editor (like Arithmetic Operators: +, -, *, /, %, ** (exponentiation) Notepad++) or an Integrated Development Environment Example: (IDE) like PyCharm or VS Code. a = 10 Python code can be run in different ways: b=3 Python Interpreter: Write and run code line by line in print(a + b) # Addition the command line or terminal. print(a ** b) # Exponentiation (10 raised to the power 3) Python Scripts: Write your code in a file with a .py Conditional Statements extension and run it using the command python Python uses if, elif, and else for conditional logic. filename.py in the terminal. Example: 2. Basic Python Syntax x = 10 Case Sensitivity: Python is case-sensitive, so Var and if x > 5: var would be treated as two different variables. print("x is greater than 5") Indentation: Indentation is crucial in Python as it elif x == 5: defines the blocks of code (like loops, functions). print("x is equal to 5") Typically, 4 spaces or a tab is used. Example: else: if 5 > 2: print("x is less than 5") Operators and Operands in Python What are Operators? **= Exponent and x **= 2 # x = x ** 2 Operators in Python are special symbols or keywords assigns that perform operations on variables and values (known //= Floor division and x //= 2 # x = x // 2 as operands). Python supports various types of operators. assigns What are Operands? Mini Project-1 Operands are the values or variables on which operators Operations on numbers act. For example, in the expression 3 + 4, 3 and 4 are Strings: Manipulating and formatting operands, and + is the operator. #Python Lists Types of Operators in Python #Lists are used to store multiple items in a single Arithmetic Operators variable. Used to perform basic mathematical operations. mylist = ["Student1", "Student2", "Student3"] Operator Description Example print(mylist) + Addition 5+3=8 #List Items - Subtraction 5-3=2 #List items are ordered, changeable, and allow duplicate * Multiplication 5 * 3 = 15 values. / Division 5 / 2 = 2.5 #List items are indexed, the first item has index [0], the % Modulus (Remainder) 5%2=1 second item has index [1] etc. ** Exponentiation (Power) 2 ** 3 = 8 mylist = ["Student1", "Student2", "Student3"] // Floor Division 5 // 2 = 2 print(mylist[1]) Comparison (Relational) Operators #Range of Indexes Used to compare values; the result is either True or #You can specify a range of indexes by specifying where False. to start and where to end the range. Operator Description Example #When specifying a range, the return value will be a new == Equal to 5 == 3 # False list with the specified items. != Not equal to 5 != 3 # True mylist = ["Student1", "Student2", "Student3", > Greater than 5 > 3 # True "Student4", "Student5"] < Less than 5 < 3 # False print(mylist[1:4]) >= Greater than or equal to 5 >= 3 # True #Change List Items <= Less than or equal to 5 <= 3 # False #To change the value of a specific item, refer to the index number: mylist = ["Student1", "Student2", "Student3", "Student4", "Student5"] mylist [1]= "Mayur" Logical Operators print(mylist) Used to combine conditional statements. #Add List Items-Append Items Operator Description Example #To add an item to the end of the list, use the append() and Returns True if both True and method: conditions are true False # False mylist = ["Student1", "Student2", "Student3", or Returns True if at True or False "Student4", "Student5"] least one condition is # True mylist.append("Krishna") true print(mylist) not Reverses the result not True # #Insert Items False #To insert a list item at a specified index, use the insert() Assignment Operators method. Used to assign values to variables. #The insert() method inserts an item at the specified Oper Description Example index: ator mylist = ["Student1", "Student2", "Student3", = Assigns value x=5 "Student4", "Student5"] += Adds and assigns x += 3 # x = x + 3 mylist.insert(2,"Rohit") -= Subtracts and x -= 2 # x = x - 2 print(mylist) assigns #Remove Specified Item *= Multiplies and x *= 4 # x = x * 4 #The remove() method removes the specified item. assigns mylist = ["Student1", "Student2", "Student3", /= Divides and assigns x /= 2 # x = x / 2 "Student4", "Student5"] %= Modulus and x %= 3 # x = x % 3 mylist.remove("Student3") assigns print(mylist) Q 5:How can you check the type of a single-item tuple #List Length and a single-item string? #To determine how many items a list has, use the len() Ans.:Add a comma for a single-item tuple, and do not function: add a comma for a single-item string. mylist = ["Student1", "Student2", "Student3"] For example: print(mylist) var_tuple = ("apple",) print(len(mylist)) print(type(var_tuple)) # Output: <class 'tuple'> #A list can contain different data types: not_a_tuple = ("apple") list1 = ["abc", 34, True, 40, "male"] print(type(not_a_tuple)) # Output: <class 'str'> print(list1) Python Sets Tuples Sets are used to store multiple items in a single variable. Tuples are used to store multiple items in a single Set is one of 4 built-in data types variable. Sets are written with curly brackets. Tuple is one of 4 built-in data types in Python used to Example store collections of data, the other 3 are List, Set, and thisset = {"apple", "banana", "cherry"} Dictionary, all with different qualities and usage. print(thisset) A tuple is a collection which is ordered and Unordered-Set items can appear in a different order unchangeable. every time you use them, and cannot be referred to by Tuples are written with round brackets. index or key. Example Once a set is created, you cannot change its items, but thistuple = ("apple", "banana", "cherry") you can remove items and add new items. print(type(thistuple)) Sets cannot have two items with the same value. Q 1:How do you access the second item in a tuple? Duplicate values will be ignored: Ans.: Example You access the second item in a tuple using index [1]. thisset = {"apple", "banana", "cherry", "apple"} For example: print(thisset) var_tuple = ("apple", "banana", "cherry") Python Dictionary print(var_tuple[1]) # Output: banana Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, Q 2:How do you convert a tuple into a list to change an changeable and do not allow duplicates. item? Dictionaries are written with curly brackets, and have Ans.:Convert the tuple to a list, change the item, then keys and values: convert it back to a tuple. Example For example: #Create and print a dictionary: x = ("apple", "banana", "cherry") thisdict = { y = list(x) "brand": "Ford", y[1] = "kiwi" "model": "Mustang", x = tuple(y) "year": 1964 print(x) # Output: ('apple', 'kiwi', 'cherry') } Q 3:How can you add an item to a tuple? print(thisdict) Ans.:Convert the tuple to a list, add the item, then Access Dictionary Items convert it back to a tuple. Dictionary items are ordered, changeable, and do not For example: allow duplicates. var_tuple = ("apple", "banana", "cherry") Dictionary items are presented in key:value pairs, and y = list(var_tuple) can be referred to by using the key name. y.append("orange") Example var_tuple = tuple(y) #Print the "brand" value of the dictionary: print(var_tuple) # Output: ('apple', 'banana', 'cherry', thisdict = { 'orange') "brand": "Ford", Q 4:How do you use negative indexing to access the last "model": "Mustang", item in a tuple? "year": 1964 Ans.:Use -1 as the index to access the last item. } For example: print(thisdict["brand"]) var_tuple = ("apple", "banana", "cherry") There is also a method called get() that will give you the print(var_tuple[-1]) # Output: cherry same result: Example c=300 #Get the value of the "model" key: if a>b: thisdict = { if a>c: "brand": "Ford", print("a is greatest") "model": "Mustang", else c>b: "year": 1964 print("c is greatest") } else b>c: x = thisdict["model"] print("a is greatest") x = thisdict.get("model") Example 2 a = 33 b = 200 if b > a: Change Dictionary Items print("a is greater than b") You can change the value of a specific item by referring else: to its key name: print("b is greater than a") Example #Change the "year" to 2018: thisdict = { "brand": "Ford", Indentation "model": "Mustang", Python relies on indentation (whitespace at the beginning "year": 1964 of a line) to define scope in the code. Other programming } languages often use curly-brackets for this purpose. thisdict["year"] = 2018 Example Update Dictionary #If statement, without indentation (will raise an error): The update() method will update the dictionary with the a = 33 items from the given argument. b = 200 Example if b > a: thisdict = { print("b is greater than a") "brand": "Ford", # you will get an error "model": "Mustang", Elif "year": 1964 The elif keyword is Python's way of saying "if the } previous conditions were not true, then try this thisdict.update({"year": 2020}) condition". Python Conditions and If statements #Example Control Flows - if…Else a = 33 Python supports the usual logical conditions from b = 33 mathematics: if b > a: Equals: a == b print("b is greater than a") Not Equals: a != b elif a < b: Less than: a < b print("a is greater than b") Less than or equal to: a <= b elif a == b: Greater than: a > b print("a and b are equal") Greater than or equal to: a >= b Q.1 Write a program to compare 3 values of variables These conditions can be used in several ways, most x=20, y=200, z=19 commonly in "if statements" and loops. Else Example: The else keyword catches anything which isn't caught by b = 33 the preceding conditions. a = 200 Example if b > a: a = 200 print("b is greater than a") b = 33 else: if b > a: print("a is greater than b") print("b is greater than a") Q.1. Write a code to compare 3 variable-values to find elif a == b: the largest number between them print("a and b are equal") a=100 else: b=200 print("a is greater than b") --------------------------*********--------------------------- Problem solving session-1 Python Exercise: Find numbers which are divisible by 7 and multiple of 5 between a range # Create an empty list to store numbers that meet the given conditions nl = [] # Iterate through numbers from 1500 to 2700 (inclusive) for x in range(1500, 2701): # Check if the number is divisible by 7 and 5 without any remainder if (x % 7 == 0) and (x % 5 == 0): # If the conditions are met, convert the number to a string and append it to the list nl.append(str(x))
# Join the numbers in the list with a comma and print the result print(','.join(nl))
Python Exercise: Convert temperatures to and from
celsius, fahrenheit Python: Centigrade and Fahrenheit Temperatures : In the centigrade scale, water freezes at 0 degrees and boils at 100 degrees. In the Fahrenheit scale, water freezes at 32 degrees and boils at 212 degrees.The centigrade to Fahrenheit conversion formula is: C = (5/9) * (F - 32)