python_Baics_ExampleProgram_ INTROTOFUNDAMENTAL OF PYTHON
1.
BACSE101 – PROBLEMSOLVING USING PYTHON MODULE 1 - INTRODUCTION TO PROBLEM SOLVING AND PYTHON FUNDAMENTALS
2.
• Automates circuitsimulations and hardware testing tasks. • Analyzes and visualizes sensor data using tools like NumPy and Matplotlib. • Programs microcontrollers (e.g., ESP32, Raspberry Pi) with MicroPython. • Interfaces with instruments (oscilloscopes, multimeters) via PyVISA. • Enables AI/ML applications in smart electronics and signal processing.
• The conceptinvolves identifying a situation, figuring out its root cause, locating, ranking, and choosing potential solutions, as well as putting those solutions into action. STEPS AND TECHNIQUES INVOLVED IN PROBLEM SOLVING STEP 1: DEFINING OR IDENTIFYING THE PROBLEM STEP 2: GENERATING THE ALTERNATIVE SOLUTION STEP 3: EVALUATING THE ALTERNATIVES STEP 4: IMPLEMENTING AND FOLLOWING UP ON THE CHOSEN ALTERNATIVE SOLUTION STEP 5: EVALUATING THE RESULTS
Boundary Test Cases •Validatebehavior at edges of input domain •Examples: minimum, maximum, one above/below limits Robust Test Cases •Validate handling of invalid or unexpected inputs •Examples: non-numeric, null, negative values
10.
Input Field MinMax Test Cases Age 0 120 –1 (invalid), 0, 1, 119, 120, 121 (invalid) Rate (%) 0 100 –5, 1, 99, 100, 105 Name – – "", "Alice", nil, 256-char string
• An algorithmis a set of well-defined instructions designed to perform a specific task or solve a particular problem. • It takes a set of inputs and produces the desired output through a series of computational steps. • Algorithms are fundamental to computer science and are used in various fields such as mathematics, data science, artificial intelligence, and more.
13.
Key characteristics ofalgorithms Clear and unambiguous: each step of the algorithm must be clear and lead to only one meaning. Well-defined inputs and outputs: the algorithm should specify the inputs it takes and the outputs it produces. Finite: the algorithm must terminate after a finite number of steps. Feasible: the algorithm should be practical and executable with the available resources. Language independent: the algorithm should be implementable in any programming language.
14.
Example: algorithm toadd three numbers • Let's consider a simple algorithm to add three numbers and print their sum: 1. Start 2. Declare three integer variables num1, num2, and num3. 3. Take the three numbers as inputs in variables num1, num2, and num3. 4. Declare an integer variable sum to store the resultant sum. 5. Add the three numbers and store the result in the variable sum. 6. Print the value of the variable sum. 7. End
Flowcharts are graphicalrepresentations of data, algorithms, or processes, providing a visual approach to understanding code. • Flowcharts illustrate step-by-step solutions to problems, making them useful for beginner programmers. • Flowcharts help in debugging and troubleshooting issues. • Flowchart consists of sequentially arranged boxes that depict the process flow.
• A pseudocodeis defined as a step-by-step description of an algorithm. • Pseudocode does not use any programming language in its representation instead it uses the simple english language text as it is intended for human understanding rather than machine reading. • Pseudocode is the intermediate state between an idea and its implementation(code) in a high-level language.
21.
What is theneed for pseudocode • Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the solution to the problem as well as the reader in understanding the approach to the problem. • Pseudocode is an intermediate state between algorithm and program that plays supports the transition of the algorithm into the program.
23.
• PSEUDOCODE EXAMPLE Begin Inputprincipal, rate, time Interest ← (principal * rate * time) / 100 Totalpayment ← principal + interest Output totalpayment End
• Python isa powerful, versatile, and beginner-friendly programming language widely used for various applications, including web development, data analysis, artificial intelligence, machine learning, automation, and more. • Its simplicity and readability make it an excellent choice for both beginners and experienced developers.
26.
Key features ofpython: • Easy to learn and use: python has a simple syntax that resembles natural language, making it accessible for beginners. • Versatile: it supports multiple programming paradigms, including procedural, object-oriented, and functional programming. • Extensive libraries: python has a rich ecosystem of libraries and frameworks like numpy, pandas, tensorflow, flask, and django. • Cross-platform: python runs on various platforms, including windows, macos, and linux. • Community support: a large and active community ensures plenty of resources, tutorials, and forums for learning and troubleshooting.
27.
What you cando with python: • Web development: build websites using frameworks like django or flask. • Data science: analyze and visualize data with libraries like pandas and matplotlib. • Machine learning: create intelligent systems using tensorflow or scikit-learn. • Automation: automate repetitive tasks with scripts. • Game development: develop games using libraries like pygame.
• Variables arecontainers for storing data values. • Python has no command for declaring a variable. • A variable is created the moment you first assign a value to it. Example, x = 5 y = "john" print(x) print(y)
31.
• Variables donot need to be declared with any particular type, and can even change type after they have been set. Example X = 4 # x is of type int x = "sally" # x is now of type str print(x)
32.
Variable names • Avariable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). • Rules for python variables: • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (a-z, 0-9, and _ ) • Variable names are case-sensitive (age, age and AGE are three different variables) • A variable name cannot be any of the python keywords.
MULTI WORDS VARIABLENAMES Camel case • Each word, except the first, starts with a capital letter: • myVariableName = "john" Pascal case • Each word starts with a capital letter: • MyVariableName = "john" Snake case • Each word is separated by an underscore character: • my_variable_name = "john"
OUTPUT VARIABLES • Thepython print() function is often used to output variables. X = "PYTHON IS AWESOME" print(X) • In the print() function, you output multiple variables, separated by a comma: X = "PYTHON" Y = "IS" Z = "AWESOME" print(X, Y, Z)
37.
• You canalso use the + operator to output multiple variables: X = "python " Y = "is " Z = "awesome" print(x + y + z) • For numbers, the + character works as a mathematical operator: X = 5 Y = 10 print(X + Y) Concatenation
38.
• In theprint() function, when you try to combine a string and a number with the + operator, python will give you an error: X = 5 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: X = 5 y = "john" print(x, y) Different Data types
• Variables canstore data of different types, and different types can do different things. • Python has the following data types built-in by default, in these categories: Text Type: str 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 None Type: NoneType
41.
• You canget the data type of any object by using the type() function: X = 5 print(type(X))
42.
PYTHON NUMERIC TYPES •There are three numeric types in python: Int Float Complex • Variables of numeric types are created when you assign a value to them: x = 1 # int y = 2.8 # float z = 1j # complex
43.
INT • Int, orinteger, is a whole number, positive or negative, without decimals, of unlimited length. X = 1 Y = 35656222554887711 Z = -3255522
44.
FLOAT • Float, or"floating point number" is a number, positive or negative, containing one or more decimals. X = 1.10 Y = 1.0 Z = -35.59 • Float can also be scientific numbers with an "e" to indicate the power of 10. X = 35e3 y = 12E4 z = -87.7e100
TYPE CONVERSION • Youcan convert from one type to another with the int(), float(), and complex() methods: X = 1 # INT Y = 2.8 # FLOAT Z = 1J # COMPLEX #CONVERT FROM INT TO FLOAT: A = FLOAT(X) #CONVERT FROM FLOAT TO INT: B = INT(Y) #CONVERT FROM INT TO COMPLEX: C = COMPLEX(X)
47.
• Store andprint your name. • Add two numbers and display the result. • Print the data type of a float number. • Swap two variables and print the new values. • Take your name as input and display a greeting message. • Convert a string number to integer and add 10. • Calculate and print the area of a rectangle. • Take two numbers from the user and print which one is greater. • Check if a number entered by the user is even or odd. • Calculate the simple interest. Formula: SI = (P × R × T) / 100 Take P, R, T from user input. • Check if a number is divisible by both 3 and 5. • Create a program that converts Celsius to Fahrenheit. Formula: F = (C × 9/5) + 32 • Check whether a number is positive, negative, or zero.
48.
PYTHON STRINGS • Stringsin python are surrounded by either single quotation marks, or double quotation marks. • 'Hello' is the same as "hello". • You can display a string literal with the print() function: print("Hello") print(‘Hello')
49.
Assign string toa variable • Assigning a string to a variable is done with the variable name followed by an equal sign and the string: A = "hello" print(a) Multiline Strings • You can assign a multiline string to a variable by using three quotes(single or double): A = """LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT, SED DO EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA.""" print(A)
50.
Slicing • You canreturn a range of characters by using the slice syntax. • Specify the start index and the end index, separated by a colon, to return a part of the string. Example Get the characters from position 2 to position 5 (not included): • B = "hello, world!" print(B[2:5]) 11O Starts with Zero and ends at one less 01234
51.
Slice from thestart • By leaving out the start index, the range will start at the first character: Example • Get the characters from the start to position 5 (not included): • B = "hello, world!" print(b[:5]) hello 01234
52.
Slice to theend • By leaving out the end index, the range will go to the end: Example • Get the characters from position 2, and all the way to the end: • B = "hello, world!" print(b[2:])
53.
Negative indexing • Usenegative indexes to start the slice from the end of the string: • B = "hello, world!" print(b[-5:-2]) Upper Case a = "Hello, World!" print(a.upper()) Lower Case a = "Hello, World!" print(a.lower())
F-strings (Format String) •To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations. • Age = 36 txt = f"my name is john, i am {age}" print(txt) • A placeholder can include a modifier to format the value. • A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals: • PRICE = 59 TXT = F"THE PRICE IS {PRICE:.2F} DOLLARS" print(TXT)
56.
PYTHON BOOLEANS • Inprogramming you often need to know if an expression is true or false. • You can evaluate any expression in python, and get one of two answers, true or false. • When you compare two values, the expression is evaluated and python returns the boolean answer: print(bool (10 > 9)) / print(10 > 9) print(10 == 9) print(10 < 9) Express - true or false
57.
• The bool()function allows you to evaluate any value, and give you True or False in return, print(bool("hello")) print(bool(15)) print(bool(0)) print(bool())
• Operators areused to perform operations on variables and values. • Python divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators
60.
Operator Name Example +Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y • ARITHMETIC OPERATORS
61.
Operator Example SameAs = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 • ASSIGNMENT OPERATORS
62.
Operator Name Example ==Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y • COMPARISON OPERATORS
63.
Operator Description Example andReturns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10) • LOGICAL OPERATORS
64.
Operator Description Example isReturns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y • IDENTITY OPERATORS
65.
Operator Description Example inReturns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y • MEMBERSHIP OPERATORS
66.
Operator Name DescriptionExample & AND Sets each bit to 1 if both bits are 1 x & y | OR Sets each bit to 1 if one of two bits is 1 x | y ^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y ~ NOT Inverts all the bits ~x << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2 >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2 • BITWISE OPERATORS
67.
Operator Description () Parentheses **Exponent +x -x ~x Unary plus, unary minus, and bitwise NOT * / // % Multiplication, division, floor division, and modulus + - Addition and subtraction << >> Bitwise left and right shifts & Bitwise AND ^ Bitwise XOR | Bitwise OR == != > >= < <= is is not, in, not in Comparisons, identity, and membership operators not Logical NOT and AND or OR OPERATOR PRECEDENCE
In python, expressionsare combinations of values, variables, operators, and function calls that are evaluated to produce a result. Here’s an overview of the main types of expressions: 1. Constant expressions • These consist of constant values only. Example: X = 42 Y = "hello, world!"
70.
2. Arithmetic expressions •Combine numeric values and operators to perform mathematical operations. Example: result = (5 + 3) * 2 - 4 / 2 3. Relational (comparison) expressions • Compare two values and return a boolean result (true or false). Example: is_greater = 10 > 5 is_equal = 7 == 7
71.
4. Logical expressions •Combine boolean values using logical operators (and, or, not). Example: result = (10 > 5) and (3 < 8) 5. Bitwise expressions • Perform operations at the bit level using operators like &, |, ^, ~, <<, >>. Example: bitwise_and = 5 & 3
72.
6. Membership expressions •Check for membership in a sequence using in or not in. Example: is_present = 'a' in 'apple’ 7. Identity expressions • Check if two objects are the same using is or is not. Example: same_object = x is y
73.
1. Python Strings 1.Reverse a String Take a string as input and print its reverse using slicing. word = "python" print(word[::-2]) 2. Check Palindrome Ask the user for a word and check if it is a palindrome (a word that reads the same backward). 2. Python Booleans 3. Check Age Eligibility Ask the user for their age. If age is 18 or above, print "Eligible to vote", else print "Not eligible". 4. Password Match Write a program that asks the user to enter a password and confirm it. Check if both match and print a boolean result. 5. Is Even? Write a program to input a number and check whether it is even. Output the result as a boolean value (True or False).
74.
3. Operators 1. SimpleCalculator Take two numbers from the user and apply all arithmetic operators: +, -, *, /, and %. 2. Compare Two Numbers Ask the user to input two numbers and use comparison operators to print which number is greater. 3. Bitwise AND/OR Write a program to input two numbers and show the result of bitwise AND (&) and OR (|). 4. Check Multiples using Modulo Ask the user for a number and check if it is a multiple of 5 using the % operator. 4. Expressions 5. Area of Circle Ask the user to input the radius and compute the area using the expression area = 3.14 * r * r. 6. Final Price After Discount Given the original price and discount percentage, calculate the final price using an expression. 7. Calculate Average Marks Ask the user for marks in 3 subjects and compute the average using an arithmetic expression.
• Python providesa wide range of built-in functions that are always available for use without needing to import any module. These functions help perform common tasks efficiently. Here's an overview of some commonly used ones: print(): Outputs data to the console. input(): Takes user input as a string. len(): Returns the length of an object (e.g., string, list). type(): Returns the type of an object. id(): Returns the unique identifier of an object.
77.
# Take userinput user_input = input("enter any text: ") # display the raw input print("you entered:", user_input) # Show length of the input print("length of input:", len(user_input)) # Show the data type of input print("type of input:", type(user_input)) # Show the unique identifier (memory address) print("object ID (memory location):", id(user_input))
• A regex,or regular expression, is a sequence of characters that forms a search pattern. • Regex can be used to check if a string contains the specified search pattern. • Python has a built-in package called re, which can be used to work with regular expressions. import re
80.
Regex functions • There module offers a set of functions that allows us to search a string for a match: Function Description findall Returns a list containing all matches search Returns a Match object if there is a match anywhere in the string split Returns a list where the string has been split at each match fullmatch ensures the entire string matches the pattern — no extra characters allowed. sub Replaces one or many matches with a string
81.
• Example import re pin= input("enter your 6-digit PIN code: ") # pattern: exactly 6 digits pattern = r"d{6}“ # Validate using fullmatch if re.fullmatch(pattern, pin): print("valid PIN") else: Print("invalid PIN") pattern=r"^[a-zA-Z0-9!@#$%^&*()-_+=]+$" pattern=r"d{6}" pattern=r"^[a-zA-Z0-9!@#$%^&*()-_+=]$" pattern=r"^[a-z][A-Z0-9][!@#0-9]{4,6}$"
82.
Gaming leaderboard usernamevalidator • In an online game, players choose usernames for the leaderboard. To make sure all usernames are clean and fair, they must follow these rules: i. The username must start with a letter (A–Z or a–z). ii. It can contain letters, numbers, and underscores (_) only. iii. It cannot start with a number. iv. No other symbols or spaces are allowed. v. The length must be between 5 and 15 characters. Write a python program using regular expressions to check if a username is valid or invalid. If invalid, display a message “invalid name”
83.
1. Create twovariables: one storing an integer age and another storing your name as a string. Print a sentence using both. 2. Convert the string "45.67" into a float, then into an integer. Print both results. 3. Create a string with extra spaces on both ends: " python ". use strip() to clean it and print the result. 4. Take the string "hello world" and print it in all uppercase and all lowercase. 5. Replace "ai" with "artificial intelligence" in the sentence "ai is transforming healthcare". 6. Given "red,blue,green,yellow" as input, split it into a list using split(','). Print each color on a new line. result = "n".join(color_list)
84.
7. Convert astring "123" to an integer and multiply it by 2. Show the result. 8. Slice the word "innovation" to get: • First 3 characters • Last 4 characters • Characters from index 2 to 6 9. Store "data" and "science" in two variables, then combine them with and without a space in between and print. 10. Ask the user for a sentence input. Replace all occurrences of "e" with "3" and print the modified sentence.