CSNT 110: Exam 1-2

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

refer to lab10.py

""" lab10.py - Jane Doe Ask user to enter name of file to process, store as infilename Open infilename for reading, store handle as infile Replace ".csv" with ".xml" in infilename, store as outfilename Open outfilename for writing, store handle as outfile Read all line from infile, store as list called lines For each line in lines Strip line, split line on ",", store as tokens Store tokens[0] as name Store tokens[1] as gender Convert tokens[2] using float(), store as height Convert tokens[3] using float(), store as weight Write to outfile ' <subject>\n' Write to outfile ' <name>' + name + '</name>\n' If gender is 'm' height = height - 1 weight = weight + 10 Write to outfile ' </subject>\n' Print name """

numlist = [4.4, 3.3, 1.1, 2.2, 5.5] #know we will need total total = 0.0 #step 2 lowest = numlist[0] #step 3 highest] highest = numlist[0] #do for loop averaage first for num in numlist: total += num #2 check for lowest num if((num)< lower): lowest = num if((num)> highest): highest = num print (numlist) if ((len(numlist)) > 0): average = total + / len(numlist) else: average = 0 #lowest: find lowerest number, take first element assume smallest num print("average is ", average) print("lowest is ", lowest) refer to examreview.py

""" Given a list of floats, write code that displays the average, lowest, and highest number """ numlist = [4.4, 3.3, 1.1, 2.2, 5.5]

infile = open("scores.txt", "r") lines = infile.readlines() #going to take the elements and put them in a list #print(lines) #print(len(lines)) #want to break up the elements in the list for line in lines: #print(line.strip()) #do this to know #what youre working with pieces = line.strip().split(",") print(pieces) name = pieces #add all the elements then loop # though for a total total = 0 for i in range(1, len(pieces)): #for everyone of those numbers #you want to add them to the #pieces total += float(pieces[i]) average = total / len(pieces) - 1 print(name, "average score is : ", average) infile = close() refer to lists.py

""" Write a program that can process the following input file, "scores.txt". This file has a the student's name, followed by his/her exam scores. The student's don't all have the same number of exams. Jane,94,91,92 John,78,88,72 Bill,50,100 You want your program to produce the following output to the screen, when your program is run: Jane average score is: 92.33 John average score is: 79.33 Bill average score is: 75.00 """

True True True False

# Logical 'or' - binary operator # requires at leat one to be true to make the overall statement true print(True or True) print(True or False) print(False or True) print(False or False)

def perimeter(width, length): return 2 * (width + length) print("Perimeter =", perimeter(w,l))

# The perimeter function accepts a rectangle's width # and length as arguments and returns the rectangle's # perimeter.

True False False False

# logical 'and' - requires two input # Only true if both inputs are true print(True and True) print(True and False) print(False and True) print(False and False)

True False False True

# not operator print(True) print(False) print(not(True)) print(not(False))

str

'Hawaii' what type of variable is this?

not, and, or

3 types of logical operators

float

3.1428 what type of variable is this?

int

72 what type of variable is this?

i = 1 bugs = 0 while i < 6: bugs = int(input('enter the amount of bugs collected today:')) + bugs average = bugs / 5 i+=1 print('average amount of bugs collected in a week is:', average)

A bug collector collects bugs every day for five days. Write a program that keeps a running total of the number of bugs collected during the five days. The loop should ask for the number of bugs collected for each day, and when the loop is finished, the program should display the total number of bugs collected.

temporarily holds items in memory, until those items can be processed.

A stack process on a computer is a process that

insert()

Adds an element at the specified position

favNum = input("Enter your favorite number: ") favNum = int(favNum) if (favNum == 7): print("That is my favorite number too!") else: print("That is a nice number.")

Ask for user's favorite number, store as favNum Convert favNum into a number, store as favNum If favNum is 7 Print "That is my favorite number too!" Else Print "That is a nice number."

favNum = input("Enter your favorite number: ") favNum = int(favNum) if (favNum == 7): print("That is my favorite number too!") print("It has always been a lucky number for me") elif (favNum < 0): print("Your favorite number is negative") print("Most people are more positive") elif (favNum >= 0 and favNum < 7): print("Your favorite number is",favNum) print("That is a nice number.") elif (favNum > 7): print("Your favorite number is",favNum) print("That is a nice number.")

Ask for user's favorite number, store as favNum Convert favNum into a number, store as favNum If favNum is 7 Print "That is my favorite number too!" Print "It has always been a lucky number for me" Else If favNum is less than 0 Print "Your favorite number is negative" Print "Most people are more positive" Else If favNum is greater or equal to zero and less than 7 Print "Your favorite number is",followed by favNum Print "That is a nice number." Else If favNum is greater than 7 Print "Your favorite number is",followed by favNum Print "That is a nice number."

i = 1 while i < 6: print(i) i = i + 1

Assign i the value of 1. Print i as long as i is less than 6.

i = 1 while i < 6: if (i == 3): i += 1 continue; print (i) i += 1

Assign i the value of 1. Print i as long as i is less than 6. In the loop, when i is 3, jump directly to the next iteration.

i = 1 while i < 6: if (i ==3): break; i += 1 print (i) else: print ("while condition is false") print("the end")

Assign i the value of 1. Print i as long as i is less than 6. Print a message once the condition is false.

i = 1 while i < 6: if i == 3: break; print (i) i += 1

Assign i the value of 1. Print i as long as i is less than 6. Stop the loop if i is 3.

if "Jane" in nameList: print("Found it") else: print("Not found")

Assuming that you have list of names called nameList . Write some code that would print "Found it" to the screen if "Jane" is in nameList , and print "Not found" if "Jane" is not in nameList .

<?xml-stylesheet rel="stylesheet" href="cssfilename" ?>

CSS declaration header for xml:

num = randint(1,10) playing=True while(playing==True): guess = input("Enter your guess between 1 and 10: ") guess = int(guess) if(guess==num): print("You made the right guess") playing=False else: print("Incorrect guess") print("Game over!")

Consider the following game in which you are guessing a number picked by the computer. The computer first picks a number between 1 and 10 using the randint() function. We then ask the user for their guess and provide the user with the right feedback. use a loop.

i is 0 j is 1 i is 0 j is 2 i is 0 j is 3 i is 1 j is 1 i is 1 j is 2 i is 1 j is 3 i is 2 j is 1 i is 2 j is 2 i is 2 j is 3

Consider the following program. On scratch paper, analyze the program and write down the output that you think the program will produce: for i in range(0,3): for j in range(1,4): print("i is" , i, "j is" , j )

for number in range(4, 9, 2): print (number * 10) print()

Convert the following loop into for loop : x = 4 while(x<=8): print(x*10) x+=2

my_fruits = ['apple', 'banana', 'cherry'] my_fruits.append('orange')

Create a list called my_fruits that contains the following fruits: apple, banana, cherry. then add the fruit "orange" to the end of the my_fruits

yes, because lists are indexed you can have multiple items with the same value

Do lists allow duplicates?

major = input("Enter major: ") print("You entered "+major) credits = input("Enter credits earned: ") print("Your credits are "+credits) print(type(credits))

Enter major: csnt You entered csnt Enter credits earned: 30 Your credits are 30 <class 'str'> what is the input?

speed = float(input("Enter speed: ")) d=400 time = 0 if(speed!=0): time = d/speed print("Inside if statement") print(time)

Enter speed: 40 Inside if statement 10.0 (d=400 and time=0)

name = input("Enter your name: ") print(name)

Enter your name: jessi pimiento jessi pimiento what is the input?

def mini (num1, num2): #pass #step 1: put pass as a place holder #return 0 #step 3 if num1 < num2: smallest = num1 else: smallest = num2 return smallest #step 5 number1 = int(input("enter first number: ")) #step 2 number2 = int(input("enter second number: ")) print("the smallest of ", number1 "and" number2 "is", mini(number1, number2))

Exercise 3: Write a function named mini() that accepts two integer values as arguments and returns the value that is the smallest of the two. For example, if 7 and 12 are passed as arguments to the function, the function should return 7. Use the function in a program that prompts the user to enter two integer values. The program should display the value that is the smallest of the two.

The file must have the declaration header and a root element. The elements must be properly nested so that the start and end tags of an element match up.

For an XML file to be valid, two things have to be true

The file must have the declaration header and a root element. The elements must be properly nested so that the start and end tags of an element match up.

For an XML file to be valid, two things have to be true:

the value stored in position 0 is jane the value stored in position 1is john the value stored in position 2 is bill

For loop to process the list by iterating over the index: names = ['jane', 'john', 'bill'] for i in range(0,3): print("the value stored in position "+str(i)+" is "+names[i]) what is the output:

len() function

How do you determine how many items a list has?

factorial = 1 number = int(input("Enter a nonnegative number: ")) for x in range (1,number + 1 ): factorial = factorial * x print ("factorial of", number, "is", factorial)

In mathematics, the notation n! represents the factorial of the nonnegative integer n. The factorial of n is the product of all the nonnegative integers from 1 to n. For example, 7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5,040 and 4! = 1 x 2 x 3 x 4 = 24 Write a program that lets the user enter a nonnegative integer then uses a loop to calculate the factorial of that number and displays the factorial.

classification = input("Enter your classification: ") classification = classification.lower() classification = classification.strip() if(classification =='freshman'): print("freshman case") print("done")

In this program, we ask for the classification of the student and based on that input, if the student is a freshman then it will print freshman case output: Enter your classification: freshman freshman case done

classification = input("Enter your classification: ") classification = classification.lower() classification = classification.strip() scholarship=0 if(classification =='freshman'): print("freshman case") scholarship = 1000 else: print("non-freshman case") scholarship = 500 print(scholarship) print("done")

In this program, we ask for the classification of the student and based on that input, if the student is a freshman then it will print freshman case. Now suppose you have two cases - freshman and non-freshman and you want to write code to handle both cases. In the above code, we give different value to scholarship variable based on what user enters for classification. If user enters "freshman" then scholarship is set to 1000. For all other inputs, scholarship is set to 500. The ELSE portion covers all cases that are non-freshman. output: Enter your classification: undeclared non-freshman case 500 done

print(names[0]) print(names[1]) print(names[2])

Items of a list are accessed via index which always starts at 0. print the names in names list names = ['jane', 'john', 'bill'] output: jane john bill

count=0 while(count<5): print(count) count +=1 else: print("count value reached %d" %(count))

Prints out 0,1,2,3,4 and then it prints "count value reached 5"

for i in range(1, 10): if(i%5==0): break print(i) else: print("this is not printed because for loop is terminated", end=" ") print("because of break but not due to fail in condition")

Prints out 1,2,3,4

fruits.pop(1)

Remove the second element of the fruit list: fruits = ['apple', 'banana', 'cherry'] output: ['apple', 'cherry']

pop()

Removes the element at the specified position

remove()

Removes the item with the specified value

import random print(random.randint(3, 9))

Return a number between 3 and 9

x = fruits.pop(1) print(x)

Return the removed element: fruits = ['apple', 'banana', 'cherry'] output: banana

index()

Returns the index of the first element with the specified value

(num >= 1) and (num < 5)

Suppose you have a variable called num and you want to test to see if num is between 1 (inclusive) and 5 (exclusive). Write the boolean expression that would be true if num is in this range.

(num > 0) and ((num % 2) == 1)

Suppose you have an integer variable called num and you want to write a boolean expression that is true if num is positive and num is odd. Write that expression.

False. You can not combine a str and and int. you can only combine the same variable types

T/F this is a correct print("Value of y is " + y)

capitalize()

The _____ function causes the first letter of the first word to be in uppercase form.

strip()

The ______ function strip off all leading and trailing whitespace

title()

The ____function causes the first letter of every word to be in uppercase form.

def area(radius): area = math.pi **2 return area print("the area of the circle with radius", r, "is", a)

The circle module has functions that perform calculations related to circles. import math The area function accepts a circle's radius as an argument and returns the area of the circle.

def circumferance(radius): c = 2 * radius* math.pi return c print("the area of the circle with radius", c, "is", r)

The circumference function accepts a circle's # radius and returns the circle's circumference.

def area (width,length): area = width * length return area print("Area = ", area(w,l))

The rectangle module has functions that perform # calculations related to rectangles. # The area function accepts a rectangle's width and # length as arguments and returns the rectangle's area

relational operators

These ___ ___ are used with numbers to form boolean expressions. there are 6 relational operators and they are always true or false.

num = 10 while num > 0: print ("there are" + str(num) + "green bottles hanging on the wall,") print ("and if 1 green bottle should accidentally fall") num = num - 1 guess = int(input("how many green bottles will be hanging on the wall?")) if (guess == num): print ("There will be"+ str(num) + "green bottles hanging on the wall") else: while guess != num: print ("not try again") guess = int(input("how many green bottles will be hanging on the wall?")) print() #to separate each of the bottles else: print ("There are no more green bottles hanging on the wall")

Using the song "10 green bottles", display the lines "There are [num] green bottles hanging on the wall, [num] green bottles hanging on the wall, and if 1 green bottle should accidentally fall". Then ask the question "how many green bottles will be hanging on the wall?" If the user answers correctly, display the message "There will be [num] green bottles hanging on the wall". If they answer incorrectly, display the message "no try again" until they get it right. When the number of green bottles gets down to 0, display the message "There are no more green bottles hanging on the wall".

index-based for loop and for-each style

What are the 2 for loop styles?

While and For loops

What are the two repetition statements?

With the break statement we can stop the loop even if the while condition is true

What does the break statement do?

With the continue statement we can stop the current iteration, and continue with the next

What does the continue statement do?

HTML Elements are predefined Parsers are forgiving Not suitable for data storage in general XML Elements are user-definable Parsers are strict Suitable for data storage

What is XML and how is it different from HTML?

initialization ex. i = 0 condition while i < 5 increment / decrement i= i + 1

What is the general structure of a while loop?

for loops should be used when the number of repetitions is fixed. In many cases, the number of repetitions a for loop executes for is determined by the number of elements in an array or a list/tuple

When do you use a For Loop?

while loops are used when a block of statements have to be repeated, but the number of repetitions is not a fixed amount. the number of repetitions are often from user input.

When do you use a While Loop?

for x in range(1,100): if x % 2 == 1: print (x) or for x in range (1,100,2): print (x)

Write a for loop that uses the range function to display all odd numbers between 1 and 100.

num = input("Enter an integer greater than 1: ") num = int(num) total = 0 count = 0 for i in range(1,num+1): total = total + i count = count + 1 print("average:",total/count)

Write a program that asks the user to enter an integer greater than 1. The program will calculate the average of the list of numbers going from 1 up to and including the number the user entered. Here are three sample runs of the program Enter an integer greater than 1: 5 average: 3.0 $ python3 question3a.py Enter an integer greater than 1: 10 average: 5.5 $ Enter an integer greater than 1: 20 average: 10.5

mylist = [28,32,47,62,14] print("mylist:",mylist) total = 0 for num in mylist: total = total + num print("average",total*1.0/(len(mylist)))

Write a program that starts with a list of numbers. The program starts by printing out that list. Then, the program uses a for loop to calculate the average value of that list. Here is a sample run of the program: mylist: [28, 32, 47, 62, 14] average 36.6

members = [] moreMembers = True while (moreMembers): member = input("Enter a member's name or leave blank when done: ") member = member.strip() if (member == ""): moreMembers = False else: members.append(member.title()) print(members)

Write a program that uses a while loop to add names of club members into a list. The names should be stored in the title format. The while loop should end when the user enters a blank string for input. After the while loop ends, the program should print the list of members. Here is a sample run:

total = 0 count = 0 done = False while (not done): score = input("Enter a score or 'done' if complete: ") score = score.strip() if (score.lower() == "done"): done = True else: score = float(score) total = total + score count = count + 1 print("Total score:",total) print("Average score:",total/count)

Write a program that uses a while loop to allow entry of some test scores. The while loop should continue until the user enters 'done' instead of a score. After the while loop is completed, the program should print out the total score, and the average score. Here is a sample run of the program

done = False while (not done): entry = input("Enter 'done' to end this loop: ") entry = entry.strip().lower() if (entry == "done"): done = True

Write a program that uses a while loop. This while loop will simply ask the user to enter 'done' to end the while loop. If the user enters anything besides 'done', the while loop will continue. Here is a sample run of the program

celsius = float(input("enter Celsius: ")) fahrenheit = (celsius * 1.8) + 32 print("the farhrenheit temperature is", fahrenheit)

Write a program to convert temperature in Celsius to Fahrenheit. Ask the user for a Celsius temperature and display the Fahrenheit temperature. Fahrenheit (°F) = (Celsius x 1.8) + 32

for number in range(5,0,-1): print str(number) + " ") + number print()

Write a program to print the following pattern 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1

n = 5 for i in range(n, 0, -1): for j in range(i): print(i, end=" ") print()

Write a program to print the following pattern 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1

total = 0 done = False while(not done): num = int(input("enter a number (negaive to end)")) if(num >= 0): total = total + num else: done = True print("the sum is", total)

Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.

filename = input("Enter name of file to write to: ") outfile = open(filename, "w") outfile.write('<?xml version="1.0" ?>\n') outfile.write("<animals>\n") stillEntering = True while stillEntering: name = input("Enter name of animal or 'done' if finished: ") if(name.lower() == "done"): stillEntering = False else: outfile.write(" <animal>" + name + "</animal>\n") outfile.write("</animals>\n")

Writing to XML file using while loop Create a Python program that prompts the user for some input and writes to an output file that is formatted as XML. The program will ask the user to enter an animal or 'done' when done. The animals entered will be written to an XML file. Here is a sample run: Enter name of file to write to: animals.xml Enter name of animal or 'done' if finished: Cat Enter name of animal or 'done' if finished: Dog Enter name of animal or 'done' if finished: Horse Enter name of animal or 'done' if finished: Pig Enter name of animal or 'done' if finished: Cow Enter name of animal or 'done' if finished: done This will produce the following XML file: <?xml version="1.0" ?> <animals> <animal>Cat</animal> <animal>Dog</animal> <animal>Horse</animal> <animal>Pig</animal> <animal>Cow</animal> </animals>

credits = int(credits) + 3 print("Your new credits",credits)

Your new credits 33 what is the input? (the credits were 30 but you are adding 3)

lower()

___ function forces all the letters of the string to be lowercase

Variable

___ is a named storage location for data. Data that is stored in ___ can be used multiple times in a program. Thus, an advantage is reusability without recreation. ____ is represented by a name that usually begins with a letter. For example, x, y, score, interest etc are valid names. Note that ____ names should not have spaces in them and should not begin with a number. _____ cannot be used unless it is given a value. It is assigned a value using the '=' (assignment operator). This operator is the only operator that can assign or change the value of _____

input()

____ function which is designed to pause the program and wait for the user to type in something. ____ function always returns a string unless you change it.

comma

____ operator to combine a literal string with a variable is much more easier than a plus (+). You do not have to do any type of conversions.

append()

adds an element to the end of the list

print("Value of y is" + str(y))

convert y temporarily to a string print("Value of y is " + y)

mylist = [1, 2, 3, 4, 5]

create a list including numbers 1,2,3,4,5 and assign it to mylist

names = [] names.append("jane") names.append("john") names.append("bill") print(names) print(len(names))

create a names list and append "jane" "john" and "bill" then print the length of names output: ['jane', 'john', 'bill'] 3

split() method splits a string into a list John Doe 34

data = "John Doe ,34, 12.00, HCC" print(type(data.split(","))) tokens = data.split(",") print(tokens[0]) print (tokens[1]) what does .split(",") do? print the output:

for i in range(0,len(tokens)): print(tokens[i]) print(type(tokens[i]))

data = "John Doe ,34, 12.00, HCC" print(type(data.split(","))) tokens = data.split(",") print(tokens[0]) print (tokens[1]) write a loop that prints each list item and the data type for each list item

tokens =data.split("|") John Doe Jane Doe Sara Doe

data = "John Doe | Jane Doe | Sara Doe" split the string into a list and name it tokens output:

for i in range(0,len(tokens)): print (tokens[i]) for monkey in tokens: print ("Testing: ", + monkey )

data = "John Doe | Jane Doe | Sara Doe" tokens=data.split("|") write a loop that prints the items in the list write another loop tells us when these test monkeys are in " testing" has the output: Testing: "John Doe" Testing: "Jane Doe" Testing: "Sara Doe"

0 1 2 3 4 5 6 7 8 9

for i in range(0,10): print(i)

0 1 2 3 4 5

for num in range(0,6): print(num,end=' ')

10 9 8 7 6 5 4 3 2

for num in range(10,1,-1): print(num, end=' ')

TypeError: 'float' object cannot be interpreted as an integer cannot increment floats

for num in range(3,20,3.7) print(num, end='')

b a n a n a

for x in "banana": print(x) output:

1 2 3 #if the loop breaks the else is not executed

for x in range(6): if x == 3: break print(x else: print("Finally finished!")

0 2 4

for y in range(0,5,2): print(y, end = ' ')

apple

fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) output:

apple cherry

fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) output:

apple banana

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break output:

apple banana cherry

fruits = ["apple", "banana", "cherry"]for x in fruits: print(x) output:

upper()

he ____ function forces all the letters of the string to be uppercase

the first item has index [0], the second item has index [1] etc.

how are list items indexed?

f = open(filename, mode)

how do you open a file in python for XML?

The element names can be chosen to describe the contents. XML file readable by humans. Modern computer performance allows text files to be accessed sequentially with acceptable performance. Due to strict XML parsers, errors in XML files can be easily detected. This made XML files one of the first successful data formats that can be read by humans and processed by computers.

main reasons why XML files are good for data storage

my_fruits.remove('banana')

my_fruits = ['apple', 'banana', 'cherry']

my_fruits.insert(0, 'cranberry')

my_fruits = ['apple', 'banana', 'cherry'] Insert the fruit "cranberry" at the beginning of my_fruits.

x = my_fruits.index("cherry") output: 2

my_fruits = ['apple', 'banana', 'cherry'] What is the position of the value "cherry"?

true, a list can contain different data types

my_list = [1, "hello", True, 3.14] is this a list true or false? why or why not?

print(len(my_list)) output: 5

my_list = [1, 2, 3, 4, 5] print the length give the output

john doejohn doejohn doejohn doejohn doe string and integer multplied

name = "john doe" print(name*5)

names.append("pearl") names.append("james") the value of stored in position 0 is jane the value of stored in position 1 is bill the value of stored in position 2 is pearl the value stored in position 3 is james

names = ['jane', 'bill'] append the names to the name list: "pearl" "james" # Index-based for loop for i in range(0,len(names)): print("the value stored in position "+str(i)+" is "+names[i]) what is the output:

the value stored in position 0 is jane the value stored in position 1 is bill

names = ['jane', 'john', 'bill'] del names[1] for i in range(0,len(names)): print("the value stored in position "+str(i)+" is "+names[i]) what is the output:

jane bill pearl james

names = [jane, bill, pearl, james] # For each style for loop for name in names: print(name) what is the output:

for index in range(len(names)): print(names[index])

names =["Donald","Daisy","Mickey"] # Items of a list are accessed via index which always starts at 0 print(names[0]) print(names[1]) print(names[2]) #use a loop to make the names spaced output: Donald Daisy Mickey

infile = open("data.txt","r") lines=infile.readlines() print(lines) # For each style for loop #for line in lines: # print(line) #Index-based for loop to process lines for i in range(0,len(lines)): data=lines[i].strip() # The individual data is separated by | tokens=data.split("|") for token in tokens: print(token.strip()) infile.close()

open file in read mode: data.text: John Doe |34 |12.00| HCC Jane Doe | 28 | 13.0| KCC Bill | 40 | 11.50 | WCC use a for loop to print the lines in the data.txt file. what type of for loop is this? then use a for loop to process the lines and then split each item in a list. what type of for loop is this? output: ['John Doe|34|12.00|HCC\n', 'Jane Doe|28|13.0|KCC\n', 'Bill|40|11.50|WCC\n'] John Doe 34 12.00 HCC Jane Doe 28 13.0 KCC Bill 40 11.50 WCC

3 0 1

print(3%5) print(0%5) print(1%5)

0 1

print(5%1) print(5%2)

true

print(5<7)

TypeError: must be str, not int cannot use the + operator to concantenate a string and an integer.

print(name+5)

12.9999 <class 'int'> 12

print(z) z = int(z) print(type(z)) print(z) what is the output? z = 12.999

range(10,0,-1) 10 9 8 7 6 5 4 3 2 1

r = range(10, 0, -1) print(r) for num in r: print(num)

range(3, 7) 3 4 5 6

r = range(3,7) print(r) for num in r: print(num) what is the output?

range(0, 6) 0 1 2 3 4 5

r = range(6) print(r) for num in r: print(num) what is the output?

the element that encloses all the other elements in the XML file. You can choose any name for the root element. Just make sure that the names of the start tag and end tag match ex. two <student> elements inside the root element. Each <student> element contains a <name> element and a <major> element.

root element

< (less than) > (greater than) <= (less than or equal to) >= (greater than or equal to) == (equal to) != (not equal to)

six different relational operators

False. Variables are the only way you can store user input

true or false: Variables are not the only way you can store user input

True

true or false: Variables can be recalled and reused in our code multiple times

total=0 count=0 #Index-based for loop for i in range(0,len(lines)): data=lines[i].strip() #print(data) tokens=data.split("|") # tokens[1] contains age information age = int(tokens[1]) total = total+age count = count+1 if count>0: avg= total/count else: avg=0 print("Average age is "+str(avg))

use a for loop to Calculate the average age of each individual in the file. what kind of for loop is this? put this all together in vscode

animals = ["cat","dog","pig","cow"] for animal in animals: print(animal) print("")

use a loop to print out all the elements in a list, one on each line. using a for-each style for loop here is the output: cat dog pig cow

for i in range(0, len(animals)): print(animals[i])

use a loop to print out all the elements in a list, one on each line. using a index based style for loop here is the output: cat dog pig cow

if (not (num <5 or num > 19)):

using or operator

These are while loops that must run at least one time because the test condition that terminates the while loop is at the end of the while loop.

what are post-test loops?

a pre-test loop checks the terminating condition at the beginning of the while loop. This means that a pre-test while loop may not even execute once.

what are pre-test loops?

HTML: elements are predefined, parsers are forgiving, not suitable for data storage in general XML: elements are user-definable, parsers are strict, suitable for data storage

what are the Key differences between HTML and XML (extensible markup language)?

"r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content "x" - Create - Creates the specified file, returns an error if the file exists

what are the four different methods (modes) for opening a file?

AND, NOT, OR

what are the logical operators

element that encloses all the other elements in the XML file. You can choose any name for the root element. Just make sure that the names of the start tag and end tag match.

what is the root element in XML?

use the for-each style, If the for loop will process all of the elements in the list in the same way

when do you use for-each style for loops?

use the index-based for loop when you want to process only some of the elements in a list, or if the for loop will treat some elements in the list different from other elements

when do you use index-based for loops?

The element names can be chosen to describe the contents. Modern computer performance allows text files to be accessed sequentially with acceptable performance. errors in XML files can be easily detected. This made XML files one of the first successful data formats that can be read by humans and processed by computers.

why are XML files are good for data storage?

<?xml version="1.0" ?>

write XML declaration header

15.714285714285714 integers and floats are allowed. The results are always floats.

x = 5 d =22/7 print(x*d)

print(type(x))

x= 22/7 How do you print the type of a variable x?

False True True True

x=30 y=20 print(x<30 or y<10) z= 80 print(x<30 or y>10 or z==80) print(not(x<30) or y>10) print(x<30 or y>10 and z==80

False False True

x=30 y=20 print(x<30 and y<10) z= 80 print(x<30 and y>10 and z==80) print(not(x<30) and y>10)

# Integer division 2.5 2

x=5 y=2 print(x/y) print(x//y)

False True True False True

x=90 y=56 print(x<y) print(not(x<y)) print(x>=y) print(x==y) print(not(x==y))

names = [] names doneEntering = False while (not doneEntering): name = input("Enter a name, or leave blank when done: ") name = name.strip() if (name == ""): doneEntering = True else: names.append(name) print(names)

you want to write a program that will be asking for the names of all the members in a club. However, we don't know how many members are actually in the club. Thus, once the while loop starts, the while loop will simply repeat until all the member's names have been entered.


Set pelajaran terkait

EA: Business SU 10.1 Partnership Operations and Partner's Taxable Income

View Set

Anatomy and Physiology II: Chapter 19

View Set

IDG1362 Introduksjon til brukersentrert design

View Set

Care for Child With Alteration in Sensory Perception/Disorder of the Eyes or Ears

View Set

Science Extended Response and Short Answer Questions

View Set