Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
60 lines (41 loc) · 1.35 KB
/
Copy pathcode.py
File metadata and controls
60 lines (41 loc) · 1.35 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# -- While loop --
number = 7
play = input("Would you like to play? (Y/n) ")
while play != "n":
user_number = int(input("Guess our number: "))
if user_number == number:
print("You guessed correctly!")
elif abs(number - user_number) == 1:
print("You were off by 1.")
else:
print("Sorry, it's wrong!")
play = input("Would you like to play? (Y/n) ")
# -- The break keyword --
while True:
play = input("Would you like to play? (Y/n) ")
if play == "n":
break # Exit the loop
user_number = int(input("Guess our number: "))
if user_number == number:
print("You guessed correctly!")
elif abs(number - user_number) == 1:
print("You were off by 1.")
else:
print("Sorry, it's wrong!")
# -- For loop --
friends = ["Rolf", "Jen", "Bob", "Anne"]
for friend in friends:
print(f"{friend} is my friend.")
# -- For loop 2 -- Average
grades = [35, 67, 98, 100, 100]
total = 0
amount = len(grades)
for grade in grades:
total += grade
print(total / amount)
# -- Rewritten using sum() --
grades = [35, 67, 98, 100, 100]
total = sum(grades)
amount = len(grades)
print(total / amount)
# You kinda just have to "know" that exists. It takes time and experience, but searching for almost _everything_ really helps. For example, you could've searched for "sum list of numbers python".