Einfaches Coding-Problem, das ich nicht lösen kann

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Bänzu
User
Beiträge: 2
Registriert: Montag 18. November 2019, 22:24

Hallo Leute

Ich habe vor ein paar Tagen mit Python-Programming begonnen und ein paar Uebungs-Sets runtergeladen. Leider renne ich schon in Schwierigkeiten... Wie kann man folgende Aufgaben mit Python-Code lösen?


# 1. Write an if statement that checks if user (based on input) is "X"
# and prints out "Welcome X" if so, or "Who are you?" if not.

user = "X"


# 2. Write an if statement that checks both the credentials below
# and prints "Successfully logged in." if they're correct or
# "Invalid username/password combination. Try again." if they're not. Again - base
# this on input from the user

user = "X"
password = "123456"


# 3. Write an if statement that checks whether the value of number is divisible
# by two and prints out "even" if it is and "odd" if it's not.
# (Hint: You can check divisiblity using the modulus (%) operator.
# n % k == 0 evaluates to true if n is an exact multiple of k.)

number = 4


# 4. Create three different lists containing:
# - The names of all your siblings
# - Your top 3 favorite movies
# - The latitude and longitude coordinates of Berlin


# 5. Use a for loop on each of the lists above to print out each element on its own line.


# 6. Use a for loop and the title() function to print out each city name capitalized

cities = ["new york city", "san francisco", "boston", "chicago", "los angeles"]


# 7. A list is different from an element in a list. What's something you can do
# to the second in Python that you can't do to the first, and vice versa?

person = ["James"]
person = "James"


# 8. Use range() and a for loop to print out:
# - the numbers from 1 to 10
# - the square of each of the numbers from 1 to 10
# - for each number from 1 to 10, print out whether it is even or not


# Bonus: In Mathematics, a Marsenne number is a number that is one less than a
# power of two (i.e. 2^n - 1). Starting with an empty list named
# marsenne_numbers (provided for you below), use the append() function inside
# of a for loop so that after the loop has run, marsenne_numbers contains a
# list of the first ten Marsenne numbers.

marsenne_numbers = []
Benutzeravatar
sparrow
User
Beiträge: 4187
Registriert: Freitag 17. April 2009, 10:28

Es ist doch dein Übungsset, also musst du das doch auch lösen. Es wäre ziemlich langweilig, wenn andere das für dich tun.

Zeig doch mal was du schon hast und wo genau du nicht weiter kommst.
Das Python-Tutorial auf python.org hast du durchgearbeitet? Falls nein: Das ist dein perfekter Einstieg.
Bänzu
User
Beiträge: 2
Registriert: Montag 18. November 2019, 22:24

Da hast du recht... Ich hab das Tutorial durchgearbeitet und nun einmal die meisten Aufgaben gelöst. Aufgabe 7 und Bonusfrage kann ich aber nicht lösen, da bin ich überfragt... kannst du helfen?

# 7. A list is different from an element in a list. What's something you can do
# to the second in Python that you can't do to the first, and vice versa?

person = ["Jason"]
person = "Jason"

# Bonus: In Mathematics, a Marsenne number is a number that is one less than a
# power of two (i.e. 2^n - 1). Starting with an empty list named
# marsenne_numbers (provided for you below), use the append() function inside
# of a for loop so that after the loop has run, marsenne_numbers contains a
# list of the first ten Marsenne numbers.

marsenne_numbers = []
Benutzeravatar
ThomasL
User
Beiträge: 1366
Registriert: Montag 14. Mai 2018, 14:44
Wohnort: Kreis Unna NRW

# 1. Write an if statement that checks if user (based on input) is "X"
# and prints out "Welcome X" if so, or "Who are you?" if not.

user = "X"
Wenn das deine Lösung zu Aufgabe 1 ist, hast du diese leider nicht gelöst.
Bei den nachfolgenden ist das größtenteils auch nicht der Fall.
Ich bin Pazifist und greife niemanden an, auch nicht mit Worten.
Für alle meine Code Beispiele gilt: "There is always a better way."
https://projecteuler.net/profile/Brotherluii.png
Jankie
User
Beiträge: 592
Registriert: Mittwoch 26. September 2018, 14:06

Lösung zu Aufgabe 1. würde so aussehen:

Code: Alles auswählen

user = input("User: ")
if user == "X":
    print("Welcome X")
else:
    print("Who are you?")
oder so:

Code: Alles auswählen

print("Welcome X") if input("User: ") == "X" else print("Who are you?")
Sirius3
User
Beiträge: 17741
Registriert: Sonntag 21. Oktober 2012, 17:20

@Jankie: die zweite Lösung ist falsch. Du benutzt ein Konstrukt, das dazu da ist, ein Ergebnis auszurechnen, dazu, eine Programmverzweigung zu verschleiern.
Wenn Du schon alles in eine Zeile packen willst, sähe das so aus:

Code: Alles auswählen

user = input("User:")
print("Welcome X" if user == "X" else "Who are you?")
Jankie
User
Beiträge: 592
Registriert: Mittwoch 26. September 2018, 14:06

Oh danke, das wusste ich nicht.
Benutzeravatar
/me
User
Beiträge: 3555
Registriert: Donnerstag 25. Juni 2009, 14:40
Wohnort: Bonn

Als Einzeiler ginge auch

Code: Alles auswählen

user = input("User:")
print(('Who are you?', 'Welcome X')[user == 'X'])
Beim Programmieren kommt es allerdings nicht darauf an möglichst zeichensparenden Code zu schreiben. Code wird viel häufiger gelesen als geschrieben und daher sollte man eine auf den ersten Blick verständliche Variante wählen. Für mich wäre das in diesem Fall ein if-else über mehrere Zeilen.
Benutzeravatar
__blackjack__
User
Beiträge: 13079
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

Code: Alles auswählen

#!/usr/bin/env python3


def main():
    # 1. Write an if statement that checks if user (based on input) is "X" and
    #    prints out "Welcome X" if so, or "Who are you?" if not.

    # Yeah, I know, no ``if`` statement…
    print("Welcome X" if input("Name? ") == "X" else "Who are you?")

    # 2. Write an if statement that checks both the credentials below and prints
    #    "Successfully logged in." if they're correct or "Invalid
    #    username/password combination. Try again." if they're not. Again - base
    #    this on input from the user

    # And again, no ``if`` statement.
    while not (input("User: ") == "X" and input("Password: ") == "123456"):
        print("Invalid user/password combination. Try again.")
    print("Successfully logged in.")

    # 3. Write an if statement that checks whether the value of number is
    #    divisible by two and prints out "even" if it is and "odd" if it's not.
    #    (Hint: You can check divisiblity using the modulus (%) operator. n % k
    #    == 0 evaluates to true if n is an exact multiple of k.)

    # Guess what…
    number = 4
    print("even" if number % 2 == 0 else "odd")

    # 4. Create three different lists containing:
    #
    #   - The names of all your siblings
    #   - Your top 3 favorite movies
    #   - The latitude and longitude coordinates of Berlin

    # Seriously?  This would even involve personal data from *other* people.
    sibling_names = []
    # At least this is just invading *my* privacy.
    top_3_movies = [
        "Redacted for privacy reasons!",
        "What are you thinking asking this?",
        "███ ████ █ ████",
    ]
    # Yes, that's right: a latitude/longitude pair is *one* item.
    coordinats_of_berlin = [(52.516667, 13.388889)]  # Source: Wikipedia.

    # 5. Use a for loop on each of the lists above to print out each element on
    #    its own line.

    for items in [sibling_names, top_3_movies, coordinats_of_berlin]:
        for item in items:
            print(item)

    # 6. Use a for loop and the title() function to print out each city name
    #    capitalized

    cities = [
        "new york city",
        "san francisco",
        "boston",
        "chicago",
        "los angeles",
    ]
    # Pendantically speaking this is wrong because there is no `title()`
    # function.  At least in Python 3 this isn't solvable without defining a
    # `title()` function first.
    for city in cities:
        print(city.title())

    # 7. A list is different from an element in a list. What's something you can
    #    do to the second in Python that you can't do to the first, and vice
    #    versa?

    # I refuse to answer this one because it is way too vague/broad and in case
    # the list element is itself a list there is no difference at all.
    person = ["James"]
    person = "James"

    # 8. Use range() and a for loop to print out:
    #
    #    - the numbers from 1 to 10
    #    - the square of each of the numbers from 1 to 10
    #    - for each number from 1 to 10, print out whether it is even or not

    # This time I have control over the type of the number, so let's twiddle
    # some bits.
    for i in range(1, 11):
        print(i, i ** 2, "odd" if i & 1 else "even", sep="\t")

    # Bonus: In Mathematics, a Marsenne number is a number that is one less than
    # a power of two (i.e. 2^n - 1). Starting with an empty list named
    # marsenne_numbers (provided for you below), use the append() function
    # inside of a for loop so that after the loop has run, marsenne_numbers
    # contains a list of the first ten Marsenne numbers.

    # More fun at bit level.
    marsenne_numbers = []
    number = 0
    for _ in range(10):
        number = (number << 1) | 1
        marsenne_numbers.append(number)
    print("Mersenne numbers:", marsenne_numbers)


if __name__ == "__main__":
    main()
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
LeSchakal
User
Beiträge: 23
Registriert: Dienstag 5. Februar 2019, 23:40

# 3. Write an if statement that checks whether the value of number is
# divisible by two and prints out "even" if it is and "odd" if it's not.
# (Hint: You can check divisiblity using the modulus (%) operator. n % k
# == 0 evaluates to true if n is an exact multiple of k.)

# Guess what…
number = 4
print("even" if number % 2 == 0 else "odd")
Oder auch:

Code: Alles auswählen

if True:
    print(['even', 'odd'][number % 2])
Benutzeravatar
__blackjack__
User
Beiträge: 13079
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@LeSchakal: Was ich als Verschleierungsversuch sehen würde den normalen Weg zu gehen. In der Regel wird in Python neue Syntax nur hinzugefügt wenn dadurch etwas neues möglich ist, oder aber die Lesbarkeit verbessert wird. Beim bedingten Ausdruck hat sich Guido eine ganze Weile gesträubt, hat dann aber doch gesehen das die Hacks die die Leute stattdessen schreiben doch neue Syntax rechtfertigen.
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Sirius3
User
Beiträge: 17741
Registriert: Sonntag 21. Oktober 2012, 17:20

Die Schreibweise, vor es den if-else-Ausdruck gab war übrigens:

Code: Alles auswählen

print(number % 2 and "odd" or "even")
Da muß man wissen, was dieses Konstrukt eigentlich bewirken soll, um es flüssig lesen zu können, und dann muß man noch prüfen, ob die Ausnahmen hier nicht gelten, dass also der mittlere Ausdruck nicht auch zu False im boolschen Kontext evaluiert werden kann.
Antworten