0% found this document useful (0 votes)
2 views

lecture3

Uploaded by

abdoelraheman28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lecture3

Uploaded by

abdoelraheman28
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lecture:4

Python Numbers and Conditionals

Lectures Notes
For 1Styear, Civil Engineering, Faculty of Engineering, Al-Azhar
University
By, Dr. Eid F. Latif, PhD, Public Work Departement
 Python number
 Python offers various operations and functions to work with numbers.
a=5+3 #Addition
b=10-4 # Subtraction
c=4*6 # Multiplication
d=9/10 # Division
e=9/2 # Floor Division (//) divides and returns the whole number part of the
result (integer).
f=10 % 3 #Modulo (%) gives the remainder after a division operation.
g=5**2 #Exponentiation (**) raises a number to a power (=5^2)
h=(3+(4*5)) #Python follows the order of operations just like math
print(a, b, c, d, e, f, g, h)
a b c d e f g h
8 6 24 0.9 4.5 1 25 23
x=10
y=20
x=x+y or x +=y # x -=y # x *=y # x /=y ------etc
print(x)
 Comparison Operations: These operations compare values and return
boolean (True or False)
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
print(5 == 3) # False

age=26
country = "Egypt"
rank = 10
print(not age < 16 and country == "Egypt" or rank >0) # True
 Other Number Functions:
#abs(x) returns the absolute value (positive version) of a
number.
print(abs(-5)) #5
#max(x, y,---) returns the larger of numbers.
print(max(5,3,7)) #7
#min(x, y, ----) returns the smaller of numbers.
print(min(5, 3,-1)) # -1
#round(x, n) rounds a number to a specified number of
decimal places (n defaults to 0).
print(round(3.14159, 2)) # 3.14
#pow(x, n) The pow(x, n) function in Python calculates the
power of a number, just like x**n.
print(pow(2,3)) #8
 Import from python library
#from math import * : This will import all functions from the math module in
Python. The math module provides various mathematical functions,
from math import *
print(floor(3.7)) # returns the smallest integer number #3
print(ceil(3.7)) # returns the largest integer number #4
print(sqrt(4)) # calculates the square root of a number #2
print(pi) #3.141592653589793
print(radians(60)) #radians(x): Converts angle from degrees to radians.
print(sin(60))#sin(x): Returns the sine of x in radians.
print(log(5))#log(x, base=None): Returns the logarithm of x to the given
base. If base is not specified, returns the natural logarithm (base e).
print(log10(5))#log10(x): Returns the base-10 logarithm of x.=log(5,10)
 If Conditional
 Conditional statements, also known as if-else statements, are fundamental
control flow structures in Python. They allow your code to make decisions based
on whether a condition is True or False.

if condition: This line introduces the conditional statement


# Code to execute if the condition is True
else:
# Code to execute if the condition is False
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
 In conditional statements, you can use the elif keyword (short for "else if") to create multiple
checks.
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
# ... more elif statements
else:
# Code to execute if all conditions are False
#Example: grade level
grade =input("Enter your letter grade (A, B, C, D, or F): \n").upper()
if grade == 'A' or grade =='B': # True, False, or, and, not, and not, in, not in may be used
print("Excellent work!") You can use either Code to achieve the desired
elif grade == 'C': if grade in ('A', 'B'): # Use 'in' to check for membership in the tuple
print("Very good!")
elif grade == 'D':
print("Good effort!")
elif grade == 'F':
print(" You may want to study more.")
else:
print("Wrong input, try again.")
#Example: user name and password
name =input("please enter your name: ")
password=input("please enter your password: ")
if name.lower() == "ibrahim" and password=="hiThere":
print("Welcome back!")
else:
print("Sorry, wrong name or password")
#Example: driving license
age =int(input("please enter your age: "))
license=input("Do you have a license? Type (Yes) or (No)")
if age >= 18 and license.lower() == "yes":
print("You can drive")
elif age < 18 or license.lower() == "no":
print("Sorry, you cannot drive")
else:
print(f"Sorry, your entry of [{license}] is not understood")
 Nested if: Nested if statements allow you to create more complex decision-making logic in
your Python code.
#Example: ID
is_egyptian =input("Are you Egyptian? ‘yes’ or ‘no’ ").lower()
if is_egyptian =="yes":
print("Good, that’s the first step")
is_18=input("Are you above 18? Type ‘yes’ or ‘no’ ").lower()
if is_18=="yes":
print("You can have an ID")
else:
print("""Sorry, you have to be 18 or older
Please try again when you are 18""")
else:
print("Sorry, an Egyptian ID is give only to Egyptians")
Example: Calculator
try: #try block: This block contains the code that you suspect might raise an exception (an error condition)
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ValueError: #except block specifies an exception type (e.g., ValueError, IndexError, etc.).
print("Invalid input. Please enter numbers only.")
exit() # Exit the program on invalid input
# Get the operator from the user
operator = input("Enter an operator (+, -, *, /): ")
# Check for valid operator
if operator not in ["+", "-", "*", "/"]:
print("Invalid operator. Please use +, -, *, or /.")
exit() # Exit the program on invalid operator
# Perform the calculation
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
else: # Division case
if num2 == 0:
print("Error: Cannot divide by zero.")
exit() # Exit the program on division by zero
result = num1 / num2
# Print the result
print("The result is:", result)
 Ternary conditional operator
The ternary conditional operator in Python provides a concise way to write an if-else
statement in a single line

#Example:
age =int(input("how old are you?"))
is_adult = age >= 18 # True or False based on age
# Ternary conditional operator version
print("You are an adult" if is_adult else "You are not an adult")
# Output: "You are an adult"
#Example: ID
is_egyptian =input("Are you Egyptian? ‘yes’ or ‘no’ ").lower()
is_18=input("Are you above 18? Type ‘yes’ or ‘no’ ").lower()
print("Good, You can have an ID" if is_egyptian =="yes" and is_18== "yes"
else " Sorry, you have to be 18 or older and an Egyptian ID is give only to
Egyptians")

You might also like