import random as rnd
answer = rnd.randint(1,8)
#This is a single line comment
""" This is
a multiline
comment"""
firstString = "Ahmed's book is here"
secondString = 'I "gave" the book to Ahmed'
x = True
y = False
Operator | Description | Example |
---|---|---|
+ | Addition | 1 + 1 = 2 |
- | Subtraction | 10 - 1 = 9 |
* | Multiplication | 3 * 5 = 15 |
/ | Division | 10 / 5 = 2 |
% | Modulus (remainder) | 11 % 5 = 1 |
** | Exponent | 3 ** 2 = 9 |
// | Floor division | 11 // 5 = 2 |
Operator | Meaning |
---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | Equal to |
!= | Not equal to |
is | Object identity |
is not | Negated object identity |
Operator | Code Example | What It Determines |
---|---|---|
or | x or y | Either x or y is True |
and | x and y | Both x and y are True |
not | not x | x is not True |
x = 10 # Assigning the value 10 to variable x
#Using line breaks
first_name = "Ahmed"
last_name = "Harbi"
#Using semicolon
first_name = "Ahmed"; last_name = "Harbi"
Built-in Function | Purpose |
---|---|
abs(x) | returns absolute value |
bin(x) | Returns a string with the value of x in binary |
float(x) | Converts a string or number to the float data type |
format(x, y) | Returns x formatted according to pattern in y |
hex(x) | Convert x to hexadecimal, prefixed with 0x |
int(x) | Converts x to integer by truncating the decimal portion |
max(x, y, z,...) | Return the largest number |
min(x, y, z, ...) | Return the smallest number |
oct(x) | Convert x to octal number, prefixed with 0o |
round(x, y) | Rounds x to y number of decimal places |
str(x) | Converts x from number to string |
type(x) | Returns a string indicating the data type of x |
Function | Purpose |
---|---|
math.acos(x) | arccosine x in radians |
math.atan(x) | arctangent of x in radians |
math.atan2(y, x) | Converts rectangular coordinates (x,y) to polar coordinates (r,theta) |
math.ceil(x) | ceiling of x, smallest integer greater than or equal x |
math.cos(x) | cosine x |
math.degrees(x) | Convert angle x from radians to degrees |
math.e | mathematical constant e |
math.exp(x) | e raised to the power x |
math.factorial(x) | factorial of x |
math.floor(x) | floor of x, largest integer less than or equal to x |
math.isnan(x) | True if x is not a number |
math.log(x,y) | logarithm of x to base y |
math.log2(x) | base-2 logarithm of x |
math.pi | The mathematical constant pi (3.14..) |
math.pow(x,y) | x raised to the power y |
math.radians(x) | convert angle x from degrees to radians |
math.sin(x) | sine of x |
math.sqrt(x) | square root of x |
math.tan(x) | tangent of x |
math.tau() | mathematical constant tau (6.283185...) |
username = "Mohammed"
print(f"Hello {username})
quantity = 100
unit_price = 14.997
print(f"Subtotal: ${quantity * unit_price:,.2f}")
sales_tax_rate = 0.065
print(f"Sales Tax Rate {sales_tax_rate:.2%}")
user1 = "Ahmed"
user2 = "Mohammed"
user3 = "Hussam"
output = f"{user1}\n{user2}\n{user3}"
print(output)
user1 = "Ahmed"
user2 = "Mohammed"
user3 = "Hussam"
output = f"""{user1}
{user2}
{user3}"""
print(output)
subtotal = 1598.40
sales_tax = 103.90
total = 1702.30
print(f"""
Subtotal: ${subtotal:>9,.2f}
Sales Tax: ${sales_tax:>9,.2f}
Total: ${total:>9,.2f}
""")
Subtotal: $ 1,598.40 Sales Tax: $ 103.90 Total: $ 1,702.30
System | Also Called | Digits Used | Symbol | Function |
---|---|---|---|---|
Base 2 | Binary | 0,1 | 0b | bin() |
Base 8 | Octal | 0,1,2,3,4,5,6,7 | 0o | oct() |
Base 16 | Hexadecimal | 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F | 0x | hex() |
x = 255
print(bin(x))
print(0b11111111)
0b11111111 255
print("My" + " " + "name" + " " + "is" + " " + "Mohammed")
My Name is Mohammed
s1 = ""
s2 = " "
s3 = "A B C"
print(len(s1))
print(len(s2))
print(len(s3))
0 1 5
Operator | Purpose |
---|---|
x in s | True if x exists in string s |
x not in s | True if x is not in string s |
s * n (or n * s) | Repeats s n times |
s[i] | Returns the ith item of string s |
s[i:j] | A slice from string s from position i until j |
s[i:j:k] | A slice of s from i to j with step k |
min(s) | Returns the smallest character in s |
max(s) | Returns that largest character in s |
s.index(x,[i,j]) | The numeric position of the first occurrence of x in string s. i and j are optional limits to the search from i to j |
s.count(x) | The number of times x appears in s |
Method | Purpose |
---|---|
s.capitalize() | capitalize the first letter and the rest lowercase |
s.count(x, [y, z]) | The number of times x appears in s from position y to z |
s.find(x, y, z) | Returns a number indicating the first position where x can be found in s from position y to z |
s.isalpha() | True if s at least has one character and contains only letters |
s.isdecimal() | True if s is at least one character long and contains only numeric characters |
s.islower() | True if all letters are lowercase |
s.isnumeric() | True if s is at least one character long and contains only numeric characters |
s.isprintable() | True if string s contains only printable characters |
s.istitle() | True if s contains letters and the first letter of each word is uppercase followed by lowercase |
s.isupper() | True if all letters are uppercase |
s.lstrip() | Returns s without leading space |
s.replace(x, y) | Returns a copy of string s with all x characters replaced with y |
s.rfind(x, y, z) | Searches backward from end of string, or from z to y. returns -1 if substring not found |
s.rindex() | Same as s.rfind() but returns an error if substring not found |
s.rstrip() | removes tailing spaces |
s.swapcase() | Converts uppercase to lowercase and vice versa. |
s.strip() | Remove leading and trailing spaces |
s.title() | Return s string with the first letter of each word in uppercase and other letters in lowercase |
s.upper() | Returns string with all letters in uppercase |
import datetime as dt
today = dt.date.today()
test_day = dt.date(2024, 9, 7)
print(today)
print(test_day)
print(test_day.month)
print(test_day.day)
print(test_day.year)
2024-12-22 2024-09-07 9 7 2024
Directive | Description | Example Output |
---|---|---|
%a | Weekday, abbreviated | Sun |
%A | Weekday, full | Sunday |
%w | Weekday number 0-6, 0 is Sunday | 0 |
%d | Number of day of the month 01-31 | 31 |
%b | Month name abbreviated | Jan |
%B | Month name full | January |
%m | Month number 0-12 | 01 |
%y | Year without century | 24 |
%Y | Year with century | 2024 |
%H | Hour 00-23 | 22 |
%I | Hour 00-12 | 11 |
%p | AM/PM | PM |
%M | Minute 00-59 | 03 |
%S | Second 00-59 | 45 |
%f | Microsecond 000000-999999 | 236478 |
%z | UTC offset | -0500 |
%Z | Time zone | EST |
%j | Day number of year 001-366 | 300 |
%U | Week number of year, Sunday first day of week, 00-53 | 50 |
%W | Week number of year, Monday first day of week, 00-53 | 50 |
%c | Local version of date and time | Tue Dec 21 23:59:45 2024 |
%x | Local version of date | 12/22/2024 |
%X | Local version of time | 22:16:59 |
%% | A % character | % |
Format string | Example |
---|---|
%a, %b %d %Y | Sun, Dec 22 2024 |
%m-%d-%y | 12-22-24 |
This %A %B %d | This Sunday December 22 |
%A %B %d is day number %j of %Y | Saturday June 01 is day number 152 of 2019 |
variablename = datetime.time(hour, minute, second, microsecond)
Format String | Example |
---|---|
%I:%M %p | 11:59 PM |
%H:%M%S and %f microseconds | 23:59:59 and 129384 microseconds |
%X | 23:59:59 |
import datatime as dt
print(dt.datetime.now())
2024-12-22 10:00:40.800331
Format String | Example |
---|---|
%A, %B %d at %I:%M%p | Tuesday, December 31 at 11:45PM |
%m/%d/%y at %H:%M | 12/22/24 at 22:36 |
%I:%M %p on %b %d | 11:59 PM on Dec 31 |
%I:%M %p on %m/%d/%y | 1:59 PM on 12/31/19 |
import datetime as dt
here_now = dt.datetime.now()
utc_now = dt.datetime.utcnow()
time_difference = (utc_now - here_now)
print(f"My time : {here_now: %I:%M %p}")
print(f"UTC time : {utc_now: %I:%M %p}")
print(f"Difference: {time_difference}")
My time : 01:02 PM UTC time : 06:02 PM Difference: 5:00:00
Operator | Meaning |
---|---|
== | Is equal to |
!= | Is not equal to |
< | Is less than |
> | Is greater than |
<= | Is less than or equal to |
>= | Is greater than or equal to |
Operator | Meaning |
---|---|
and | Both are true |
or | One of the other is true |
not | Is not true |
if condition: do this
do this no matter what
if x == 0:
x = x +1
print("This line will also execute")
print("This line is also part of the if statement block")
print("This line is not part of the block")
if x > 5:
print("This will only be printed if condition is true.")
else:
print("This will only be printed if condition is false.")
if name == "Ahmed":
print("Hi Ahmed")
elif name == "Mohammed":
print("Hi Mohammed")
elif name == "Hussam":
print("Hussam is eating Fish!")
else:
print("The last else is optional")
for x in range(y):
do this
do this
...
un-indented code will execute after the loop is complete
for x in range(3):
print(x)
print("All done")
0 1 2 All done
for x in range(1, 4):
print(x)
print("All done")
1 2 3 All done
name = "Ahmed"
for x in name:
print(x)
print("Done")
A h m e d Done
for x in ["My", "name", "is", "Mohammed"]:
print(x)
print("Done")
My name is Mohammed Done
for x in range(5):
if x == 3:
break
print(x)
print("Done")
0 1 2 Done
for x in range(5):
if x == 3:
continue
print(x)
print("Done")
0 1 2 4 Done
for x in ["First", "Second", "Third"]:
print(x)
for y in range(1, 4):
print(y)
print("both loops are done")
First 1 2 3 Second 1 2 3 Third 1 2 3 both loops are done
counter = 5
while counter < 11:
print(counter)
counter += 1
5 6 7 8 9 10
counter = 0
while counter < 6:
counter += 1
if counter == 3:
continue
print(counter)
1 2 4 5 6
counter = 0
while counter < 6:
if counter == 4:
break
print(counter)
counter += 1
0 1 2 3