Pyton-2: Unterschied zwischen den Versionen
| (12 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt) | |||
| Zeile 72: | Zeile 72: | ||
</pre> | </pre> | ||
= | =012= | ||
Wörter mit mindestens n Zeichen ausgeben und zählen | |||
<pre> | <pre> | ||
# check word length | |||
def count_word(words, min_word_length): | |||
i = 0 | |||
for word in words: | |||
if len(word) >= min_word_length: | |||
print(word) | |||
i = i + 1 | |||
print(f"Total Wörter mit mindestens {min_word_length} Zeichen: {i}") | |||
return i | |||
n = 0 # Gesamttotal aller Wörter | |||
cities = ["Basel", "Bern", "Lausanne", "Zug", "Lugano", "Zürich", "St. Gallen"] | |||
countries = ["Schweiz", "Deutschland", "Italien", "Frankreich"] | |||
n = n + count_word(cities, 6) | |||
print(f"%%%% Total: {n}") | |||
n = n + count_word(countries, 8) | |||
print(f"%%%% Total: {n}") | |||
</pre> | </pre> | ||
= | =013= | ||
Dictionaries | |||
<pre> | <pre> | ||
# dictionaries | |||
nam2nick = {} | |||
nam2nick["Frankreich"] = "F" | |||
nam2nick["Schweiz"] = "CH" | |||
print(nam2nick["Frankreich"]) | |||
print(nam2nick["Schweiz"]) | |||
# loop through | |||
for my_key, my_value in nam2nick.items(): | |||
print(my_key + " : " + my_value) | |||
# or | |||
inventory = { | |||
" apples ": 430, | |||
" bananas ": 312, | |||
} | |||
print(inventory[" apples "]) | |||
# loop through | |||
for my_key, my_value in inventory.items(): | |||
print(f"{my_key} : {my_value}") | |||
# only print keys | |||
for fruit in inventory.keys(): | |||
print(fruit) | |||
# only print values | |||
for value in inventory.values(): | |||
print(value) | |||
</pre> | </pre> | ||
= | =014= | ||
Punktzahl eingeben und danach die Note berechnen | |||
<pre> | <pre> | ||
# Noten berechnen | |||
def calculate_mark(points, max_points): | |||
mark = (points * 5 / max_points) + 1 | |||
return mark | |||
# max value | |||
max_points = float(14) | |||
# loop through input until "exit" is entered | |||
while True: | |||
points = input("how many points?") | |||
if points.lower() == "exit": | |||
break | |||
# check if number within a range is given | |||
try: | |||
float(points) | |||
points = float(points) | |||
if points > max_points: | |||
print(f"max points is {max_points} - you entered {points}. Try again!") | |||
else: | |||
points = float(points) | |||
mark = calculate_mark(points, max_points) | |||
# round to nearst 0.5 | |||
mark_final = round(mark * 2) / 2 | |||
print(mark) | |||
print(mark_final) | |||
except ValueError: | |||
print("Not a float. Enter a number.") | |||
</pre> | </pre> | ||
= | =015= | ||
Noten berechnen. Speichern der Daten in einem dictionary. | |||
<pre> | <pre> | ||
# Noten berechnen | |||
def calculate_mark(points, max_points): | |||
mark = (points * 5 / max_points) + 1 | |||
return mark | |||
= | # max value | ||
max_points = float(14) | |||
# dictionaries | |||
studi_points = {} | |||
# loop through input until "exit" is entered | |||
while True: | |||
student = input("student name or exit to quit: ") | |||
if student.lower() == "exit": | |||
break | |||
points = input("how many points? ") | |||
studi_points[student] = points | |||
# check if number within a range is given | |||
try: | |||
float(points) | |||
points = float(points) | |||
if points > max_points: | |||
print(f"max points is {max_points} - you entered {points}. Try again!") | |||
else: | |||
points = float(points) | |||
mark = calculate_mark(points, max_points) | |||
# round to nearst 0.5 | |||
mark_final = round(mark * 2) / 2 | |||
except ValueError: | |||
print("Not a float. Enter a number.") | |||
for my_key, my_value in studi_points.items(): | |||
print(f"{my_key} : {my_value}") | |||
</pre> | </pre> | ||
= | =016= | ||
Datei Operationen - Zeilen hinzufügen, Datei ausgeben | |||
<pre> | <pre> | ||
# files | |||
# write to a file - append | |||
import time | |||
= | start_time = time.time() | ||
i = 1 | |||
# write a few lines with timestamp | |||
with open("einedatei2.txt", "a") as file: | |||
< | while i <= 10: | ||
file.write(f"hallo {i} - {time.time()}\n") | |||
i += 1 | |||
= | # read the file | ||
with open("einedatei2.txt", "r") as file: | |||
for line in file.readlines(): | |||
# to omit the newline in the file | |||
line = line.strip() | |||
print(line) | |||
# how many lines in file? | |||
file.seek(0) | |||
lines = file.read() | |||
count = lines.splitlines() | |||
print(f"Total lines in file: {len(count)}") | |||
</pre> | </pre> | ||
Aktuelle Version vom 16. November 2024, 16:04 Uhr
008
Lists
# Lists # array von 1 bis 42 lottozahlen = list(range(1, 43)) print(lottozahlen)
009
Lottozahlen generieren
# Zufallszahlen
import random
def my_print(output):
print(output)
print("********")
# range from 1 to 42 / random.sample gives unique elements
lottozahlen = random.sample(range(1, 43), 6)
my_print(lottozahlen)
lottozahlen.sort()
my_print(lottozahlen)
totelemente = len(lottozahlen)
my_print(totelemente)
i = 1
while i <= totelemente:
print(f"zahl {i} {lottozahlen[i - 1]}")
i += 1
010
Reverse String
# reverse a string
def reverse_string(my_string):
# uppercase the string
upper_string = my_string.upper()
# reverse it with slice
reversed = upper_string[::-1]
# how many chars in string?
tot_chars = len(reversed)
i = 0
# loop through all chars
while i < tot_chars:
print(reversed[i])
i += 1
my_string = "Das ist ein Satz."
reverse_string(my_string)
my_string = "Yet another one."
reverse_string(my_string)
011
einfacher for-loop
# simple for loop
teams = ["FCZ", "GC", "YF", "Red Star"]
teams.sort()
for team in teams:
print(team)
012
Wörter mit mindestens n Zeichen ausgeben und zählen
# check word length
def count_word(words, min_word_length):
i = 0
for word in words:
if len(word) >= min_word_length:
print(word)
i = i + 1
print(f"Total Wörter mit mindestens {min_word_length} Zeichen: {i}")
return i
n = 0 # Gesamttotal aller Wörter
cities = ["Basel", "Bern", "Lausanne", "Zug", "Lugano", "Zürich", "St. Gallen"]
countries = ["Schweiz", "Deutschland", "Italien", "Frankreich"]
n = n + count_word(cities, 6)
print(f"%%%% Total: {n}")
n = n + count_word(countries, 8)
print(f"%%%% Total: {n}")
013
Dictionaries
# dictionaries
nam2nick = {}
nam2nick["Frankreich"] = "F"
nam2nick["Schweiz"] = "CH"
print(nam2nick["Frankreich"])
print(nam2nick["Schweiz"])
# loop through
for my_key, my_value in nam2nick.items():
print(my_key + " : " + my_value)
# or
inventory = {
" apples ": 430,
" bananas ": 312,
}
print(inventory[" apples "])
# loop through
for my_key, my_value in inventory.items():
print(f"{my_key} : {my_value}")
# only print keys
for fruit in inventory.keys():
print(fruit)
# only print values
for value in inventory.values():
print(value)
014
Punktzahl eingeben und danach die Note berechnen
# Noten berechnen
def calculate_mark(points, max_points):
mark = (points * 5 / max_points) + 1
return mark
# max value
max_points = float(14)
# loop through input until "exit" is entered
while True:
points = input("how many points?")
if points.lower() == "exit":
break
# check if number within a range is given
try:
float(points)
points = float(points)
if points > max_points:
print(f"max points is {max_points} - you entered {points}. Try again!")
else:
points = float(points)
mark = calculate_mark(points, max_points)
# round to nearst 0.5
mark_final = round(mark * 2) / 2
print(mark)
print(mark_final)
except ValueError:
print("Not a float. Enter a number.")
015
Noten berechnen. Speichern der Daten in einem dictionary.
# Noten berechnen
def calculate_mark(points, max_points):
mark = (points * 5 / max_points) + 1
return mark
# max value
max_points = float(14)
# dictionaries
studi_points = {}
# loop through input until "exit" is entered
while True:
student = input("student name or exit to quit: ")
if student.lower() == "exit":
break
points = input("how many points? ")
studi_points[student] = points
# check if number within a range is given
try:
float(points)
points = float(points)
if points > max_points:
print(f"max points is {max_points} - you entered {points}. Try again!")
else:
points = float(points)
mark = calculate_mark(points, max_points)
# round to nearst 0.5
mark_final = round(mark * 2) / 2
except ValueError:
print("Not a float. Enter a number.")
for my_key, my_value in studi_points.items():
print(f"{my_key} : {my_value}")
016
Datei Operationen - Zeilen hinzufügen, Datei ausgeben
# files
# write to a file - append
import time
start_time = time.time()
i = 1
# write a few lines with timestamp
with open("einedatei2.txt", "a") as file:
while i <= 10:
file.write(f"hallo {i} - {time.time()}\n")
i += 1
# read the file
with open("einedatei2.txt", "r") as file:
for line in file.readlines():
# to omit the newline in the file
line = line.strip()
print(line)
# how many lines in file?
file.seek(0)
lines = file.read()
count = lines.splitlines()
print(f"Total lines in file: {len(count)}")