PYTHON CO1
Basic Print Functions in Python
1. Simple Print Function
Question: Write a Python program that prints "Hello, World!".
Solution:
print("Hello, World!")
```
## 2. Print Variables
- **Question:** Write a Python program that defines two variables, name and age, and prints them in the format: "Name: [name], Age: [age]".
- **Solution:**
python name = "Alice" age = 30 print("Name:", name, "Age:", age) ```
3. String Concatenation
Question: Write a Python program that prints "Python" and "Programming" on the same line using string concatenation.
Solution:
print("Python" + " " + "Programming")
```
## 4. Formatting Strings
- **Question:** Write a Python program that uses the format method to print "Alice is 30 years old".
- **Solution:**
python name = "Alice" age = 30 print("{} is {} years old".format(name, age)) ```
5. f-Strings
Question: Write a Python program that uses an f-string to print "Alice is 30 years old".
Solution:
name = "Alice"
age = 30
print(f"{name} is {age} years old")
```
## 6. Printing Multiple Lines
- **Question:** Write a Python program that prints the following:
- Line 1
- Line 2
- Line 3
- **Solution:**
python print("Line 1") print("Line 2") print("Line 3") ```
7. Escape Characters
Question: Write a Python program that prints the following: She said, "Hello, World!"
Solution:
print('She said, "Hello, World!"')
```
## 8. Using Newline Character
- **Question:** Write a Python program that prints the following using a single print statement:
- Line 1
- Line 2
- Line 3
- **Solution:**
python print("Line 1\nLine 2\nLine 3") ```
9. Printing a Backslash
Question: Write a Python program that prints the following: This is a backslash: \
Solution:
print("This is a backslash: \\ ")
```
## 10. Suppressing the Newline
- **Question:** Write a Python program that prints "Hello," and "World!" on the same line using two print statements.
- **Solution:**
python print("Hello,", end=" ") print("World!") ```
11. Add Two Numbers
Question: Write a Python program that adds two numbers and prints the output.
Solution:
print(4 + 3)
```
# Questions to Practice
1. Write a Python program that prints your Name and ID Number as the output.
2. Write a Python program that defines two variables, Course_title and Course_Code, and prints them in the format: "Name: [name], Age: [age]".
3. Write a Python program that prints "Computational Thinking for" and "Problem Solving" on the same line using string concatenation.
4. Write a Python program that uses the format method to print "Guido Van Rossum created Python Language".
5. Write a Python program that uses an f-string to print "Guido Van Rossum created Python Language".
6. Write a Python program for printing multiple lines as following:
- Line1: First year Sem 1
- Line2: CTPS
- Line3: SEC 16
- Line4: Python
7. Write a Python program that prints using Escape Character the following: Faculty instructed, "Workbook is mandatory to bring for all the Lab Sessions".
8. Write a Python program that prints the following using a single print statement using Newline Character:
- Line1: First year Sem 1
- Line2: CTPS
- Line3: SEC 16
- Line4: Python
9. Write a Python program that prints "Introduction to," and "Python" on the same line using two print statements.
10. Write a Python program that adds two numbers and prints the output.
11. Write a Python program that prints the variable value.
12. Write a Python program that increments the variable value by 5.
13. Create variables:
python num_years = 4 days_per_year = 365 hours_per_day = 24 mins_per_hour = 60 secs_per_min = 60 ``` Write a python program to calculate the number of seconds in four years.
Operators
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, etc.
Examples of Arithmetic Operators
Initialize values:
a = 10
b = 3
```
- Addition:
python addition = a + b # 10 + 3 = 13 ```
Subtraction:
subtraction = a - b # 10 - 3 = 7
```
- Multiplication:
python multiplication = a * b # 10 * 3 = 30 ```
Division:
division = a / b # 10 / 3 = 3.3333...
```
- Modulus:
python modulus = a % b # 10 % 3 = 1 (remainder of the division) ```
Exponentiation:
exponentiation = a ** b # 10^3 = 1000
```
- Floor Division:
python floor_division = a // b # 10 // 3 = 3 (quotient without remainder) ```
2. Assignment Operators
Assignment operators are used to assign values to variables.
Examples of Assignment Operators
Simple assignment:
x = 5 # Simple assignment
```
- Add and assign:
python x += 3 # Equivalent to x = x + 3 (x is now 8) ```
Subtract and assign:
x -= 2 # Equivalent to x = x - 2 (x is now 6)
```
- Multiply and assign:
python x *= 4 # Equivalent to x = x * 4 (x is now 24) ```
Divide and assign:
x /= 3 # Equivalent to x = x / 3 (x is now 8.0)
```
- Modulus and assign:
python x %= 5 # Equivalent to x = x % 5 (x is now 3.0) ```
Exponentiate and assign:
x **= 2 # Equivalent to x = x ** 2 (x is now 9.0)
```
- Floor divide and assign:
python x //= 3 # Equivalent to x = x // 3 (x is now 3.0) ```
3. Comparison Operators
Comparison operators compare two values and return a Boolean result (True or False).
Examples of Comparison Operators
Initialize values:
a = 10
b = 20
```
- Equal:
python print(a == b) # Output: False ```
Not equal:
print(a != b) # Output: True
```
- Greater than:
python print(a > b) # Output: False ```
Less than:
print(a < b) # Output: True
```
- Greater than or equal to:
python print(a >= b) # Output: False ```
Less than or equal to:
print(a <= b) # Output: True
```
## 4. Logical Operators
- Logical operators are used to combine conditional statements.
### Examples of Logical Operators
- Initialize values:
python x = True y = False ```
Logical AND:
print(x and y) # Output: False
```
- Logical OR:
python print(x or y) # Output: True ```
Logical NOT:
print(not x) # Output: False
```
## 5. Membership Operators
- Membership operators are used to test if a sequence contains a specified value.
### Examples of Membership Operators
- Initialize a list:
python numbers = [1, 2, 3, 4, 5] ```
Check for membership:
print(3 in numbers) # Output: True
print(10 not in numbers) # Output: True
```
## 6. Bitwise Operators
- Bitwise operators operate on binary numbers at the bit level.
### Examples of Bitwise Operators
- Initialize values:
python a = 10 # Binary: 1010 b = 4 # Binary: 0100 ```
Bitwise AND:
print(a & b) # Output: 0 (Binary: 0000)
```
- Bitwise OR:
python print(a | b) # Output: 14 (Binary: 1110) ```
Bitwise XOR:
print(a ^ b) # Output: 14 (Binary: 1110)
```
- Bitwise NOT:
python print(~a) # Output: -11 (Binary: 1011) ```
Left shift:
print(a << 1) # Output: 20 (Binary: 10100)
```
- Right shift:
python print(a >> 1) # Output: 5 (Binary: 0101) ```
7. Identity Operators
Identity operators are used to compare the memory locations of two objects.
Examples of Identity Operators
Initialize values:
a = 10
b = 10
```
- Check identity:
python print(a is b) # Output: True print(a is not b) # Output: False ```
List examples:
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # Output: False
print(x is not y) # Output: True
```
# Operator Precedence
## 1. Basic Arithmetic Operations
- **Example Code:**
python result = 2 + 3 * 4 print(result) # Output: 14 ``` - Explanation: Multiplication (*) has higher precedence than addition (+). So, 3 * 4 is evaluated first, giving 12. Thus, 2 + 12 results in 14.
2. Using Parentheses to Change Precedence
Example Code:
result = (2 + 3) * 4
print(result) # Output: 20
```
- **Explanation:** Parentheses () have the highest precedence. Hence, 2 + 3 is calculated first, giving 5, and then 5 * 4 results in 20.
## 3. Mixed Operations with Exponentiation
- **Example Code:**
python result = 2 + 3 ** 2 * 2 print(result) # Output: 20 ``` - Explanation: Exponentiation (*) has higher precedence than multiplication () and addition (+). Consequently, 3 ** 2 is evaluated first, yielding 9, followed by 9 * 2 = 18, and finally 2 + 18 results in 20.
4. Division and Multiplication
**Example Code: **
result = 8 / 4 * 2
print(result) # Output: 4.0
```
- **Explanation:** Division (/) and multiplication (*) share the same precedence and are evaluated from left to right. Therefore, 8 / 4 yields 2.0, followed by 2.0 * 2 resulting in 4.0.
## 5. Mix of Addition, Multiplication, and Modulo
- **Example Code:**
python result = 5 + 3 * 4 % 6 print(result) # Output: 5 ``` - Explanation: The multiplication (*) and modulo (%) operations have higher precedence than addition (+). Thus, 3 * 4 gives 12, followed by 12 % 6 yielding 0 and finally 5 + 0 equals 5.
6. Exponentiation with Multiplication and Division
Example Code:
result = 2 ** 3 * 4 / 2
print(result) # Output: 16.0
```
- **Explanation:** Exponentiation (**) ranks highest, therefore 2 ** 3 yields 8, subsequently 8 * 4 equals 32, and finally 32 / 2 results in 16.0.
## 7. Subtraction and Division with Parentheses
- **Example Code:**
python result = (20 - 5) / 3 + 2 * 4 print(result) # Output: 13.0 ``` - Explanation: Parentheses () hold the top precedence; hence, 20 - 5 produces 15, then 15 / 3 results in 5.0, then 2 * 4 equals 8, and finally 5.0 + 8 computes to 13.0.
8. Nested Parentheses and Exponentiation
Example Code:
result = 2 * (3 + 4) ** 2
print(result) # Output: 98
```
- **Explanation:** Parentheses ( ) are evaluated first giving 3 + 4 = 7, followed by exponentiation resulting in 7 ** 2 = 49, and finally 2 * 49 gives 98.
## 9. Complex Expression with Multiple Operations
- **Example Code:**
python result = 5 + 2 ** 3 * 4 - 8 / 2 print(result) # Output: 33.0 ``` - Explanation: Start with 2 ** 3 giving 8, then 8 * 4 results in 32, followed by 8 / 2 yielding 4.0. The operations are sequenced left to right: 5 + 32 = 37, then 37 - 4.0 gives 33.0.
10. Comparison with Logical AND
Example Code:
result = 5 > 3 and 2 < 4
print(result) # Output: True
```
- **Explanation:** Comparison operators (>, <) are assessed before logical operators. 5 > 3 is evaluated as True, with 2 < 4 also being True. Hence, True and True yields True.
## 11. Not Operator with Comparison
- **Example Code:**
python result = not 3 > 1 print(result) # Output: False ``` - Explanation: The not operator has lower precedence than comparison operators; thus, 3 > 1 evaluates True, which becomes not True resulting in False.
Round() Function
Example 1: Rounding a Floating-Point Number
Rounding Number:
number = 5.67
rounded_number = round(number)
print(rounded_number) # Output: 6
```
- **Explanation:** Since 5.67 is closer to 6 than to 5, the round() function rounds it up to 6.
## Example 2: Rounding to a Specific Number of Decimal Places
- **Rounding to 1 Decimal Place:**
python number = 3.14159 rounded_number = round(number, 2) print(rounded_number) # Output: 3.14 ``` - Explanation: In this example, round() rounds 3.14159 to two decimal places resulting in 3.14.
Example 3: Rounding Halfway Cases
Rounding a Halfway Case:
number = 2.675
rounded_number = round(number, 2)
print(rounded_number) # Output: 2.67
```
- **Explanation:** Python uses the "round to even" strategy, rounding halfway cases like 2.675 to 2.67 instead of 2.68.
## Example 4: Rounding a Negative Number
- **Rounding a Negative Number:**
python number = -1.27 rounded_number = round(number) print(rounded_number) # Output: -1 ``` - Explanation: Negative numbers are rounded similar to positive ones; -1.27 is closer to -1 than -2, so it rounds to -1.
Example 5: Rounding Large Numbers
Rounding a Large Number:
number = 123456.789
rounded_number = round(number, -3)
print(rounded_number) # Output: 123000
```
- **Explanation:** Here, round() with a negative argument (-3) rounds 123456.789 to the nearest thousand yielding 123000.
# Conditional Statements
## 1. if Statement
python a=7 b=10 if a>b: print("CTPS") print("Python")
## 2. if-else Statements
python age=17 if age>=18: print("eligible to vote") else: print("not eligible to vote") print("elections are over")
## 3. if-elif-else Statements
python a=int(input()) b=int(input()) c=int(input()) if a>b and a>c: print("a is largest") elif b>a and b>c: print("b is largest") elif c>a and c>b: print("c is largest") else: print("Welcome to Python")
## 4. Nested if-else Statements
python
a=4 if a>0: if a>=5: print("CTPS") else: print("Python") else: print("Coding")
## 5. If-else Conditional Statement with Format String
python name = input("Enter your name: ") age = int(input("Enter your age: ")) if age >= 18: print(f"{name}, you are eligible to vote.") else: print(f"Sorry {name}, you are not eligible to vote yet.")
## 6. Conditional Statements for Grades
python ch=int(input("enter marks of chemistry")) b=int(input("enter marks of biology")) m=int(input("enter marks of maths")) p=int(input("enter marks of physics")) c=int(input("enter marks of computers")) total=ch+b+m+p+c per=(total/500)*100 if per>=90: print("grade a") elif per>=80 and per<90: print("grade b") elif per>=70 and per<80: print("grade c") elif per>=60 and per<70: print("grade d") elif per>=40 and per<60: print("grade e") else: print("fail")
## 7. Short Hand if...else Statement
python x=5 print("x is greater") if x>5 else print("x is smaller or equal")
# While Loop Statements
## 1. Generate n Natural Numbers
python i=1 n=int(input("enter the limit: ")) while(i<=n): print(i) i+=1
## 2. Sum of n Natural Numbers
python sum=0 count=1 while(count<10): sum=sum+count count+=1 print(count) print(sum)
## 3. Fibonacci Series
python
Number of terms to be generated
num_terms = int(input("Enter the number of terms: "))
Initialize the first two terms and a counter
a, b = 0, 1 count = 0
Print the Fibonacci series
print("Fibonacci series:") while count < num_terms: print(a) # Update the values of a and b for the next term a, b = b, a + b count += 1
## 4. Break in While Loop
python i = 1 while i < 6: print(i) if (i == 3): break i += 1
## 5. Continue in While Loop
python i = 0 while i < 6: i += 1 if i == 3: continue print(i)
# For Loop Statements
## 1. Simple For Loop with String
python fruit="apple" for i in fruit: print(i)
## 2. For Loop with List
python numbers=[1,2,3,4,5] for i in numbers: print(i)
## 3. Indexing in For Loop
python name=input("enter a string: ") for i in range(0,len(name)): print(name[i])
## 4. Using Range in For Loop
python for i in range(5): print(i)
## 5. Using Range with Else in For Loop
python for i in range(0,5): print(i) else: print("finally, else part corresponding statement.")
## 6. For Loop with Break Condition
python numbers = [1, 2, 3, 4, 5]
For loop with a break condition
for i in numbers: if i == 5: print("Found 5, stopping the loop.") break print(i)
## 7. For Loop with Continue Condition
python numbers = [1, 2, 3, 4, 5]
For loop with a continue condition
for i in numbers: if i == 3: print("Skipping 3.") continue print(i)
## 8. Nested For Loop
python adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)
# Strings in Python
## 1. String Data Type
- In Python, a string is a sequence of characters enclosed in quotes. Strings can be enclosed in single quotes (`'...'`), double quotes (`"..."`), or triple quotes (`'''...'''` or `"""..."""`).
- Strings are immutable, meaning their content cannot be changed after they are created.
### Example 1:
python my_string = "Hello, Python!" print(my_string) # Output: Hello, Python!
### Example 2:
python multiline_string = """ This is a multiline string. It can span multiple lines. Great for documentation or long texts. """ print(multiline_string) # Output: This is a multiline string. It can span multiple lines. Great for documentation or long texts.
## 2. Indexing in Strings
- In Python, strings behave like arrays of bytes representing unicode characters.
- Square brackets [ ] can be used to access elements of the string. Indexing allows access to individual characters.
- Python uses zero-based indexing; the first character has an index of 0. Negative indexing starts from the end of the string.
### Example 1:
python my_string = "Python" print(my_string[0]) # Output: P print(my_string[-1]) # Output: n
### Example 2:
python word = "Programming" first_letter = word[0] # P last_letter = word[-1] # g middle_letter = word[len(word)//2] # a print(first_letter, last_letter, middle_letter) # Output: P g a
## 3. Iterating or Looping Over Strings
- Use a `for` loop to iterate over a string and access each character.
### Example 1:
python my_string = "Python" for char in my_string: print(char) # Output: P y t h o n
### Example 2:
python vowels = "aeiou" sentence = "Python is awesome!" vowel_count = 0 for char in sentence: if char.lower() in vowels: vowel_count += 1 print(f"Number of vowels: {vowel_count}") # Output: Number of vowels: 6
## 4. Strings Are Objects
- In Python, strings are objects of the `str` class, meaning they have methods and attributes.
### Example 1:
python my_string = "Hello, World!" print(type(my_string)) # Output:
### Example 2:
python my_string = "hello" capitalized = my_string.capitalize() print(capitalized) # Output: Hello
## 5. String Methods
- Python includes various built-in string methods for manipulating and analyzing strings.
### Example 1:
python my_string = "Python programming" print(my_string.upper()) # Output: PYTHON PROGRAMMING print(my_string.lower()) # Output: python programming print(my_string.replace("Python", "Java")) # Output: Java programming
### Example 2:
python text = "Python programming is fun!"
Strip leading/trailing spaces
cleaned_text = text.strip()
Split into words
words = cleaned_text.split()
Join words with a hyphen
hyphenated = '-'.join(words) print(hyphenated) # Output: Python-programming-is-fun!
## 6. String Slicing
- Slicing allows extraction of a portion of a string. Syntax: `string[start:stop:step]`.
- `start`: the inclusive starting index.
- `stop`: the exclusive stopping index.
- `step`: the interval (optional).
### Example 1:
python my_string = "Hello, World!" print(my_string[0:5]) # Output: Hello
### Example 2:
python
Reverse a string using slicing
reversed_string = my_string[::-1] print(reversed_string) # Output: !dlroW ,olleH
Extract every second character from the string
every_second_char = my_string[::2] print(every_second_char) # Output: Hlo ol!
## 7. Check String Presence
- Use the keyword `in` to check for a certain phrase or character in a string.
### Example:
python txt = "The best things in life are free!" print("free" in txt) # Output: True
Check if NOT
print("expensive" not in txt) # Output: True ```