Homework 5-7
Below is an example of decimal number to binary converter which you can use as a starting template.
def DecimalToBinary(num):
strs = ""
while num:
# if (num & 1) = 1
if (num & 1):
strs += "1"
# if (num & 1) = 0
else:
strs += "0"
# right shift by 1
num >>= 1
return strs
# function to reverse the string
def reverse(strs):
print(strs[::-1])
# Driver Code
num = 67
print("Binary of num 67 is:", end=" ")
reverse(DecimalToBinary(num))
Notes
- Inequalities are normal (= is after <> things for equal/less than) (!= is unequal)
- boolen is similar to binary, its just true or false
- operators
- conditions affects the flow of a program and can alow things only when a requirement is met
- if/else or if/elif/else
- nested conditionals are conditionals within a conditional
print("True:",4 == 4)
print("True:",1 != 0)
print("False:",7 == 3)
print("True:",5 != 6)
print("False:",7 == 8)
print("True:",3 == 3)
print('why is this empty?')
# Same as above, but now for other values other than int
print('True:',"as"=="as")
print("False:",True == False)
print("False:",[2,3,1]!=[2,3,1])
print("True:",'af'!='bc')
print("False:",'ce'=='cf')
print("True:",[1,'b']!=[1,'a'])
print('why is this empty too?')
print("True:", True or False)
print("False:", not True)
print("True:", True and True)
print("False:", not True)
print("False:", True and False)
print("True:", not False)
print( 3 3 4 6 5 7)
number = 7
if number == 5:
print("5")
else:
print("not 5")
if number <= 3:
print("less than 3")
else:
print("not less than 3")
if number <= 7:
print("less than 7")
else:
print("not less than 7")
if number > :
print("big")
else:
print("7")
def convert(temp):
value = []
temp = float(temp)
i = 0
while temp > 0:
if temp % 2 == 0:
value.append(0)
temp = temp / 2
else:
value.append(1)
temp = temp /2
temp = temp - 0.5
i = i + 1
final = ""
x = len(value) - 1
print("This number is",x+1,"binary digits long.")
print("This means that your number is",x+1,"bit.")
while x >= 0:
final = final + str(value[x])
x = x - 1
print(final)
ssalcsihtetahi = input("Type a number.")
print(ssalcsihtetahi)
convert(ssalcsihtetahi)