Lecture Python2
Lecture Python2
Python function
Lectures Notes
For 1Styear, Civil Engineering, Faculty of Engineering, Al-Azhar
University
By, Dr. Eid F. Latif, PhD, Public Work Departement
Variables
In Python, a variable acts like a labeled container that stores data in your
program's memory. You can think of it as a box with a name where you
can keep different types of information, like numbers, text, or even
collections of data. Here's a breakdown of key points about variables in
Python:
1. Creating a Variable:
It's simply created the moment you assign a value to it. The assignment
uses the following syntax:
variable_name = value
For example, to store the number 10 in a variable named age, you would
write:
age = 10
2. Naming Conventions:
•Variable names can consist of letters (uppercase and lowercase),
numbers, and underscores (_).
•They cannot start with a number, and cannot be keywords reserved by
Python (like if, else, or for).
•It's recommended to use descriptive and meaningful names that
reflect the variable's purpose, improving code readability.
Variables
3. Assigning New Values:
•You can change the value stored in a variable by assigning a new value to it.
•For example, if age is 10, you can update it to 25:
age = 25
4. Using Variables:
•Once you have a variable, you can reference it by its name to use the stored
value in your code.
•This allows you to perform calculations, display information, or manipulate data
based on the variable's content.
•Examples:
•a, b, c=1, 2, 3
# Integer
age = 25
print("My age is:", age)
# Float
pi = 3.14159
print("The value of pi is:", pi)
# Boolean
is_happy = True
print("Am I happy? ", is_happy)
# List
fruits = ["apple", "banana", "orange"]
print("My favorite fruits:", fruits)
•Examples:
character_name = "Ahmed“
age = 30
print ("there was a boy called "+ character_name+ ", he was " +str(age)+ " years
old. ")
age = 50
print("but he wasn’t happy about being", age)
there was a boy called Ahmed, he was 30 years old.
but he wasn’t happy about being 50
Error
print ("there was a boy called "+ character_name+ ", he was " +age+ "
years old. " )
TypeError: can only concatenate str (not "int") to str
Comments
To convert the code to comment use Ctrl+/, this will appear as
#print(4) and prevent code from execution
You can include comment beside the code by adding # before the comment
print (3) # this will not be print
""" '''
This is not This is not
multiple multiple
line comments line comments
"""
Python function
Print
The print() function in Python is a built-in function that allows you to
display objects on the console.
These are the values you want to print. They can be strings, numbers,
variables, or any other data type.
sep (optional): This argument specifies the separator between the
objects being printed. By default, it's a space (" ").
end (optional): This argument determines what to print at the end of
the output. By default, it's a newline character (\n).
Examples:
# Print a simple string
print("Hello, world!") Code
Hello, world! Results
# Print multiple values on separate lines
print(10)
print(3.14)
10
3.14
# Print multiple values on a single line using commas
print("This", "is", "on", "a", "single", "line")
This is on a single line
Example: write a python codes to aske the user the following steps to generate
YouTube Channel Name
Welcome to the youTube Channel Name Generator:
What is your nickname? Eid
What is your channel about?
Python Programming
You could name your channel ' Python Programming with Eid '
you could name your channel Python Programming with Eid
Examples
data = [1, 2, 3]
print(type(data).__name__) # Output: list
data = "Hello"
print(type(data).__name__) # Output: str
data = False
print(type(data).__name__) # Output: bool
What are Strings?
Sequences of Characters: Strings are essentially ordered sequences of
characters used to represent text. Each character can be a letter, digit, symbol,
or whitespace.
Enclosed in Quotes: In Python, strings are enclosed in either single quotes ('),
double quotes ("), or triple quotes (''' or """). Triple quotes are mainly used for
multiline strings.
Immutable: Once a string is created, its contents cannot be modified. Any
operations that seem to modify a string actually create a new string.
original_string = "Hello"
# Trying to modify the original string will result in an error
# original_string[0] = 'M' # This will cause an error
modified_string = "M" + original_string[1:] # Create a new string
print(modified_string) # Output: Mello
Creating Strings
name = "Alice"
message = 'Hello, world!'
long_text = """This is a
multiline string"""
Accessing String Characters
my_string = "Python"
first_char = my_string[0] # Accesses the first character 'P'
last_char = my_string[-1] # Accesses the last character 'n'
print(first_char) # Output: P
print(last_char) # Output: n
String Slicing
Slicing allows you to extract a portion of a string based on specified indices. The syntax
is string[start:end:step]:
start: The index of the first character to include (inclusive). Defaults to 0 (beginning).
end: The index of the first character to exclude (exclusive). Defaults to the end of the
string.
step: The step value used to iterate through the characters. Defaults to 1 (includes every
character).
my_string = "Hello, world!"
# Extract characters from index 7 to 12 (excluding 13)
substring = my_string[7:12] # "world"
# Extract every other character (starting from index 0, default)
every_other = my_string[::2] # "Hlo ol!"
# Reverse the string (step of -1)
reversed_string = my_string[::-1] # "!dlrow ,olleH"
String operations:
Python offers various built-in functions and methods for working with strings. These include
concatenation (joining strings), finding the length, searching for substrings, formatting strings, and
more.
Concatenation: + operator
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print("Concatenation:", full_name) # Output: Alice Smith
Length: len(string) function
message = "Hello, world!"
length = len(message)
print("Length:", length) # Output: 13
Finding Substring: find(substring) method
text = "Hello, world!"
substring = "world"
print(text.find(substring)) # Output: 7
print(text.find("world")) # Output: 7
Formatting: String formatting f-strings
name = "Bob"
age = 30
print(f"Hello, {name}! You are {age} years old." )
Formatting:
.upper(): Returns a copy of the string with all letters uppercase.
.lower(): Returns a copy of the string with all letters lowercase.
.capitalize() : used to modify the case of the first character in a string.
.isupper(): Returns True if all characters in the string are uppercase, otherwise False.
. islower() Returns True if all characters in the string are lowercase, otherwise False.
.strip(): Returns a copy of the string with whitespace removed from the start and end.
replace(): Returns a new string with a substring replaced with another.
Example
text = "Hello, world!"
print(text.upper()) # Output: HELLO, WORLD!
print(text.lower()) # Output: hello, world!
print(text.capitalize()) # Output: Hello, world!
print(text.islower()) # Output: False
print(text.isupper()) # Output: False
print(text.lower().islower()) # Output: True
text2 = " Hello, world! "
print(text2.strip()) # Output: Hello, world!
print(text.replace("world", "Python")) # Output: Hello, Python!
Other useful methods
.split(): Splits a string into a list of substrings based on a delimiter (separator).
.join(): Joins elements of a list or tuple into a string using a specified
separator.
Example
sentence = "This is a string."
words = sentence.split() # Split by spaces
print(words) # Output: ['This', 'is', 'a', 'string.']
• Write Python code to calculate the worker's wages for painting the ceiling of a
room.
• # Get room dimensions from user
• room_length = float(input("Enter the length of the room in meters: "))
• room_width = float(input("Enter the width of the room in meters: "))
• # Get wage per square meter from user
• wage_per_sqm = float(input("Enter the wage per square meter in
dollars: "))
• # Calculate the area of the room area = room_length * room_width
• area=room_length*room_width
• # Calculate the total wages
• total_wages = area * wage_per_sqm
• # Print the result
• print(f"The worker's wages for painting the room are: ${total_wages}")
• Enter the length of the room in meters: 5.5
• Enter the width of the room in meters: 6.5
• Enter the wage per square meter in dollars: .5
• The worker's wages for painting the room are: $17.875
Programming Assignment: Time Converter
Write a Python program that converts a given number of minutes
into hours and remaining minutes.
• Total_minutes=int(input("please type the number of minutes:\n"))
• hours=Total_minutes//60
• minutes=Total_minutes%60
• print("This course is: "+str(hours)+" hours and "+ str(minutes)+ " minutes
long ")
• please type the number of minutes:
• 623
• This course is: 10 hours and 23 minutes long