Tuesday, October 16, 2018

Strings, Lists, Files

String stuff

#strings, Lists, files
def main():
    mystring='This has already been a long morning.'
    print ('there are',len(mystring),'characters')
    print ('the 12th character is',mystring[12])
    for c in range(len(mystring)):
        print(mystring[c])
    midstring=mystring[9:17]
    print (midstring)
    wordlist=mystring.split()
    print(wordlist)
    print(wordlist[5])
    for w in range(len(wordlist)):
        print(wordlist[w])
    mystring=mystring.upper()
    print(mystring)
    mystring=mystring.lower()
    print(mystring)
    mystring=mystring.title()
    print(mystring)
    print (ord('a'))
    print (ord('A'))
    print(chr(97))
    print(chr(475))
    daylist='sun,mon,tue,wed,thurs,fri,sat'
    days=daylist.split(",")
    print(days)


main()

ListExamples

#Lists
def main():
    numbers=[1,37,4,4,2,1,9,10]
    sum=0
    for i in range(0,len(numbers)):
        sum += numbers[i]
    average=sum/len(numbers)
    print('the total is', sum, '\n' + 'the average is', average)

    mylist=[]
    for i in range(5):
       word=input("Enter a word: ")
        mylist.append(word)
    print(mylist)

    testgrade=[]
    num = int(input("How many grades: "))
    total=0
    
    for g in range(num):
        grade=float(input("Enter grade: "))
        testgrade.append(grade)
    
    print(testgrade)
    for g in range(0,len(testgrade)):
        total += testgrade[g]
    avg=total/len(testgrade)
    print("the average grade is", avg )

main()

FileExamples.py

#write and read a file
def main():
    outfile=open("C:\\temp\\outfile.txt", "w")
    print("this is my first sentence", file=outfile)
    print("this is my second sentence", file =outfile)
    outfile.close()

    infile=open('C:\\temp\\outfile.txt','r')
    for line in infile:
        print(line)
    infile.close()

main()

No comments:

Post a Comment