You are on page 1of 8

Python

Python is one of the most popular programming languages in the world. It’s widely used in web and
game development, data analytics, data science, machine learning, and much more. It was
created by Guido van Rossum, and released in 1991.
Python has a simple syntax, which means that it’s easier to learn. In this course you’ll start coding
your own programs in no time, so you can solve real-world problems and build your own
applications.
Q: What’s a programming language?
(i) A language used by machines to communicate with aliens
(ii) A language used by humans to communicate with machines
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
# This is a single-line comment
print("Hello, World!") # This is also a comment

"""
This is a multi-line comment or docstring.
It can span multiple lines and is often used
to provide documentation for code.
"""

1. Variable Naming Rules:


• Variable names can consist of letters (uppercase or lowercase), digits, and underscores.
• Variable names must start with a letter (a-z, A-Z) or an underscore (_).
• Variable names are case-sensitive, meaning myVar and myvar are considered different
variables.
• Python keywords (reserved words) cannot be used as variable names.
2. Variable Assignment:
• You can assign a value to a variable using the assignment operator (=).
• Python is dynamically typed, so you don't need to declare the variable's data type explicitly;
it's determined automatically based on the assigned value.
Example:
x = 5 # x is assigned the integer value 5
name = "Alice" # name is assigned the string value "Alice"
3. Variable Data Types:
Python supports various data types for variables, including:
• int: Integer data type (e.g., 5, -3).
• float: Floating-point data type (e.g., 3.14, -0.5).
• str: String data type (e.g., "Hello, World!").
• bool: Boolean data type (True or False).
• list: Ordered collection of items (e.g., [1, 2, 3]).
• tuple: Immutable ordered collection of items (e.g., (1, 2, 3)).
• dict: Dictionary data type (e.g., {"name": "Alice", "age": 30}).
• set: Unordered collection of unique items (e.g., {1, 2, 3}).
4. Variable Reassignment:
You can change the value of a variable by assigning it a new value of the same or a different data
type.
Example:
x=5
x = 10 # x is reassigned to a new value (integer)
name = "Alice"
name = "Bob" # name is reassigned to a new value (string)
5. Variable Scope:
• Variables can have different scopes, including global and local.
• Global variables are defined outside of functions and are accessible throughout the program.
• Local variables are defined inside functions and have limited scope within that function.
Example:
global_var = 10 # Global variable
def my_function():
local_var = 5 # Local variable
print(global_var) # Accessing global variable
print(local_var) # Accessing local variable
my_function()
6. Variable Naming Conventions:
It's a good practice to follow certain naming conventions for variables to make your code more
readable. For example, using lowercase letters and underscores for variable names (snake_case) is
a common convention in Python.
Example:
user_name = "Alice"
7. Basic Arithmetic Operators:
• + (Addition): Adds two numbers together.
• - (Subtraction): Subtracts the second number from the first.
• * (Multiplication): Multiplies two numbers.
• / (Division): Divides the first number by the second, resulting in a float.
• // (Floor Division): Divides the first number by the second, resulting in an integer.
• % (Modulus): Returns the remainder after division.
• ** (Exponentiation): Raises the first number to the power of the second.
a = 10
b=3
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
floor_division = a // b
modulus = a % b
exponentiation = a ** b
import math
x = 2.0
# Trigonometric functions
sin_x = math.sin(x)
cos_x = math.cos(x)
tan_x = math.tan(x)
# Logarithmic functions
log_x = math.log(x)
log10_x = math.log10(x)
# Exponential functions
exp_x = math.exp(x)
pi_value = math.pi
e_value = math.e
a = -4.75
abs_a = abs(a) # Absolute value: 4.75
rounded_a = round(a) # Round to the nearest integer: -5
Output
The print command or instruction is the easiest way to send a specified message to the screen or
other display device.
This message or output can be a number, text, or the result of a calculation.
print(“Hello Naogaon Basi!!”)
print("Welcome to the Code Playground")
1. The print() instruction is the easiest way to send a message to the screen or other display
device.
print ("Hello, World!")
Python Casting
In Python, casting refers to the process of converting one data type into another. Python
provides built-in functions for performing type casting, allowing you to convert variables from
one data type to another when needed. Here are some of the common type casting functions and
techniques in Python:
1. int() Function:
The int() function is used to cast other data types to integers.
When converting floating-point numbers to integers, it truncates the decimal part (rounding
towards zero).
When converting strings to integers, the string must represent a valid integer. Otherwise, it raises
a ValueError.
Example:
float_num = 3.75
int_num = int(float_num) # Converts 3.75 to 3
str_num = "42"
int_from_str = int(str_num) # Converts "42" to 42
2. float() Function:
The float() function is used to cast other data types to floating-point numbers.
It can convert integers, strings representing floats, or other numeric types to floats.
Example:
int_num = 42
float_num = float(int_num) # Converts 42 to 42.0
str_num = "3.14"
float_from_str = float(str_num) # Converts "3.14" to 3.14
3. str() Function:
The str() function is used to cast other data types to strings.
It converts integers, floating-point numbers, and other data types to strings.
Example:
int_num = 42
str_num = str(int_num) # Converts 42 to "42"
float_num = 3.14
str_from_float = str(float_num) # Converts 3.14 to "3.14"
4. Type Casting for Boolean Values:
You can use type casting to convert boolean values to integers, where True becomes 1 and False
becomes 0.
Example:
bool_value = True
int_value = int(bool_value) # Converts True to 1
Python Strings
Strings are a fundamental data type in Python used to represent sequences of characters. They
are enclosed in either single quotes (''), double quotes (""), or triple quotes ('''''' or """"""), and
Python treats them as immutable sequences. Here are some important details about strings in
Python:
Creating Strings:
You can create strings by enclosing text in single, double, or triple quotes.
Example:
single_quoted_str = 'This is a string.'
double_quoted_str = "This is another string."
triple_quoted_str = '''A multi-line
string using triple quotes.'''
String Concatenation:
You can concatenate (join) strings using the + operator.
Example:
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2 # Result: "Hello World"
String Repetition:
You can repeat a string by using the * operator.
Example:
original_str = "Python"
repeated_str = original_str * 3 # Result: "PythonPythonPython"
original_str = "Python"
repeated_str = original_str * 3 # Result: "PythonPythonPython"
String Length:
You can find the length of a string using the len() function.
Example:
text = "Python is awesome"
length = len(text) # Result: 17
Accessing Characters:
You can access individual characters in a string using indexing. Python uses 0-based indexing,
where the first character is at index 0.
Example:
text = "Python"
first_char = text[0] # Result: "P"
Slicing Strings:
You can extract substrings from a string using slicing, which specifies a start and end index.
Example:
text = "Python is fun"
sub_str = text[7:9] # Result: "is"
String Methods:
Python provides a wide range of string methods for manipulating and working with strings. Some
common methods include upper(), lower(), strip(), split(), replace(), and find().
Example:
text = "Hello, World!"
upper_text = text.upper() # Convert to uppercase
lower_text = text.lower() # Convert to lowercase
stripped_text = text.strip() # Remove leading and trailing whitespace
String Formatting:
You can format strings using methods like string interpolation and the format() method.
Example (f-strings, available in Python 3.6+):
name = "Alice"
age = 30
formatted_str = f"My name is {name} and I am {age} years old."
Escape Sequences:
Escape sequences are used to include special characters within a string, such as newline (\n), tab
(\t), and backslash (\\).
Example:
escape_str = "This is a newline\nThis is a tab\tThis is a backslash\\"
Immutable Nature:
Strings in Python are immutable, which means you cannot modify the contents of a string once it
is created. Any manipulation creates a new string.
String Operations:
You can perform various operations on strings, such as checking for substrings using in,
comparing strings, and more.
Example:
text = "Hello, World!"
is_world_in_text = "World" in text # Checks if "World" is in the string
String slicing
String slicing in Python allows you to extract a portion of a string by specifying a start and end
index. This technique is used to obtain substrings or subsequences from a given string. Python
uses zero-based indexing, where the first character of the string has an index of 0. Here's the
basic syntax for string slicing:
string[start:end]
start: The index at which the slice begins (inclusive).
end: The index at which the slice ends (exclusive).
The resulting substring includes characters from the start index up to, but not including, the
character at the end index.
Here are some examples of string slicing:
text = "Hello, World!"
# Extracting a substring from index 7 to 11
substring = text[7:12] # Result: "World"
# Slicing from the beginning to index 5 (exclusive)
slice1 = text[:5] # Result: "Hello"
# Slicing from index 7 to the end
slice2 = text[7:] # Result: "World!"
# Slicing the entire string (creating a copy)
copy_of_text = text[:] # Result: "Hello, World!"
# Slicing with negative indices (counting from the end)
last_five_chars = text[-5:] # Result: "world!"

A variable is a reserved memory area (memory address) to store value.


name = "John" # string assignment
age = 25 # integer assignment
salary = 25800.60 # float assignment

print(name) # John
print(age) # 25
print(salary) # 25800.6
var = 10
print(var) # 10
# print its type

print(type(var)) # <class 'int'>


# assign different integer value to var
var = 55
print(var) # 55

# change var to string


var = "Now I'm a string"
print(var) # Now I'm a string
# print its type
print(type(var)) # <class 'str'>

# change var to float


var = 35.69
print(var) # 35.69
# print its type
print(type(var)) # <class 'float'>
birth_year = input()
print(type(birth_year))
1. What is the output of the following code
print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j))
3. What is the output of the expression print(-18 // 4)
4. What is the output of print(2%6)
7. What is the output of print(2 * 3 ** 3 * 4)
8. What is the output of the following code
x = 100
y = 50
print(x and y)
What is the output of print(10 - 4 * 2)
What is the output of the following code
x=6
y=2
print(x ** y)
print(x // y)
The int(), str() and float() instructions are examples of explicit conversion, which means
they are performed by an instruction given by a programmer (like you).
On the other hand, run the code to see some examples of implicit (automatic) data type
conversions
x = 5 # integer
y = 2 # integer
z = x/y # float (implicit conversion)
What will the code output?
x = input()
y = input()
print(x+y)
What does the print() statement do?
(a) It modifies a variable
(b)It displays a value on the screen
How do you access the value stored in a variable?
(a) Using exclamation marks
(b) Calling the variable name
Which 2 values will this code display on the screen?
username = "magician"
points = 50
lives = 3
print(username)
print(points)
What will this code send to the screen?
price = 5
amount = 3
print(price * amount)
What will this code send to the screen?
points = 35
points = 45
print(points)
What values will the code send to the screen?
name = "Tom"
level = 14
print(name)
level = level + 1
print(level)
What will this code send to the screen?
player = "James"
score = 55
level = 14
What value will this code send to the screen?
band = "Beatles"
song = "Yesterday"
song = "Let it be"
print(song)
Coding consists of 3 steps:
- Writing
- Executing (or running)
- Fixing errors (or debugging)
The line of code below contains a bug, can you identify it?
print 5 + 3
(a) parentheses are missing
(b) variables have not been defined
(c) quotation marks are missing
Which lines contain bugs?
salary = 50000
role = Analyst
age -> 29
print(salary)
At which line will this code stop the execution?
salary = 50000
role = Analyst
age -> 29
print(salary)
The computer will get stuck at line 2. Why?
salary = 50000
role = Analyst
age -> 29
print(salary)
(a) Line 2 contains the first error
(b) The error in line 3 is anticipated
At which line will this code stop execution?
salary = 70000
print(salary)
age -> 32
role = "Product Manager"
print(role)
What will this code send to the screen?
print(balance)
(a) the message "balance"
(b) An error because the balance variable has not been declared
Problem
The given code is expected to display the results of a dancing competition on the screen but
something is wrong with the instructions.
Task
Fix the bugs to show the following result on the screen
Anna
96
What will this code send to the screen?
#print("Game Over")
How many different variables are being declared in the code below?
credit = 300
Credit = 280
CREDIT = 320
What would you call a variable that stores a user id?
user*id
user/id
user_id
user#id
What will this code send to the screen?
salary = 900
new_salary = salary + 200
print(new_salary)
What will this code send to the screen?
salary = 1000
pay_raise = 100
print(new_salary)
new_salary = salary + pay_raise
What will this code send to the screen?
salary = 1000
pay_raise = 100
new_salary = salary + pay_raise
print(salary)
What will this code display on the screen?
payment_status = "returned"
payment_status = "paid"
print(payment_status)

What will this code send to the screen?


a=3
a=5
a=7
print(a)
Computer programs can have multiple inputs and outputs. What will the code output?
username = "zombie"
points = 50
lives = 3
print(points)
print(lives)
Problem
Write a program that asks the user for an input and displays it on the screen. You'll continue
working on this code after the next lesson.
Task
Complete the code to ask the user for input, store it in the name variable, and display it on the
screen.
Input Output
name =”Ami” Ami
name = “Tomi” Tomi
Select the string
2 "Nintendo" 2.5
Select the only integer value
3.14 2 "Apple"
What’s this variable storing?
variable = 5/2
"2.5" - a string
2 - an integer
2.5 - a float
What will the code output?
a = "basket"
b = "ball"
print(a+b)
What's the value stored in the variable?
var = "360"
What would be the output?
print("360" + "360")
Problem
Modify the code to display a friendly message to the user
Task
Use string concatenation to join strings together and display a personalized friendly message
Problem
Modify the code to display a friendly message to the user
Task
Use string concatenation to join strings together and display a personalized friendly message
Input Example Output Example
name ="Abul" Nice to meet you, Abul
name ="Babul" Nice to meet you , Babul
age = 16
if age >= 18:
print("Regular price")
else:
print("Discount")
age = 30
if age >= 18:
print("Regular price")
else:
print("Discount")
print("Proceed to payment")
What will the code output?

You might also like