In [1]:
a = "55"
In [2]:
type(a)
Out[2]:
str
In [3]:
b = eval(a)
In [4]:
type(b)
Out[4]:
int
In [5]:
# Return the max between two numbers 
def max(num1, num2): 
    if num1 > num2:
        result = num1
    else:
        result = num2

    return result

def main():
    i = 5
    j = 2
    k = max(i, j) # Call the max function
    print("The maximum between", i, "and", j, "is", k)

main() # Call the main function
The maximum between 5 and 2 is 5
In [6]:
# Print grade for the score 
def printGrade(score):
    if score >= 90.0:
        print('A')
    elif score >= 80.0:
        print('B')
    elif score >= 70.0:
        print('C')
    elif score >= 60.0:
        print('D')
    else:
        print('F')

def main():
    score = eval(input("Enter a score: "))
    print("The grade is ", end = "")
    printGrade(score)

main() # Call the main function
Enter a score: 75
The grade is C
In [7]:
# Return the grade for the score 
def getGrade(score):
    if score >= 90.0:
        return 'A'
    elif score >= 80.0:
        return 'B'
    elif score >= 70.0:
        return 'C'
    elif score >= 60.0:
        return 'D'
    else:
        return 'F'

def main():
    score = eval(input("Enter a score: "))
    print("The grade is", getGrade(score))

main() # Call the main function
Enter a score: 65
The grade is D
In [8]:
# Print grade for the score 
def printGrade1(score):
    if score >= 90.0:
        print('A')
    elif score >= 80.0:
        print('B')
    elif score >= 70.0:
        print('C')
    elif score >= 60.0:
        print('D')
    else:
        print('F')
In [9]:
a = printGrade1(85)
B
In [10]:
print(a)
None
In [11]:
def sum(number1, number2):
    total = number1 + number2
print(sum(1, 2))
None
In [12]:
def sum(number1, number2):
    total = number1 + number2
    return total
print(sum(1, 2))
3
In [13]:
for i in range(1, 6 + 1):
    for j in range(6, 0, -1):
       print(j if j <= i else " ", end = " ")
    print()
          1 
        2 1 
      3 2 1 
    4 3 2 1 
  5 4 3 2 1 
6 5 4 3 2 1 
In [14]:
def nPrintln(message, n):
    for i in range(0, n):
        print(message)    
In [15]:
nPrintln("Welcome to Python", 5)
Welcome to Python
Welcome to Python
Welcome to Python
Welcome to Python
Welcome to Python
In [16]:
nPrintln(5, "Welcome to Python")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [16], in <cell line: 1>()
----> 1 nPrintln(5, "Welcome to Python")

Input In [14], in nPrintln(message, n)
      1 def nPrintln(message, n):
----> 2     for i in range(0, n):
      3         print(message)

TypeError: 'str' object cannot be interpreted as an integer
In [17]:
nPrintln(n = 4, message = "Computer Science")
Computer Science
Computer Science
Computer Science
Computer Science
In [27]:
def my_function(*kids):
    print("The youngest child is " + kids[4])
    
my_function("Emil", "Tobias", "Linus", "Ali", "Veli")
The youngest child is Veli
In [35]:
def my_function(**kid):
    print("Department name is " + str(kid["dname"]))
    print("His last name is " + str(kid["age"]))

my_function(fname = "Tobias", lname = "Refsnes", age = 20, dname = "Computer Eng.")
Department name is Computer Eng.
His last name is 20
In [36]:
y = lambda a,b : a ** b
In [37]:
y(2,3)
Out[37]:
8
In [39]:
def main():
    x = 1
    print("Before the call, x is", x)
    increment(x)
    print("After the call, x is", x)

def increment(n): 
    n += 10
    print("\tn inside the function is", n)
    

main() # Call the main function
Before the call, x is 1
	n inside the function is 11
After the call, x is 1
In [40]:
# Return the gcd of two integers 
def gcd(n1, n2):
    gcd = 1 # Initial gcd is 1
    k = 2   # Possible gcd

    while k <= n1 and k <= n2:
        if n1 % k == 0 and n2 % k == 0:
            gcd = k # Update gcd
        k += 1

    return gcd # Return gcd
In [41]:
# Prompt the user to enter two integers 
n1 = eval(input("Enter the first integer: "))
n2 = eval(input("Enter the second integer: "))

print("The greatest common divisor for", n1, "and", n2, "is", gcd(n1, n2))
Enter the first integer: 10
Enter the second integer: 15
The greatest common divisor for 10 and 15 is 5
In [55]:
# Convert a decimal to a hex as a string 
def decimalToHex(decimalValue):
    hex = ""
 
    while decimalValue != 0:
        hexValue = decimalValue % 16 
        hex = toHexChar(hexValue) + hex
        decimalValue = decimalValue // 16
    
    return hex
  
# Convert an integer to a single hex digit in a character 
def toHexChar(hexValue):
    if 0 <= hexValue <= 9:
        return chr(hexValue + ord('0'))
    else:  # 10 <= hexValue <= 15
        return chr(hexValue - 10 + ord('A'))

def main():
    # Prompt the user to enter a decimal integer
    decimalValue = eval(input("Enter a decimal number: "))

    print("The hex number for decimal", 
        decimalValue, "is", decimalToHex(decimalValue))
  
main() # Call the main function
Enter a decimal number: 29
The hex number for decimal 29 is 1D
In [46]:
#12 =     1 * 10 + 2 * 1
In [45]:
#536 --> 5 * 100 + 3 * 10 + 6 * 1
In [47]:
5 * (10**2) + 3 * (10 ** 1) + 6 * (10**0)
Out[47]:
536
In [48]:
2 * (16 ** 1) + 14 * (16 ** 0)   # 2E
Out[48]:
46
In [50]:
4 * (16 ** 2) + 0 * (16 ** 1) + 1 * (16**0) # 401 in hexadecimal
Out[50]:
1025
In [51]:
1 * 16 + 9    # 25 in decimal and 19 in hexadecimal
Out[51]:
25
In [53]:
25 % 16
Out[53]:
9
In [54]:
25 // 16
Out[54]:
1
In [58]:
chr(15 - 10 + ord('A'))
Out[58]:
'F'
In [61]:
ord("A") + 2
Out[61]:
67
In [62]:
ord("C")
Out[62]:
67
In [63]:
for i in range(5):
    print(i)
0
1
2
3
4
In [64]:
for i in range(5,10):
    print(i)
5
6
7
8
9
In [65]:
for i in range(5,20,3):
    print(i)
5
8
11
14
17
In [66]:
# print ("Compoted sin(" + str(x) + ")", sum, "math.sin(" + str(math.sin(x))  + "Difference =", sum - math.six(x))
In [68]:
globalVar = 1

def f1():
    localVar = 2
    print(globalVar)
    print(localVar)
    
f1()
print(globalVar)
print(localVar)  
1
2
1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [68], in <cell line: 10>()
      8 f1()
      9 print(globalVar)
---> 10 print(localVar)

NameError: name 'localVar' is not defined
In [71]:
x = 1
y = 5

def f1():
    x = 2
    y = 10
    print(x) # Displays 2
    print(y)

f1()

print(x) # Displays 1
2
10
1
In [73]:
x = eval(input("Enter a number: "))
if (x > 0):
    h = 4
print(h) # This gives an error if y is not created
Enter a number: -11
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [73], in <cell line: 4>()
      2 if (x > 0):
      3     h = 4
----> 4 print(h)

NameError: name 'h' is not defined
In [74]:
x = 1
def increase():
    global x
    x =  x + 1
    print(x) # Displays 2
    
increase()

print(x) # Displays 2
2
2
In [75]:
def printArea(width = 1, height = 2):
    area = width * height
    print("width:", width, "\theight:", height, "\tarea:", area)

printArea() # Default arguments width = 1 and height = 2
printArea(4, 2.5) # Positional arguments width = 4 and height = 2.5
printArea(height = 5, width = 3) # Keyword arguments width 
printArea(width = 1.2) # Default height = 2
printArea(height = 6.2) # Default widht = 1
width: 1 	height: 2 	area: 2
width: 4 	height: 2.5 	area: 10.0
width: 3 	height: 5 	area: 15
width: 1.2 	height: 2 	area: 2.4
width: 1 	height: 6.2 	area: 6.2
In [77]:
def sort(number1, number2):
    if number1 < number2:
        return number1, number2
    else:
        return number2, number1

n1, n2 = sort(2, 3)
print("n1 is", n1)
print("n2 is", n2)
n1 is 2
n2 is 3
In [78]:
from random import randint # import randint

# Generate a random character between ch1 and ch2
def getRandomCharacter(ch1, ch2):
    return chr(randint(ord(ch1), ord(ch2)))

# Generate a random lowercase letter
def getRandomLowerCaseLetter():
    return getRandomCharacter('a', 'z')

# Generate a random uppercase letter
def getRandomUpperCaseLetter():
    return getRandomCharacter('A', 'Z')

# Generate a random digit character
def getRandomDigitCharacter():
    return getRandomCharacter('0', '9')

# Generate a random character
def getRandomASCIICharacter():
    return getRandomCharacter(chr(0), chr(127))
In [79]:
#import RandomCharacter

NUMBER_OF_CHARS = 175 # Number of characters to generate
CHARS_PER_LINE = 25 # Number of characters to display per line

# Print random characters between 'a' and 'z', 25 chars per line
for i in range(NUMBER_OF_CHARS):
    print(getRandomLowerCaseLetter(), end = "")
    if (i + 1) % CHARS_PER_LINE == 0:
        print()  # Jump to the new line
kfukhlfsmajhnbgjanqosnzyz
kalgylgvydsjbpjgvphovwzcl
yfncztwezlsddmajhuquyjilb
spmflogadfppbiyclisffkpct
uctkdqbahrggjlngjbjdfkydh
tgwwzjoywrkqvvainvikzxugm
ciiadziojpfluhtcmvscnyhkh
In [80]:
ord("a")
Out[80]:
97
In [81]:
ord("z")
Out[81]:
122
In [82]:
chr(100)
Out[82]:
'd'
In [83]:
import math
In [84]:
math.sin(3)
Out[84]:
0.1411200080598672
In [87]:
math.sin(math.pi/2)
Out[87]:
1.0
In [89]:
# Print the calendar for a month in a year 
def printMonth(year, month): 
    # Print the headings of the calendar
    printMonthTitle(year, month)

    # Print the body of the calendar
    printMonthBody(year, month)
  
# Print the month title, e.g., May, 1999
def printMonthTitle(year, month): 
    print("         ", getMonthName(month), " ", year)
    print("-----------------------------")
    print(" Sun Mon Tue Wed Thu Fri Sat")

# Print month body 
def printMonthBody(year, month): 
    # Get start day of the week for the first date in the month
    startDay = getStartDay(year, month)

    # Get number of days in the month
    numberOfDaysInMonth = getNumberOfDaysInMonth(year, month)

    # Pad space before the first day of the month
    i = 0
    for i in range(startDay):
       print("    ", end = "")

    for i in range(1, numberOfDaysInMonth + 1):
        print(format(i, '4d'), end = "")

        if (i + startDay) % 7 == 0:
            print() # Jump to the new line

# Get the English name for the month
def getMonthName(month): 
    if month == 1:
        monthName = "January"
    elif month == 2:
        monthName = "February"
    elif month == 3:
        monthName = "March"
    elif month == 4:
        monthName = "April"
    elif month == 5:
        monthName = "May"
    elif month == 6:
        monthName = "June"
    elif month == 7:
        monthName = "July"
    elif month == 8: 
        monthName = "August"
    elif month == 9:
        monthName = "September"
    elif month == 10:
        monthName = "October"
    elif month == 11:
        monthName = "November"
    else:
        monthName = "December"

    return monthName

# Get the start day of month/1/year 
def getStartDay(year, month): 
    START_DAY_FOR_JAN_1_1800 = 3

    # Get total number of days from 1/1/1800 to month/1/year
    totalNumberOfDays = getTotalNumberOfDays(year, month)

    # Return the start day for month/1/year
    return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7

# Get the total number of days since January 1, 1800
def getTotalNumberOfDays(year, month): 
    total = 0

    # Get the total days from 1800 to 1/1/year
    for i in range(1800, year):
        if isLeapYear(i):
            total = total + 366
        else:
            total = total + 365

    # Add days from Jan to the month prior to the calendar month
    for i in range(1, month):
        total = total + getNumberOfDaysInMonth(year, i)

    return total

# Get the number of days in a month
def getNumberOfDaysInMonth(year, month): 
    if (month == 1 or month == 3 or month == 5 or month == 7 or
        month == 8 or month == 10 or month == 12):
        return 31

    if month == 4 or month == 6 or month == 9 or month == 11:
        return 30

    if month == 2:
        return 29 if isLeapYear(year) else 28

    return 0 # If month is incorrect

# Determine if it is a leap year
def isLeapYear(year): 
    return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)

def main():
    # Prompt the user to enter year and month 
    year = eval(input("Enter full year (e.g., 2001): "))
    month = eval(input(("Enter month as number between 1 and 12: ")))

    # Print calendar for the month of the year
    printMonth(year, month)
 
main() # Call the main function
Enter full year (e.g., 2001): 2022
Enter month as number between 1 and 12: 12
          December   2022
-----------------------------
 Sun Mon Tue Wed Thu Fri Sat
                   1   2   3
   4   5   6   7   8   9  10
  11  12  13  14  15  16  17
  18  19  20  21  22  23  24
  25  26  27  28  29  30  31
In [90]:
import turtle

# Draw a line from (x1, y1) to (x2, y2)
def drawLine(x1, y1, x2, y2):
    turtle.penup()
    turtle.goto(x1, y1)
    turtle.pendown()
    turtle.goto(x2, y2)

# Write a text at the specified location (x, y)
def writeText(s, x, y): 
    turtle.penup() # Pull the pen up
    turtle.goto(x, y)
    turtle.pendown() # Pull the pen down
    turtle.write(s) # Write a string

# Draw a point at the specified location (x, y)
def drawPoint(x, y): 
    turtle.penup() # Pull the pen up
    turtle.goto(x, y)
    turtle.pendown() # Pull the pen down
    turtle.begin_fill() # Begin to fill color in a shape
    turtle.circle(3) 
    turtle.end_fill() # Fill the shape

# Draw a circle at centered at (x, y) with the specified radius
def drawCircle(x, y, radius): 
    turtle.penup() # Pull the pen up
    turtle.goto(x, y - radius)
    turtle.pendown() # Pull the pen down
    turtle.circle(radius) 
    
# Draw a rectangle at (x, y) with the specified width and height
def drawRectangle(x, y, width, height): 
    turtle.penup() # Pull the pen up
    turtle.goto(x + width / 2, y + height / 2)
    turtle.pendown() # Pull the pen down
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)
In [91]:
import turtle
# from UsefulTurtleFunctions import *

# Draw a line from (-50, -50) to (50, 50)
drawLine(-50, -50, 50, 50)

# Write a text at (-50, -60)
writeText("Testing useful Turtle functions", -50, -60)

# Draw a point at (0, 0)
drawPoint(0, 0)

# Draw a circle at (0, 0) with radius 80
drawCircle(0, 0, 80)
    
# Draw a rectangle at (0, 0) with width 60 and height 40
drawRectangle(0, 0, 60, 40)

turtle.hideturtle()
turtle.done() 
In [98]:
a = "4"
In [99]:
b = "4.8"
In [100]:
c = "5 + 5.3 + 1"
In [101]:
eval(a)
Out[101]:
4
In [102]:
eval(b)
Out[102]:
4.8
In [103]:
eval(c)
Out[103]:
11.3
In [104]:
int(a)
Out[104]:
4
In [105]:
int(b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [105], in <cell line: 1>()
----> 1 int(b)

ValueError: invalid literal for int() with base 10: '4.8'
In [106]:
float(b)
Out[106]:
4.8
In [ ]: